@opentiny/next-sdk 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,56 +1,56 @@
1
- (function(Oe,rn){typeof exports=="object"&&typeof module<"u"?rn(exports):typeof define=="function"&&define.amd?define(["exports"],rn):(Oe=typeof globalThis<"u"?globalThis:Oe||self,rn(Oe.WebMCP={}))})(this,(function(Oe){"use strict";function rn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Po={exports:{}},Zi={},_r={},nn={},Fi={},Vi={},Hi={},kd;function Oo(){return kd||(kd=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(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((_,b)=>`${_}${b}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((_,b)=>(b instanceof r&&(_[b.str]=(_[b.str]||0)+1),_),{})}}t._Code=n,t.nil=new n("");function s(w,...y){const _=[w[0]];let b=0;for(;b<y.length;)i(_,y[b]),_.push(w[++b]);return new n(_)}t._=s;const o=new n("+");function a(w,...y){const _=[d(w[0])];let b=0;for(;b<y.length;)_.push(o),i(_,y[b]),_.push(o,d(w[++b]));return c(_),new n(_)}t.str=a;function i(w,y){y instanceof n?w.push(...y._items):y instanceof r?w.push(y):w.push(p(y))}t.addCodeArg=i;function c(w){let y=1;for(;y<w.length-1;){if(w[y]===o){const _=l(w[y-1],w[y+1]);if(_!==void 0){w.splice(y-1,3,_);continue}w[y++]="+"}y++}}function l(w,y){if(y==='""')return w;if(w==='""')return y;if(typeof w=="string")return y instanceof r||w[w.length-1]!=='"'?void 0:typeof y!="string"?`${w.slice(0,-1)}${y}"`:y[0]==='"'?w.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(w instanceof r))return`"${w}${y.slice(1)}`}function u(w,y){return y.emptyStr()?w:w.emptyStr()?y:a`${w}${y}`}t.strConcat=u;function p(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:d(Array.isArray(w)?w.join(","):w)}function h(w){return new n(d(w))}t.stringify=h;function d(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function f(w){return typeof w=="string"&&t.IDENTIFIER.test(w)?new n(`.${w}`):s`[${w}]`}t.getProperty=f;function v(w){if(typeof w=="string"&&t.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}t.getEsmExportName=v;function g(w){return new n(w.toString())}t.regexpCode=g})(Hi)),Hi}var Bi={},Sd;function Td(){return Sd||(Sd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=Oo();class r extends Error{constructor(l){super(`CodeGen: "code" for ${l} not defined`),this.value=l.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:l,parent:u}={}){this._names={},this._prefixes=l,this._parent=u}toName(l){return l instanceof e.Name?l:this.name(l)}name(l){return new e.Name(this._newName(l))}_newName(l){const u=this._names[l]||this._nameGroup(l);return`${l}${u.index++}`}_nameGroup(l){var u,p;if(!((p=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||p===void 0)&&p.has(l)||this._prefixes&&!this._prefixes.has(l))throw new Error(`CodeGen: prefix "${l}" is not allowed in this scope`);return this._names[l]={prefix:l,index:0}}}t.Scope=s;class o extends e.Name{constructor(l,u){super(u),this.prefix=l}setValue(l,{property:u,itemIndex:p}){this.value=l,this.scopePath=(0,e._)`.${new e.Name(u)}[${p}]`}}t.ValueScopeName=o;const a=(0,e._)`\n`;class i extends s{constructor(l){super(l),this._values={},this._scope=l.scope,this.opts={...l,_n:l.lines?a:e.nil}}get(){return this._scope}name(l){return new o(l,this._newName(l))}value(l,u){var p;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(l),{prefix:d}=h,f=(p=u.key)!==null&&p!==void 0?p:u.ref;let v=this._values[d];if(v){const y=v.get(f);if(y)return y}else v=this._values[d]=new Map;v.set(f,h);const g=this._scope[d]||(this._scope[d]=[]),w=g.length;return g[w]=u.ref,h.setValue(u,{property:d,itemIndex:w}),h}getValue(l,u){const p=this._values[l];if(p)return p.get(u)}scopeRefs(l,u=this._values){return this._reduceValues(u,p=>{if(p.scopePath===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return(0,e._)`${l}${p.scopePath}`})}scopeCode(l=this._values,u,p){return this._reduceValues(l,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,p)}_reduceValues(l,u,p={},h){let d=e.nil;for(const f in l){const v=l[f];if(!v)continue;const g=p[f]=p[f]||new Map;v.forEach(w=>{if(g.has(w))return;g.set(w,n.Started);let y=u(w);if(y){const _=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${_} ${w} = ${y};${this.opts._n}`}else if(y=h?.(w))d=(0,e._)`${d}${y}${this.opts._n}`;else throw new r(w);g.set(w,n.Completed)})}return d}}t.ValueScope=i})(Bi)),Bi}var Cd;function Ce(){return Cd||(Cd=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=Oo(),r=Td();var n=Oo();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=Td();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 o{optimizeNodes(){return this}optimizeNames(E,I){return this}}class a extends o{constructor(E,I,$){super(),this.varKind=E,this.name=I,this.rhs=$}render({es5:E,_n:I}){const $=E?r.varKinds.var:this.varKind,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${B};`+I}optimizeNames(E,I){if(E[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,E,I)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(E,I,$){super(),this.lhs=E,this.rhs=I,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,I){if(!(this.lhs instanceof e.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,E,I),this}get names(){const E=this.lhs instanceof e.Name?{}:{...this.lhs.names};return U(E,this.rhs)}}class c extends i{constructor(E,I,$,B){super(E,$,B),this.op=I}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class l extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class p extends o{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends o{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,I){return this.code=V(this.code,E,I),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends o{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((I,$)=>I+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let I=E.length;for(;I--;){const $=E[I].optimizeNodes();Array.isArray($)?E.splice(I,1,...$):$?E[I]=$:E.splice(I,1)}return E.length>0?this:void 0}optimizeNames(E,I){const{nodes:$}=this;let B=$.length;for(;B--;){const W=$[B];W.optimizeNames(E,I)||(ne(E,W.names),$.splice(B,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,I)=>D(E,I.names),{})}}class f extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends d{}class g extends f{}g.kind="else";class w extends f{constructor(E,I){super(I),this.condition=E}render(E){let I=`if(${this.condition})`+super.render(E);return this.else&&(I+="else "+this.else.render(E)),I}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let I=this.else;if(I){const $=I.optimizeNodes();I=this.else=Array.isArray($)?new g($):$}if(I)return E===!1?I instanceof w?I:I.nodes:this.nodes.length?this:new w(fe(E),I instanceof w?[I]:I.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,I){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,I),!!(super.optimizeNames(E,I)||this.else))return this.condition=V(this.condition,E,I),this}get names(){const E=super.names;return U(E,this.condition),this.else&&D(E,this.else.names),E}}w.kind="if";class y extends f{}y.kind="for";class _ extends y{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,I){if(super.optimizeNames(E,I))return this.iteration=V(this.iteration,E,I),this}get names(){return D(super.names,this.iteration.names)}}class b extends y{constructor(E,I,$,B){super(),this.varKind=E,this.name=I,this.from=$,this.to=B}render(E){const I=E.es5?r.varKinds.var:this.varKind,{name:$,from:B,to:W}=this;return`for(${I} ${$}=${B}; ${$}<${W}; ${$}++)`+super.render(E)}get names(){const E=U(super.names,this.from);return U(E,this.to)}}class k extends y{constructor(E,I,$,B){super(),this.loop=E,this.varKind=I,this.name=$,this.iterable=B}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,I){if(super.optimizeNames(E,I))return this.iterable=V(this.iterable,E,I),this}get names(){return D(super.names,this.iterable.names)}}class S extends f{constructor(E,I,$){super(),this.name=E,this.args=I,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class T extends d{render(E){return"return "+super.render(E)}}T.kind="return";class x extends f{render(E){let I="try"+super.render(E);return this.catch&&(I+=this.catch.render(E)),this.finally&&(I+=this.finally.render(E)),I}optimizeNodes(){var E,I;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(I=this.finally)===null||I===void 0||I.optimizeNodes(),this}optimizeNames(E,I){var $,B;return super.optimizeNames(E,I),($=this.catch)===null||$===void 0||$.optimizeNames(E,I),(B=this.finally)===null||B===void 0||B.optimizeNames(E,I),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class R extends f{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}R.kind="catch";class j extends f{render(E){return"finally"+super.render(E)}}j.kind="finally";class O{constructor(E,I={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...I,_n:I.lines?`
2
- `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,I){const $=this._extScope.value(E,I);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,I){return this._extScope.getValue(E,I)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,I,$,B){const W=this._scope.toName(I);return $!==void 0&&B&&(this._constants[W.str]=$),this._leafNode(new a(E,W,$)),W}const(E,I,$){return this._def(r.varKinds.const,E,I,$)}let(E,I,$){return this._def(r.varKinds.let,E,I,$)}var(E,I,$){return this._def(r.varKinds.var,E,I,$)}assign(E,I,$){return this._leafNode(new i(E,I,$))}add(E,I){return this._leafNode(new c(E,t.operators.ADD,I))}code(E){return typeof E=="function"?E():E!==e.nil&&this._leafNode(new h(E)),this}object(...E){const I=["{"];for(const[$,B]of E)I.length>1&&I.push(","),I.push($),($!==B||this.opts.es5)&&(I.push(":"),(0,e.addCodeArg)(I,B));return I.push("}"),new e._Code(I)}if(E,I,$){if(this._blockNode(new w(E)),I&&$)this.code(I).else().code($).endIf();else if(I)this.code(I).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(w,g)}_for(E,I){return this._blockNode(E),I&&this.code(I).endFor(),this}for(E,I){return this._for(new _(E),I)}forRange(E,I,$,B,W=this.opts.es5?r.varKinds.var:r.varKinds.let){const _e=this._scope.toName(E);return this._for(new b(W,_e,I,$),()=>B(_e))}forOf(E,I,$,B=r.varKinds.const){const W=this._scope.toName(E);if(this.opts.es5){const _e=I instanceof e.Name?I:this.var("_arr",I);return this.forRange("_i",0,(0,e._)`${_e}.length`,pe=>{this.var(W,(0,e._)`${_e}[${pe}]`),$(W)})}return this._for(new k("of",B,W,I),()=>$(W))}forIn(E,I,$,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,e._)`Object.keys(${I})`,$);const W=this._scope.toName(E);return this._for(new k("in",B,W,I),()=>$(W))}endFor(){return this._endBlockNode(y)}label(E){return this._leafNode(new l(E))}break(E){return this._leafNode(new u(E))}return(E){const I=new T;if(this._blockNode(I),this.code(E),I.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(E,I,$){if(!I&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new x;if(this._blockNode(B),this.code(E),I){const W=this.name("e");this._currNode=B.catch=new R(W),I(W)}return $&&(this._currNode=B.finally=new j,this.code($)),this._endBlockNode(R,j)}throw(E){return this._leafNode(new p(E))}block(E,I){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(I),this}endBlock(E){const I=this._blockStarts.pop();if(I===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-I;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=I,this}func(E,I=e.nil,$,B){return this._blockNode(new S(E,I,$)),B&&this.code(B).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,I){const $=this._currNode;if($ instanceof E||I&&$ instanceof I)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${I?`${E.kind}/${I.kind}`:E.kind}"`)}_elseNode(E){const I=this._currNode;if(!(I instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=I.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const I=this._nodes;I[I.length-1]=E}}t.CodeGen=O;function D(q,E){for(const I in E)q[I]=(q[I]||0)+(E[I]||0);return q}function U(q,E){return E instanceof e._CodeOrName?D(q,E.names):q}function V(q,E,I){if(q instanceof e.Name)return $(q);if(!B(q))return q;return new e._Code(q._items.reduce((W,_e)=>(_e instanceof e.Name&&(_e=$(_e)),_e instanceof e._Code?W.push(..._e._items):W.push(_e),W),[]));function $(W){const _e=I[W.str];return _e===void 0||E[W.str]!==1?W:(delete E[W.str],_e)}function B(W){return W instanceof e._Code&&W._items.some(_e=>_e instanceof e.Name&&E[_e.str]===1&&I[_e.str]!==void 0)}}function ne(q,E){for(const I in E)q[I]=(q[I]||0)-(E[I]||0)}function fe(q){return typeof q=="boolean"||typeof q=="number"||q===null?!q:(0,e._)`!${F(q)}`}t.not=fe;const de=P(t.operators.AND);function te(...q){return q.reduce(de)}t.and=te;const ye=P(t.operators.OR);function H(...q){return q.reduce(ye)}t.or=H;function P(q){return(E,I)=>E===e.nil?I:I===e.nil?E:(0,e._)`${F(E)} ${q} ${F(I)}`}function F(q){return q instanceof e.Name?q:(0,e._)`(${q})`}})(Vi)),Vi}var $e={},$d;function Ae(){if($d)return $e;$d=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.checkStrictMode=$e.getErrorPath=$e.Type=$e.useFunc=$e.setEvaluated=$e.evaluatedPropsToName=$e.mergeEvaluated=$e.eachItem=$e.unescapeJsonPointer=$e.escapeJsonPointer=$e.escapeFragment=$e.unescapeFragment=$e.schemaRefOrVal=$e.schemaHasRulesButRef=$e.schemaHasRules=$e.checkUnknownRules=$e.alwaysValidSchema=$e.toHash=void 0;const t=Ce(),e=Oo();function r(k){const S={};for(const T of k)S[T]=!0;return S}$e.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(s(k,S),!o(S,k.self.RULES.all))}$e.alwaysValidSchema=n;function s(k,S=k.schema){const{opts:T,self:x}=k;if(!T.strictSchema||typeof S=="boolean")return;const R=x.RULES.keywords;for(const j in S)R[j]||b(k,`unknown keyword: "${j}"`)}$e.checkUnknownRules=s;function o(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(S[T])return!0;return!1}$e.schemaHasRules=o;function a(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(T!=="$ref"&&S.all[T])return!0;return!1}$e.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},T,x,R){if(!R){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,t._)`${T}`}return(0,t._)`${k}${S}${(0,t.getProperty)(x)}`}$e.schemaRefOrVal=i;function c(k){return p(decodeURIComponent(k))}$e.unescapeFragment=c;function l(k){return encodeURIComponent(u(k))}$e.escapeFragment=l;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}$e.escapeJsonPointer=u;function p(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}$e.unescapeJsonPointer=p;function h(k,S){if(Array.isArray(k))for(const T of k)S(T);else S(k)}$e.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:T,resultToName:x}){return(R,j,O,D)=>{const U=O===void 0?j:O instanceof t.Name?(j instanceof t.Name?k(R,j,O):S(R,j,O),O):j instanceof t.Name?(S(R,O,j),j):T(j,O);return D===t.Name&&!(U instanceof t.Name)?x(R,U):U}}$e.mergeEvaluated={props:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>{k.if((0,t._)`${S} === true`,()=>k.assign(T,!0),()=>k.assign(T,(0,t._)`${T} || {}`).code((0,t._)`Object.assign(${T}, ${S})`))}),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>{S===!0?k.assign(T,!0):(k.assign(T,(0,t._)`${T} || {}`),v(k,T,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:f}),items:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>k.assign(T,(0,t._)`${S} === true ? true : ${T} > ${S} ? ${T} : ${S}`)),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>k.assign(T,S===!0?!0:(0,t._)`${T} > ${S} ? ${T} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function f(k,S){if(S===!0)return k.var("props",!0);const T=k.var("props",(0,t._)`{}`);return S!==void 0&&v(k,T,S),T}$e.evaluatedPropsToName=f;function v(k,S,T){Object.keys(T).forEach(x=>k.assign((0,t._)`${S}${(0,t.getProperty)(x)}`,!0))}$e.setEvaluated=v;const g={};function w(k,S){return k.scopeValue("func",{ref:S,code:g[S.code]||(g[S.code]=new e._Code(S.code))})}$e.useFunc=w;var y;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(y||($e.Type=y={}));function _(k,S,T){if(k instanceof t.Name){const x=S===y.Num;return T?x?(0,t._)`"[" + ${k} + "]"`:(0,t._)`"['" + ${k} + "']"`:x?(0,t._)`"/" + ${k}`:(0,t._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,t.getProperty)(k).toString():"/"+u(k)}$e.getErrorPath=_;function b(k,S,T=k.opts.strictSchema){if(T){if(S=`strict mode: ${S}`,T===!0)throw new Error(S);k.self.logger.warn(S)}}return $e.checkStrictMode=b,$e}var Ao={},Ed;function Lr(){if(Ed)return Ao;Ed=1,Object.defineProperty(Ao,"__esModule",{value:!0});const t=Ce(),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 Ao.default=e,Ao}var xd;function Mo(){return xd||(xd=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=Ce(),r=Ae(),n=Lr();t.keywordError={message:({keyword:g})=>(0,e.str)`must pass "${g}" keyword validation`},t.keyword$DataError={message:({keyword:g,schemaType:w})=>w?(0,e.str)`"${g}" keyword must be ${w} ($data)`:(0,e.str)`"${g}" keyword is invalid ($data)`};function s(g,w=t.keywordError,y,_){const{it:b}=g,{gen:k,compositeRule:S,allErrors:T}=b,x=p(g,w,y);_??(S||T)?c(k,x):l(b,(0,e._)`[${x}]`)}t.reportError=s;function o(g,w=t.keywordError,y){const{it:_}=g,{gen:b,compositeRule:k,allErrors:S}=_,T=p(g,w,y);c(b,T),k||S||l(_,n.default.vErrors)}t.reportExtraError=o;function a(g,w){g.assign(n.default.errors,w),g.if((0,e._)`${n.default.vErrors} !== null`,()=>g.if(w,()=>g.assign((0,e._)`${n.default.vErrors}.length`,w),()=>g.assign(n.default.vErrors,null)))}t.resetErrorsCount=a;function i({gen:g,keyword:w,schemaValue:y,data:_,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=g.name("err");g.forRange("i",b,n.default.errors,T=>{g.const(S,(0,e._)`${n.default.vErrors}[${T}]`),g.if((0,e._)`${S}.instancePath === undefined`,()=>g.assign((0,e._)`${S}.instancePath`,(0,e.strConcat)(n.default.instancePath,k.errorPath))),g.assign((0,e._)`${S}.schemaPath`,(0,e.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(g.assign((0,e._)`${S}.schema`,y),g.assign((0,e._)`${S}.data`,_))})}t.extendErrors=i;function c(g,w){const y=g.const("err",w);g.if((0,e._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${n.default.vErrors}.push(${y})`),g.code((0,e._)`${n.default.errors}++`)}function l(g,w){const{gen:y,validateName:_,schemaEnv:b}=g;b.$async?y.throw((0,e._)`new ${g.ValidationError}(${w})`):(y.assign((0,e._)`${_}.errors`,w),y.return(!1))}const u={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(g,w,y){const{createErrors:_}=g.it;return _===!1?(0,e._)`{}`:h(g,w,y)}function h(g,w,y={}){const{gen:_,it:b}=g,k=[d(b,y),f(g,y)];return v(g,w,k),_.object(...k)}function d({errorPath:g},{instancePath:w}){const y=w?(0,e.str)`${g}${(0,r.getErrorPath)(w,r.Type.Str)}`:g;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,y)]}function f({keyword:g,it:{errSchemaPath:w}},{schemaPath:y,parentSchema:_}){let b=_?w:(0,e.str)`${w}/${g}`;return y&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(y,r.Type.Str)}`),[u.schemaPath,b]}function v(g,{params:w,message:y},_){const{keyword:b,data:k,schemaValue:S,it:T}=g,{opts:x,propertyName:R,topSchemaRef:j,schemaPath:O}=T;_.push([u.keyword,b],[u.params,typeof w=="function"?w(g):w||(0,e._)`{}`]),x.messages&&_.push([u.message,typeof y=="function"?y(g):y]),x.verbose&&_.push([u.schema,S],[u.parentSchema,(0,e._)`${j}${O}`],[n.default.data,k]),R&&_.push([u.propertyName,R])}})(Fi)),Fi}var Id;function T_(){if(Id)return nn;Id=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.boolOrEmptySchema=nn.topBoolOrEmptySchema=void 0;const t=Mo(),e=Ce(),r=Lr(),n={message:"boolean schema is false"};function s(i){const{gen:c,schema:l,validateName:u}=i;l===!1?a(i,!1):typeof l=="object"&&l.$async===!0?c.return(r.default.data):(c.assign((0,e._)`${u}.errors`,null),c.return(!0))}nn.topBoolOrEmptySchema=s;function o(i,c){const{gen:l,schema:u}=i;u===!1?(l.var(c,!1),a(i)):l.var(c,!0)}nn.boolOrEmptySchema=o;function a(i,c){const{gen:l,data:u}=i,p={gen:l,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,t.reportError)(p,n,void 0,c)}return nn}var nt={},sn={},Rd;function Pd(){if(Rd)return sn;Rd=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.getRules=sn.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)}sn.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 sn.getRules=n,sn}var vr={},Od;function Ad(){if(Od)return vr;Od=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.shouldUseRule=vr.shouldUseGroup=vr.schemaHasRulesForType=void 0;function t({schema:n,self:s},o){const a=s.RULES.types[o];return a&&a!==!0&&e(n,a)}vr.schemaHasRulesForType=t;function e(n,s){return s.rules.some(o=>r(n,o))}vr.shouldUseGroup=e;function r(n,s){var o;return n[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>n[a]!==void 0))}return vr.shouldUseRule=r,vr}var Md;function No(){if(Md)return nt;Md=1,Object.defineProperty(nt,"__esModule",{value:!0}),nt.reportTypeError=nt.checkDataTypes=nt.checkDataType=nt.coerceAndCheckDataType=nt.getJSONTypes=nt.getSchemaTypes=nt.DataType=void 0;const t=Pd(),e=Ad(),r=Mo(),n=Ce(),s=Ae();var o;(function(y){y[y.Correct=0]="Correct",y[y.Wrong=1]="Wrong"})(o||(nt.DataType=o={}));function a(y){const _=i(y.type);if(_.includes("null")){if(y.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!_.length&&y.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');y.nullable===!0&&_.push("null")}return _}nt.getSchemaTypes=a;function i(y){const _=Array.isArray(y)?y:y?[y]:[];if(_.every(t.isJSONType))return _;throw new Error("type must be JSONType or JSONType[]: "+_.join(","))}nt.getJSONTypes=i;function c(y,_){const{gen:b,data:k,opts:S}=y,T=u(_,S.coerceTypes),x=_.length>0&&!(T.length===0&&_.length===1&&(0,e.schemaHasRulesForType)(y,_[0]));if(x){const R=f(_,k,S.strictNumbers,o.Wrong);b.if(R,()=>{T.length?p(y,_,T):g(y)})}return x}nt.coerceAndCheckDataType=c;const l=new Set(["string","number","integer","boolean","null"]);function u(y,_){return _?y.filter(b=>l.has(b)||_==="array"&&b==="array"):[]}function p(y,_,b){const{gen:k,data:S,opts:T}=y,x=k.let("dataType",(0,n._)`typeof ${S}`),R=k.let("coerced",(0,n._)`undefined`);T.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(x,(0,n._)`typeof ${S}`).if(f(_,S,T.strictNumbers),()=>k.assign(R,S))),k.if((0,n._)`${R} !== undefined`);for(const O of b)(l.has(O)||O==="array"&&T.coerceTypes==="array")&&j(O);k.else(),g(y),k.endIf(),k.if((0,n._)`${R} !== undefined`,()=>{k.assign(S,R),h(y,R)});function j(O){switch(O){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(R,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(R,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${S} === null
3
- || (${x} == "string" && ${S} && ${S} == +${S})`).assign(R,(0,n._)`+${S}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${S} === null
4
- || (${x} === "string" && ${S} && ${S} == +${S} && !(${S} % 1))`).assign(R,(0,n._)`+${S}`);return;case"boolean":k.elseIf((0,n._)`${S} === "false" || ${S} === 0 || ${S} === null`).assign(R,!1).elseIf((0,n._)`${S} === "true" || ${S} === 1`).assign(R,!0);return;case"null":k.elseIf((0,n._)`${S} === "" || ${S} === 0 || ${S} === false`),k.assign(R,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
5
- || ${x} === "boolean" || ${S} === null`).assign(R,(0,n._)`[${S}]`)}}}function h({gen:y,parentData:_,parentDataProperty:b},k){y.if((0,n._)`${_} !== undefined`,()=>y.assign((0,n._)`${_}[${b}]`,k))}function d(y,_,b,k=o.Correct){const S=k===o.Correct?n.operators.EQ:n.operators.NEQ;let T;switch(y){case"null":return(0,n._)`${_} ${S} null`;case"array":T=(0,n._)`Array.isArray(${_})`;break;case"object":T=(0,n._)`${_} && typeof ${_} == "object" && !Array.isArray(${_})`;break;case"integer":T=x((0,n._)`!(${_} % 1) && !isNaN(${_})`);break;case"number":T=x();break;default:return(0,n._)`typeof ${_} ${S} ${y}`}return k===o.Correct?T:(0,n.not)(T);function x(R=n.nil){return(0,n.and)((0,n._)`typeof ${_} == "number"`,R,b?(0,n._)`isFinite(${_})`:n.nil)}}nt.checkDataType=d;function f(y,_,b,k){if(y.length===1)return d(y[0],_,b,k);let S;const T=(0,s.toHash)(y);if(T.array&&T.object){const x=(0,n._)`typeof ${_} != "object"`;S=T.null?x:(0,n._)`!${_} || ${x}`,delete T.null,delete T.array,delete T.object}else S=n.nil;T.number&&delete T.integer;for(const x in T)S=(0,n.and)(S,d(x,_,b,k));return S}nt.checkDataTypes=f;const v={message:({schema:y})=>`must be ${y}`,params:({schema:y,schemaValue:_})=>typeof y=="string"?(0,n._)`{type: ${y}}`:(0,n._)`{type: ${_}}`};function g(y){const _=w(y);(0,r.reportError)(_,v)}nt.reportTypeError=g;function w(y){const{gen:_,data:b,schema:k}=y,S=(0,s.schemaRefOrVal)(y,k,"type");return{gen:_,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:y}}return nt}var fs={},Nd;function C_(){if(Nd)return fs;Nd=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.assignDefaults=void 0;const t=Ce(),e=Ae();function r(s,o){const{properties:a,items:i}=s.schema;if(o==="object"&&a)for(const c in a)n(s,c,a[c].default);else o==="array"&&Array.isArray(i)&&i.forEach((c,l)=>n(s,l,c.default))}fs.assignDefaults=r;function n(s,o,a){const{gen:i,compositeRule:c,data:l,opts:u}=s;if(a===void 0)return;const p=(0,t._)`${l}${(0,t.getProperty)(o)}`;if(c){(0,e.checkStrictMode)(s,`default is ignored for: ${p}`);return}let h=(0,t._)`${p} === undefined`;u.useDefaults==="empty"&&(h=(0,t._)`${h} || ${p} === null || ${p} === ""`),i.if(h,(0,t._)`${p} = ${(0,t.stringify)(a)}`)}return fs}var Ft={},je={},Ld;function Vt(){if(Ld)return je;Ld=1,Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const t=Ce(),e=Ae(),r=Lr(),n=Ae();function s(y,_){const{gen:b,data:k,it:S}=y;b.if(u(b,k,_,S.opts.ownProperties),()=>{y.setParams({missingProperty:(0,t._)`${_}`},!0),y.error()})}je.checkReportMissingProp=s;function o({gen:y,data:_,it:{opts:b}},k,S){return(0,t.or)(...k.map(T=>(0,t.and)(u(y,_,T,b.ownProperties),(0,t._)`${S} = ${T}`)))}je.checkMissingProp=o;function a(y,_){y.setParams({missingProperty:_},!0),y.error()}je.reportMissingProp=a;function i(y){return y.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=i;function c(y,_,b){return(0,t._)`${i(y)}.call(${_}, ${b})`}je.isOwnProperty=c;function l(y,_,b,k){const S=(0,t._)`${_}${(0,t.getProperty)(b)} !== undefined`;return k?(0,t._)`${S} && ${c(y,_,b)}`:S}je.propertyInData=l;function u(y,_,b,k){const S=(0,t._)`${_}${(0,t.getProperty)(b)} === undefined`;return k?(0,t.or)(S,(0,t.not)(c(y,_,b))):S}je.noPropertyInData=u;function p(y){return y?Object.keys(y).filter(_=>_!=="__proto__"):[]}je.allSchemaProperties=p;function h(y,_){return p(_).filter(b=>!(0,e.alwaysValidSchema)(y,_[b]))}je.schemaProperties=h;function d({schemaCode:y,data:_,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:T},it:x},R,j,O){const D=O?(0,t._)`${y}, ${_}, ${k}${S}`:_,U=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,T)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const V=(0,t._)`${D}, ${b.object(...U)}`;return j!==t.nil?(0,t._)`${R}.call(${j}, ${V})`:(0,t._)`${R}(${V})`}je.callValidateCode=d;const f=(0,t._)`new RegExp`;function v({gen:y,it:{opts:_}},b){const k=_.unicodeRegExp?"u":"",{regExp:S}=_.code,T=S(b,k);return y.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,t._)`${S.code==="new RegExp"?f:(0,n.useFunc)(y,S)}(${b}, ${k})`})}je.usePattern=v;function g(y){const{gen:_,data:b,keyword:k,it:S}=y,T=_.name("valid");if(S.allErrors){const R=_.let("valid",!0);return x(()=>_.assign(R,!1)),R}return _.var(T,!0),x(()=>_.break()),T;function x(R){const j=_.const("len",(0,t._)`${b}.length`);_.forRange("i",0,j,O=>{y.subschema({keyword:k,dataProp:O,dataPropType:e.Type.Num},T),_.if((0,t.not)(T),R)})}}je.validateArray=g;function w(y){const{gen:_,schema:b,keyword:k,it:S}=y;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(j=>(0,e.alwaysValidSchema)(S,j))&&!S.opts.unevaluated)return;const x=_.let("valid",!1),R=_.name("_valid");_.block(()=>b.forEach((j,O)=>{const D=y.subschema({keyword:k,schemaProp:O,compositeRule:!0},R);_.assign(x,(0,t._)`${x} || ${R}`),y.mergeValidEvaluated(D,R)||_.if((0,t.not)(x))})),y.result(x,()=>y.reset(),()=>y.error(!0))}return je.validateUnion=w,je}var jd;function $_(){if(jd)return Ft;jd=1,Object.defineProperty(Ft,"__esModule",{value:!0}),Ft.validateKeywordUsage=Ft.validSchemaType=Ft.funcKeywordCode=Ft.macroKeywordCode=void 0;const t=Ce(),e=Lr(),r=Vt(),n=Mo();function s(h,d){const{gen:f,keyword:v,schema:g,parentSchema:w,it:y}=h,_=d.macro.call(y.self,g,w,y),b=l(f,v,_);y.opts.validateSchema!==!1&&y.self.validateSchema(_,!0);const k=f.name("valid");h.subschema({schema:_,schemaPath:t.nil,errSchemaPath:`${y.errSchemaPath}/${v}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Ft.macroKeywordCode=s;function o(h,d){var f;const{gen:v,keyword:g,schema:w,parentSchema:y,$data:_,it:b}=h;c(b,d);const k=!_&&d.compile?d.compile.call(b.self,w,y,b):d.validate,S=l(v,g,k),T=v.let("valid");h.block$data(T,x),h.ok((f=d.valid)!==null&&f!==void 0?f:T);function x(){if(d.errors===!1)O(),d.modifying&&a(h),D(()=>h.error());else{const U=d.async?R():j();d.modifying&&a(h),D(()=>i(h,U))}}function R(){const U=v.let("ruleErrs",null);return v.try(()=>O((0,t._)`await `),V=>v.assign(T,!1).if((0,t._)`${V} instanceof ${b.ValidationError}`,()=>v.assign(U,(0,t._)`${V}.errors`),()=>v.throw(V))),U}function j(){const U=(0,t._)`${S}.errors`;return v.assign(U,null),O(t.nil),U}function O(U=d.async?(0,t._)`await `:t.nil){const V=b.opts.passContext?e.default.this:e.default.self,ne=!("compile"in d&&!_||d.schema===!1);v.assign(T,(0,t._)`${U}${(0,r.callValidateCode)(h,S,V,ne)}`,d.modifying)}function D(U){var V;v.if((0,t.not)((V=d.valid)!==null&&V!==void 0?V:T),U)}}Ft.funcKeywordCode=o;function a(h){const{gen:d,data:f,it:v}=h;d.if(v.parentData,()=>d.assign(f,(0,t._)`${v.parentData}[${v.parentDataProperty}]`))}function i(h,d){const{gen:f}=h;f.if((0,t._)`Array.isArray(${d})`,()=>{f.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${d} : ${e.default.vErrors}.concat(${d})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function c({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function l(h,d,f){if(f===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,t.stringify)(f)})}function u(h,d,f=!1){return!d.length||d.some(v=>v==="array"?Array.isArray(h):v==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==v||f&&typeof h>"u")}Ft.validSchemaType=u;function p({schema:h,opts:d,self:f,errSchemaPath:v},g,w){if(Array.isArray(g.keyword)?!g.keyword.includes(w):g.keyword!==w)throw new Error("ajv implementation error");const y=g.dependencies;if(y?.some(_=>!Object.prototype.hasOwnProperty.call(h,_)))throw new Error(`parent schema must have dependencies of ${w}: ${y.join(",")}`);if(g.validateSchema&&!g.validateSchema(h[w])){const b=`keyword "${w}" value is invalid at path "${v}": `+f.errorsText(g.validateSchema.errors);if(d.validateSchema==="log")f.logger.error(b);else throw new Error(b)}}return Ft.validateKeywordUsage=p,Ft}var wr={},qd;function E_(){if(qd)return wr;qd=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;const t=Ce(),e=Ae();function r(o,{keyword:a,schemaProp:i,schema:c,schemaPath:l,errSchemaPath:u,topSchemaRef:p}){if(a!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const h=o.schema[a];return i===void 0?{schema:h,schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:h[i],schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}${(0,t.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,e.escapeFragment)(i)}`}}if(c!==void 0){if(l===void 0||u===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:l,topSchemaRef:p,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}wr.getSubschema=r;function n(o,a,{dataProp:i,dataPropType:c,data:l,dataTypes:u,propertyName:p}){if(l!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=a;if(i!==void 0){const{errorPath:f,dataPathArr:v,opts:g}=a,w=h.let("data",(0,t._)`${a.data}${(0,t.getProperty)(i)}`,!0);d(w),o.errorPath=(0,t.str)`${f}${(0,e.getErrorPath)(i,c,g.jsPropertySyntax)}`,o.parentDataProperty=(0,t._)`${i}`,o.dataPathArr=[...v,o.parentDataProperty]}if(l!==void 0){const f=l instanceof t.Name?l:h.let("data",l,!0);d(f),p!==void 0&&(o.propertyName=p)}u&&(o.dataTypes=u);function d(f){o.data=f,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,f]}}wr.extendSubschemaData=n;function s(o,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:c,createErrors:l,allErrors:u}){c!==void 0&&(o.compositeRule=c),l!==void 0&&(o.createErrors=l),u!==void 0&&(o.allErrors=u),o.jtdDiscriminator=a,o.jtdMetadata=i}return wr.extendSubschemaMode=s,wr}var pt={},Ji,zd;function Dd(){return zd||(zd=1,Ji=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,o;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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var a=o[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}),Ji}var Gi={exports:{}},Ud;function x_(){if(Ud)return Gi.exports;Ud=1;var t=Gi.exports=function(n,s,o){typeof s=="function"&&(o=s,s={}),o=s.cb||o;var a=typeof o=="function"?o:o.pre||function(){},i=o.post||function(){};e(s,a,i,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,o,a,i,c,l,u,p,h){if(a&&typeof a=="object"&&!Array.isArray(a)){s(a,i,c,l,u,p,h);for(var d in a){var f=a[d];if(Array.isArray(f)){if(d in t.arrayKeywords)for(var v=0;v<f.length;v++)e(n,s,o,f[v],i+"/"+d+"/"+v,c,i,d,a,v)}else if(d in t.propsKeywords){if(f&&typeof f=="object")for(var g in f)e(n,s,o,f[g],i+"/"+d+"/"+r(g),c,i,d,a,g)}else(d in t.keywords||n.allKeys&&!(d in t.skipKeywords))&&e(n,s,o,f,i+"/"+d,c,i,d,a)}o(a,i,c,l,u,p,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Gi.exports}var Zd;function Lo(){if(Zd)return pt;Zd=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;const t=Ae(),e=Dd(),r=x_(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(v,g=!0){return typeof v=="boolean"?!0:g===!0?!a(v):g?i(v)<=g:!1}pt.inlineRef=s;const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const g in v){if(o.has(g))return!0;const w=v[g];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let g=0;for(const w in v){if(w==="$ref")return 1/0;if(g++,!n.has(w)&&(typeof v[w]=="object"&&(0,t.eachItem)(v[w],y=>g+=i(y)),g===1/0))return 1/0}return g}function c(v,g="",w){w!==!1&&(g=p(g));const y=v.parse(g);return l(v,y)}pt.getFullPath=c;function l(v,g){return v.serialize(g).split("#")[0]+"#"}pt._getFullPath=l;const u=/#\/?$/;function p(v){return v?v.replace(u,""):""}pt.normalizeId=p;function h(v,g,w){return w=p(w),v.resolve(g,w)}pt.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function f(v,g){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:y}=this.opts,_=p(v[w]||g),b={"":_},k=c(y,_,!1),S={},T=new Set;return r(v,{allKeys:!0},(j,O,D,U)=>{if(U===void 0)return;const V=k+O;let ne=b[U];typeof j[w]=="string"&&(ne=fe.call(this,j[w])),de.call(this,j.$anchor),de.call(this,j.$dynamicAnchor),b[O]=ne;function fe(te){const ye=this.opts.uriResolver.resolve;if(te=p(ne?ye(ne,te):te),T.has(te))throw R(te);T.add(te);let H=this.refs[te];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(j,H.schema,te):te!==p(V)&&(te[0]==="#"?(x(j,S[te],te),S[te]=j):this.refs[te]=V),te}function de(te){if(typeof te=="string"){if(!d.test(te))throw new Error(`invalid anchor "${te}"`);fe.call(this,`#${te}`)}}}),S;function x(j,O,D){if(O!==void 0&&!e(j,O))throw R(D)}function R(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return pt.getSchemaRefs=f,pt}var Fd;function jo(){if(Fd)return _r;Fd=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.getData=_r.KeywordCxt=_r.validateFunctionCode=void 0;const t=T_(),e=No(),r=Ad(),n=No(),s=C_(),o=$_(),a=E_(),i=Ce(),c=Lr(),l=Lo(),u=Ae(),p=Mo();function h(A){if(k(A)&&(T(A),b(A))){g(A);return}d(A,()=>(0,t.topBoolOrEmptySchema)(A))}_r.validateFunctionCode=h;function d({gen:A,validateName:Z,schema:G,schemaEnv:K,opts:Q},ue){Q.code.es5?A.func(Z,(0,i._)`${c.default.data}, ${c.default.valCxt}`,K.$async,()=>{A.code((0,i._)`"use strict"; ${y(G,Q)}`),v(A,Q),A.code(ue)}):A.func(Z,(0,i._)`${c.default.data}, ${f(Q)}`,K.$async,()=>A.code(y(G,Q)).code(ue))}function f(A){return(0,i._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${A.dynamicRef?(0,i._)`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}function v(A,Z){A.if(c.default.valCxt,()=>{A.var(c.default.instancePath,(0,i._)`${c.default.valCxt}.${c.default.instancePath}`),A.var(c.default.parentData,(0,i._)`${c.default.valCxt}.${c.default.parentData}`),A.var(c.default.parentDataProperty,(0,i._)`${c.default.valCxt}.${c.default.parentDataProperty}`),A.var(c.default.rootData,(0,i._)`${c.default.valCxt}.${c.default.rootData}`),Z.dynamicRef&&A.var(c.default.dynamicAnchors,(0,i._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{A.var(c.default.instancePath,(0,i._)`""`),A.var(c.default.parentData,(0,i._)`undefined`),A.var(c.default.parentDataProperty,(0,i._)`undefined`),A.var(c.default.rootData,c.default.data),Z.dynamicRef&&A.var(c.default.dynamicAnchors,(0,i._)`{}`)})}function g(A){const{schema:Z,opts:G,gen:K}=A;d(A,()=>{G.$comment&&Z.$comment&&U(A),j(A),K.let(c.default.vErrors,null),K.let(c.default.errors,0),G.unevaluated&&w(A),x(A),V(A)})}function w(A){const{gen:Z,validateName:G}=A;A.evaluated=Z.const("evaluated",(0,i._)`${G}.evaluated`),Z.if((0,i._)`${A.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${A.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${A.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${A.evaluated}.items`,(0,i._)`undefined`))}function y(A,Z){const G=typeof A=="object"&&A[Z.schemaId];return G&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function _(A,Z){if(k(A)&&(T(A),b(A))){S(A,Z);return}(0,t.boolOrEmptySchema)(A,Z)}function b({schema:A,self:Z}){if(typeof A=="boolean")return!A;for(const G in A)if(Z.RULES.all[G])return!0;return!1}function k(A){return typeof A.schema!="boolean"}function S(A,Z){const{schema:G,gen:K,opts:Q}=A;Q.$comment&&G.$comment&&U(A),O(A),D(A);const ue=K.const("_errs",c.default.errors);x(A,ue),K.var(Z,(0,i._)`${ue} === ${c.default.errors}`)}function T(A){(0,u.checkUnknownRules)(A),R(A)}function x(A,Z){if(A.opts.jtd)return fe(A,[],!1,Z);const G=(0,e.getSchemaTypes)(A.schema),K=(0,e.coerceAndCheckDataType)(A,G);fe(A,G,!K,Z)}function R(A){const{schema:Z,errSchemaPath:G,opts:K,self:Q}=A;Z.$ref&&K.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,Q.RULES)&&Q.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function j(A){const{schema:Z,opts:G}=A;Z.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function O(A){const Z=A.schema[A.opts.schemaId];Z&&(A.baseId=(0,l.resolveUrl)(A.opts.uriResolver,A.baseId,Z))}function D(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:A,schemaEnv:Z,schema:G,errSchemaPath:K,opts:Q}){const ue=G.$comment;if(Q.$comment===!0)A.code((0,i._)`${c.default.self}.logger.log(${ue})`);else if(typeof Q.$comment=="function"){const he=(0,i.str)`${K}/$comment`,Ve=A.scopeValue("root",{ref:Z.root});A.code((0,i._)`${c.default.self}.opts.$comment(${ue}, ${he}, ${Ve}.schema)`)}}function V(A){const{gen:Z,schemaEnv:G,validateName:K,ValidationError:Q,opts:ue}=A;G.$async?Z.if((0,i._)`${c.default.errors} === 0`,()=>Z.return(c.default.data),()=>Z.throw((0,i._)`new ${Q}(${c.default.vErrors})`)):(Z.assign((0,i._)`${K}.errors`,c.default.vErrors),ue.unevaluated&&ne(A),Z.return((0,i._)`${c.default.errors} === 0`))}function ne({gen:A,evaluated:Z,props:G,items:K}){G instanceof i.Name&&A.assign((0,i._)`${Z}.props`,G),K instanceof i.Name&&A.assign((0,i._)`${Z}.items`,K)}function fe(A,Z,G,K){const{gen:Q,schema:ue,data:he,allErrors:Ve,opts:Be,self:X}=A,{RULES:ke}=X;if(ue.$ref&&(Be.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ue,ke))){Q.block(()=>B(A,"$ref",ke.all.$ref.definition));return}Be.jtd||te(A,Z),Q.block(()=>{for(const Ee of ke.rules)wt(Ee);wt(ke.post)});function wt(Ee){(0,r.shouldUseGroup)(ue,Ee)&&(Ee.type?(Q.if((0,n.checkDataType)(Ee.type,he,Be.strictNumbers)),de(A,Ee),Z.length===1&&Z[0]===Ee.type&&G&&(Q.else(),(0,n.reportTypeError)(A)),Q.endIf()):de(A,Ee),Ve||Q.if((0,i._)`${c.default.errors} === ${K||0}`))}}function de(A,Z){const{gen:G,schema:K,opts:{useDefaults:Q}}=A;Q&&(0,s.assignDefaults)(A,Z.type),G.block(()=>{for(const ue of Z.rules)(0,r.shouldUseRule)(K,ue)&&B(A,ue.keyword,ue.definition,Z.type)})}function te(A,Z){A.schemaEnv.meta||!A.opts.strictTypes||(ye(A,Z),A.opts.allowUnionTypes||H(A,Z),P(A,A.dataTypes))}function ye(A,Z){if(Z.length){if(!A.dataTypes.length){A.dataTypes=Z;return}Z.forEach(G=>{q(A.dataTypes,G)||I(A,`type "${G}" not allowed by context "${A.dataTypes.join(",")}"`)}),E(A,Z)}}function H(A,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&I(A,"use allowUnionTypes to allow union type keyword")}function P(A,Z){const G=A.self.RULES.all;for(const K in G){const Q=G[K];if(typeof Q=="object"&&(0,r.shouldUseRule)(A.schema,Q)){const{type:ue}=Q.definition;ue.length&&!ue.some(he=>F(Z,he))&&I(A,`missing type "${ue.join(",")}" for keyword "${K}"`)}}}function F(A,Z){return A.includes(Z)||Z==="number"&&A.includes("integer")}function q(A,Z){return A.includes(Z)||Z==="integer"&&A.includes("number")}function E(A,Z){const G=[];for(const K of A.dataTypes)q(Z,K)?G.push(K):Z.includes("integer")&&K==="number"&&G.push("integer");A.dataTypes=G}function I(A,Z){const G=A.schemaEnv.baseId+A.errSchemaPath;Z+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(A,Z,A.opts.strictTypes)}class ${constructor(Z,G,K){if((0,o.validateKeywordUsage)(Z,G,K),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=K,this.data=Z.data,this.schema=Z.schema[K],this.$data=G.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,K,this.$data),this.schemaType=G.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=G,this.$data)this.schemaCode=Z.gen.const("vSchema",pe(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${K} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",c.default.errors))}result(Z,G,K){this.failResult((0,i.not)(Z),G,K)}failResult(Z,G,K){this.gen.if(Z),K?K():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,G){this.failResult((0,i.not)(Z),void 0,G)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,G,K){if(G){this.setParams(G),this._error(Z,K),this.setParams({});return}this._error(Z,K)}_error(Z,G){(Z?p.reportExtraError:p.reportError)(this,this.def.error,G)}$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(Z){this.allErrors||this.gen.if(Z)}setParams(Z,G){G?Object.assign(this.params,Z):this.params=Z}block$data(Z,G,K=i.nil){this.gen.block(()=>{this.check$data(Z,K),G()})}check$data(Z=i.nil,G=i.nil){if(!this.$data)return;const{gen:K,schemaCode:Q,schemaType:ue,def:he}=this;K.if((0,i.or)((0,i._)`${Q} === undefined`,G)),Z!==i.nil&&K.assign(Z,!0),(ue.length||he.validateSchema)&&(K.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&K.assign(Z,!1)),K.else()}invalid$data(){const{gen:Z,schemaCode:G,schemaType:K,def:Q,it:ue}=this;return(0,i.or)(he(),Ve());function he(){if(K.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const Be=Array.isArray(K)?K:[K];return(0,i._)`${(0,n.checkDataTypes)(Be,G,ue.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Ve(){if(Q.validateSchema){const Be=Z.scopeValue("validate$data",{ref:Q.validateSchema});return(0,i._)`!${Be}(${G})`}return i.nil}}subschema(Z,G){const K=(0,a.getSubschema)(this.it,Z);(0,a.extendSubschemaData)(K,this.it,Z),(0,a.extendSubschemaMode)(K,Z);const Q={...this.it,...K,items:void 0,props:void 0};return _(Q,G),Q}mergeEvaluated(Z,G){const{it:K,gen:Q}=this;K.opts.unevaluated&&(K.props!==!0&&Z.props!==void 0&&(K.props=u.mergeEvaluated.props(Q,Z.props,K.props,G)),K.items!==!0&&Z.items!==void 0&&(K.items=u.mergeEvaluated.items(Q,Z.items,K.items,G)))}mergeValidEvaluated(Z,G){const{it:K,gen:Q}=this;if(K.opts.unevaluated&&(K.props!==!0||K.items!==!0))return Q.if(G,()=>this.mergeEvaluated(Z,i.Name)),!0}}_r.KeywordCxt=$;function B(A,Z,G,K){const Q=new $(A,G,Z);"code"in G?G.code(Q,K):Q.$data&&G.validate?(0,o.funcKeywordCode)(Q,G):"macro"in G?(0,o.macroKeywordCode)(Q,G):(G.compile||G.validate)&&(0,o.funcKeywordCode)(Q,G)}const W=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(A,{dataLevel:Z,dataNames:G,dataPathArr:K}){let Q,ue;if(A==="")return c.default.rootData;if(A[0]==="/"){if(!W.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);Q=A,ue=c.default.rootData}else{const X=_e.exec(A);if(!X)throw new Error(`Invalid JSON-pointer: ${A}`);const ke=+X[1];if(Q=X[2],Q==="#"){if(ke>=Z)throw new Error(Be("property/index",ke));return K[Z-ke]}if(ke>Z)throw new Error(Be("data",ke));if(ue=G[Z-ke],!Q)return ue}let he=ue;const Ve=Q.split("/");for(const X of Ve)X&&(ue=(0,i._)`${ue}${(0,i.getProperty)((0,u.unescapeJsonPointer)(X))}`,he=(0,i._)`${he} && ${ue}`);return he;function Be(X,ke){return`Cannot access ${X} ${ke} levels up, current level is ${Z}`}}return _r.getData=pe,_r}var qo={},Vd;function Wi(){if(Vd)return qo;Vd=1,Object.defineProperty(qo,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return qo.default=t,qo}var zo={},Hd;function Do(){if(Hd)return zo;Hd=1,Object.defineProperty(zo,"__esModule",{value:!0});const t=Lo();class e extends Error{constructor(n,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,o),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return zo.default=e,zo}var xt={},Bd;function Ki(){if(Bd)return xt;Bd=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.resolveSchema=xt.getCompilingSchema=xt.resolveRef=xt.compileSchema=xt.SchemaEnv=void 0;const t=Ce(),e=Wi(),r=Lr(),n=Lo(),s=Ae(),o=jo();class a{constructor(w){var y;this.refs={},this.dynamicAnchors={};let _;typeof w.schema=="object"&&(_=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(y=w.baseId)!==null&&y!==void 0?y:(0,n.normalizeId)(_?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=_?.$async,this.refs={}}}xt.SchemaEnv=a;function i(g){const w=u.call(this,g);if(w)return w;const y=(0,n.getFullPath)(this.opts.uriResolver,g.root.baseId),{es5:_,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new t.CodeGen(this.scope,{es5:_,lines:b,ownProperties:k});let T;g.$async&&(T=S.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const x=S.scopeName("validate");g.validateName=x;const R={gen:S,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:S.scopeValue("schema",this.opts.code.source===!0?{ref:g.schema,code:(0,t.stringify)(g.schema)}:{ref:g.schema}),validateName:x,ValidationError:T,schema:g.schema,schemaEnv:g,rootId:y,baseId:g.baseId||y,schemaPath:t.nil,errSchemaPath:g.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(g),(0,o.validateFunctionCode)(R),S.optimize(this.opts.code.optimize);const O=S.toString();j=`${S.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(j=this.opts.code.process(j,g));const U=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(x,{ref:U}),U.errors=null,U.schema=g.schema,U.schemaEnv=g,g.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:x,validateCode:O,scopeValues:S._values}),this.opts.unevaluated){const{props:V,items:ne}=R;U.evaluated={props:V instanceof t.Name?void 0:V,items:ne instanceof t.Name?void 0:ne,dynamicProps:V instanceof t.Name,dynamicItems:ne instanceof t.Name},U.source&&(U.source.evaluated=(0,t.stringify)(U.evaluated))}return g.validate=U,g}catch(O){throw delete g.validate,delete g.validateName,j&&this.logger.error("Error compiling schema, function code:",j),O}finally{this._compilations.delete(g)}}xt.compileSchema=i;function c(g,w,y){var _;y=(0,n.resolveUrl)(this.opts.uriResolver,w,y);const b=g.refs[y];if(b)return b;let k=h.call(this,g,y);if(k===void 0){const S=(_=g.localRefs)===null||_===void 0?void 0:_[y],{schemaId:T}=this.opts;S&&(k=new a({schema:S,schemaId:T,root:g,baseId:w}))}if(k!==void 0)return g.refs[y]=l.call(this,k)}xt.resolveRef=c;function l(g){return(0,n.inlineRef)(g.schema,this.opts.inlineRefs)?g.schema:g.validate?g:i.call(this,g)}function u(g){for(const w of this._compilations)if(p(w,g))return w}xt.getCompilingSchema=u;function p(g,w){return g.schema===w.schema&&g.root===w.root&&g.baseId===w.baseId}function h(g,w){let y;for(;typeof(y=this.refs[w])=="string";)w=y;return y||this.schemas[w]||d.call(this,g,w)}function d(g,w){const y=this.opts.uriResolver.parse(w),_=(0,n._getFullPath)(this.opts.uriResolver,y);let b=(0,n.getFullPath)(this.opts.uriResolver,g.baseId,void 0);if(Object.keys(g.schema).length>0&&_===b)return v.call(this,y,g);const k=(0,n.normalizeId)(_),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const T=d.call(this,g,S);return typeof T?.schema!="object"?void 0:v.call(this,y,T)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(w)){const{schema:T}=S,{schemaId:x}=this.opts,R=T[x];return R&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,R)),new a({schema:T,schemaId:x,root:g,baseId:b})}return v.call(this,y,S)}}xt.resolveSchema=d;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(g,{baseId:w,schema:y,root:_}){var b;if(((b=g.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const T of g.fragment.slice(1).split("/")){if(typeof y=="boolean")return;const x=y[(0,s.unescapeFragment)(T)];if(x===void 0)return;y=x;const R=typeof y=="object"&&y[this.opts.schemaId];!f.has(T)&&R&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,R))}let k;if(typeof y!="boolean"&&y.$ref&&!(0,s.schemaHasRulesButRef)(y,this.RULES)){const T=(0,n.resolveUrl)(this.opts.uriResolver,w,y.$ref);k=d.call(this,_,T)}const{schemaId:S}=this.opts;if(k=k||new a({schema:y,schemaId:S,root:_,baseId:w}),k.schema!==k.root.schema)return k}return xt}const I_={$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 Uo={},hs={exports:{}},Yi,Jd;function Gd(){if(Jd)return Yi;Jd=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(h){let d="",f=0,v=0;for(v=0;v<h.length;v++)if(f=h[v].charCodeAt(0),f!==48){if(!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[v];break}for(v+=1;v<h.length;v++){if(f=h[v].charCodeAt(0),!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[v]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(h){return h.length=0,!0}function o(h,d,f){if(h.length){const v=r(h);if(v!=="")d.push(v);else return f.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const f={error:!1,address:"",zone:""},v=[],g=[];let w=!1,y=!1,_=o;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(y=!0),!_(g,v,f))break;if(++d>7){f.error=!0;break}b>0&&h[b-1]===":"&&(w=!0),v.push(":");continue}else if(k==="%"){if(!_(g,v,f))break;_=s}else{g.push(k);continue}}return g.length&&(_===s?f.zone=g.join(""):y?v.push(g.join("")):v.push(r(g))),f.address=v.join(""),f}function i(h){if(c(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let f=d.address,v=d.address;return d.zone&&(f+="%"+d.zone,v+="%25"+d.zone),{host:f,isIPV6:!0,escapedHost:v}}}function c(h,d){let f=0;for(let v=0;v<h.length;v++)h[v]===d&&f++;return f}function l(h){let d=h;const f=[];let v=-1,g=0;for(;g=d.length;){if(g===1){if(d===".")break;if(d==="/"){f.push("/");break}else{f.push(d);break}}else if(g===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){f.push("/");break}}else if(g===3&&d==="/.."){f.length!==0&&f.pop(),f.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),f.length!==0&&f.pop();continue}}if((v=d.indexOf("/",1))===-1){f.push(d);break}else f.push(d.slice(0,v)),d=d.slice(v)}return f.join("")}function u(h,d){const f=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=f(h.scheme)),h.userinfo!==void 0&&(h.userinfo=f(h.userinfo)),h.host!==void 0&&(h.host=f(h.host)),h.path!==void 0&&(h.path=f(h.path)),h.query!==void 0&&(h.query=f(h.query)),h.fragment!==void 0&&(h.fragment=f(h.fragment)),h}function p(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let f=unescape(h.host);if(!e(f)){const v=i(f);v.isIPV6===!0?f=`[${v.escapedHost}]`:f=h.host}d.push(f)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return Yi={nonSimpleDomain:n,recomposeAuthority:p,normalizeComponentEncoding:u,removeDotSegments:l,isIPv4:e,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:r},Yi}var Qi,Wd;function R_(){if(Wd)return Qi;Wd=1;const{isUUID:t}=Gd(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function s(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function o(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=s(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function c(k){if((k.port===(s(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[S,T]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=T,k.resourceName=void 0}return k.fragment=void 0,k}function l(k,S){if(!k.path)return k.error="URN can not be parsed",k;const T=k.path.match(e);if(T){const x=S.scheme||k.scheme||"urn";k.nid=T[1].toLowerCase(),k.nss=T[2];const R=`${x}:${S.nid||k.nid}`,j=b(R);k.path=void 0,j&&(k=j.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const T=S.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),R=`${T}:${S.nid||x}`,j=b(R);j&&(k=j.serialize(k,S));const O=k,D=k.nss;return O.path=`${x||S.nid}:${D}`,S.skipEscape=!0,O}function p(k,S){const T=k;return T.uuid=T.nss,T.nss=void 0,!S.tolerant&&(!T.uuid||!t(T.uuid))&&(T.error=T.error||"UUID is not valid."),T}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:o,serialize:a},f={scheme:"https",domainHost:d.domainHost,parse:o,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:c},g={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},_={http:d,https:f,ws:v,wss:g,urn:{scheme:"urn",parse:l,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:p,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(_,null);function b(k){return k&&(_[k]||_[k.toLowerCase()])||void 0}return Qi={wsIsSecure:s,SCHEMES:_,isValidSchemeName:n,getSchemeHandler:b},Qi}var Kd;function P_(){if(Kd)return hs.exports;Kd=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:o}=Gd(),{SCHEMES:a,getSchemeHandler:i}=R_();function c(g,w){return typeof g=="string"?g=h(f(g,w),w):typeof g=="object"&&(g=f(h(g,w),w)),g}function l(g,w,y){const _=y?Object.assign({scheme:"null"},y):{scheme:"null"},b=u(f(g,_),f(w,_),_,!0);return _.skipEscape=!0,h(b,_)}function u(g,w,y,_){const b={};return _||(g=f(h(g,y),y),w=f(h(w,y),y)),y=y||{},!y.tolerant&&w.scheme?(b.scheme=w.scheme,b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.path?(w.path[0]==="/"?b.path=e(w.path):((g.userinfo!==void 0||g.host!==void 0||g.port!==void 0)&&!g.path?b.path="/"+w.path:g.path?b.path=g.path.slice(0,g.path.lastIndexOf("/")+1)+w.path:b.path=w.path,b.path=e(b.path)),b.query=w.query):(b.path=g.path,w.query!==void 0?b.query=w.query:b.query=g.query),b.userinfo=g.userinfo,b.host=g.host,b.port=g.port),b.scheme=g.scheme),b.fragment=w.fragment,b}function p(g,w,y){return typeof g=="string"?(g=unescape(g),g=h(n(f(g,y),!0),{...y,skipEscape:!0})):typeof g=="object"&&(g=h(n(g,!0),{...y,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=h(n(f(w,y),!0),{...y,skipEscape:!0})):typeof w=="object"&&(w=h(n(w,!0),{...y,skipEscape:!0})),g.toLowerCase()===w.toLowerCase()}function h(g,w){const y={host:g.host,scheme:g.scheme,userinfo:g.userinfo,port:g.port,path:g.path,query:g.query,nid:g.nid,nss:g.nss,uuid:g.uuid,fragment:g.fragment,reference:g.reference,resourceName:g.resourceName,secure:g.secure,error:""},_=Object.assign({},w),b=[],k=i(_.scheme||y.scheme);k&&k.serialize&&k.serialize(y,_),y.path!==void 0&&(_.skipEscape?y.path=unescape(y.path):(y.path=escape(y.path),y.scheme!==void 0&&(y.path=y.path.split("%3A").join(":")))),_.reference!=="suffix"&&y.scheme&&b.push(y.scheme,":");const S=r(y);if(S!==void 0&&(_.reference!=="suffix"&&b.push("//"),b.push(S),y.path&&y.path[0]!=="/"&&b.push("/")),y.path!==void 0){let T=y.path;!_.absolutePath&&(!k||!k.absolutePath)&&(T=e(T)),S===void 0&&T[0]==="/"&&T[1]==="/"&&(T="/%2F"+T.slice(2)),b.push(T)}return y.query!==void 0&&b.push("?",y.query),y.fragment!==void 0&&b.push("#",y.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(g,w){const y=Object.assign({},w),_={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;y.reference==="suffix"&&(y.scheme?g=y.scheme+":"+g:g="//"+g);const k=g.match(d);if(k){if(_.scheme=k[1],_.userinfo=k[3],_.host=k[4],_.port=parseInt(k[5],10),_.path=k[6]||"",_.query=k[7],_.fragment=k[8],isNaN(_.port)&&(_.port=k[5]),_.host)if(s(_.host)===!1){const x=t(_.host);_.host=x.host.toLowerCase(),b=x.isIPV6}else b=!0;_.scheme===void 0&&_.userinfo===void 0&&_.host===void 0&&_.port===void 0&&_.query===void 0&&!_.path?_.reference="same-document":_.scheme===void 0?_.reference="relative":_.fragment===void 0?_.reference="absolute":_.reference="uri",y.reference&&y.reference!=="suffix"&&y.reference!==_.reference&&(_.error=_.error||"URI is not a "+y.reference+" reference.");const S=i(y.scheme||_.scheme);if(!y.unicodeSupport&&(!S||!S.unicodeSupport)&&_.host&&(y.domainHost||S&&S.domainHost)&&b===!1&&o(_.host))try{_.host=URL.domainToASCII(_.host.toLowerCase())}catch(T){_.error=_.error||"Host's domain name can not be converted to ASCII: "+T}(!S||S&&!S.skipNormalize)&&(g.indexOf("%")!==-1&&(_.scheme!==void 0&&(_.scheme=unescape(_.scheme)),_.host!==void 0&&(_.host=unescape(_.host))),_.path&&(_.path=escape(unescape(_.path))),_.fragment&&(_.fragment=encodeURI(decodeURIComponent(_.fragment)))),S&&S.parse&&S.parse(_,y)}else _.error=_.error||"URI can not be parsed.";return _}const v={SCHEMES:a,normalize:c,resolve:l,resolveComponent:u,equal:p,serialize:h,parse:f};return hs.exports=v,hs.exports.default=v,hs.exports.fastUri=v,hs.exports}var Yd;function O_(){if(Yd)return Uo;Yd=1,Object.defineProperty(Uo,"__esModule",{value:!0});const t=P_();return t.code='require("ajv/dist/runtime/uri").default',Uo.default=t,Uo}var Qd;function A_(){return Qd||(Qd=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=jo();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Ce();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=Wi(),s=Do(),o=Pd(),a=Ki(),i=Ce(),c=Lo(),l=No(),u=Ae(),p=I_,h=O_(),d=(H,P)=>new RegExp(H,P);d.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={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."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function _(H){var P,F,q,E,I,$,B,W,_e,pe,A,Z,G,K,Q,ue,he,Ve,Be,X,ke,wt,Ee,$t,Or;const Et=H.strict,ct=(P=H.code)===null||P===void 0?void 0:P.optimize,Zt=ct===!0||ct===void 0?1:ct||0,en=(q=(F=H.code)===null||F===void 0?void 0:F.regExp)!==null&&q!==void 0?q:d,tn=(E=H.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(I=H.strictSchema)!==null&&I!==void 0?I:Et)!==null&&$!==void 0?$:!0,strictNumbers:(W=(B=H.strictNumbers)!==null&&B!==void 0?B:Et)!==null&&W!==void 0?W:!0,strictTypes:(pe=(_e=H.strictTypes)!==null&&_e!==void 0?_e:Et)!==null&&pe!==void 0?pe:"log",strictTuples:(Z=(A=H.strictTuples)!==null&&A!==void 0?A:Et)!==null&&Z!==void 0?Z:"log",strictRequired:(K=(G=H.strictRequired)!==null&&G!==void 0?G:Et)!==null&&K!==void 0?K:!1,code:H.code?{...H.code,optimize:Zt,regExp:en}:{optimize:Zt,regExp:en},loopRequired:(Q=H.loopRequired)!==null&&Q!==void 0?Q:y,loopEnum:(ue=H.loopEnum)!==null&&ue!==void 0?ue:y,meta:(he=H.meta)!==null&&he!==void 0?he:!0,messages:(Ve=H.messages)!==null&&Ve!==void 0?Ve:!0,inlineRefs:(Be=H.inlineRefs)!==null&&Be!==void 0?Be:!0,schemaId:(X=H.schemaId)!==null&&X!==void 0?X:"$id",addUsedSchema:(ke=H.addUsedSchema)!==null&&ke!==void 0?ke:!0,validateSchema:(wt=H.validateSchema)!==null&&wt!==void 0?wt:!0,validateFormats:(Ee=H.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:($t=H.unicodeRegExp)!==null&&$t!==void 0?$t:!0,int32range:(Or=H.int32range)!==null&&Or!==void 0?Or:!0,uriResolver:tn}}class b{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,..._(P)};const{es5:F,lines:q}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:F,lines:q}),this.logger=D(P.logger);const E=P.validateFormats;P.validateFormats=!1,this.RULES=(0,o.getRules)(),k.call(this,g,P,"NOT SUPPORTED"),k.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&R.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),T.call(this),P.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:F,schemaId:q}=this.opts;let E=p;q==="id"&&(E={...p},E.id=E.$id,delete E.$id),F&&P&&this.addMetaSchema(E,E[q],!1)}defaultMeta(){const{meta:P,schemaId:F}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[F]||P:void 0}validate(P,F){let q;if(typeof P=="string"){if(q=this.getSchema(P),!q)throw new Error(`no schema with key or ref "${P}"`)}else q=this.compile(P);const E=q(F);return"$async"in q||(this.errors=q.errors),E}compile(P,F){const q=this._addSchema(P,F);return q.validate||this._compileSchemaEnv(q)}compileAsync(P,F){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:q}=this.opts;return E.call(this,P,F);async function E(pe,A){await I.call(this,pe.$schema);const Z=this._addSchema(pe,A);return Z.validate||$.call(this,Z)}async function I(pe){pe&&!this.getSchema(pe)&&await E.call(this,{$ref:pe},!0)}async function $(pe){try{return this._compileSchemaEnv(pe)}catch(A){if(!(A instanceof s.default))throw A;return B.call(this,A),await W.call(this,A.missingSchema),$.call(this,pe)}}function B({missingSchema:pe,missingRef:A}){if(this.refs[pe])throw new Error(`AnySchema ${pe} is loaded but ${A} cannot be resolved`)}async function W(pe){const A=await _e.call(this,pe);this.refs[pe]||await I.call(this,A.$schema),this.refs[pe]||this.addSchema(A,pe,F)}async function _e(pe){const A=this._loading[pe];if(A)return A;try{return await(this._loading[pe]=q(pe))}finally{delete this._loading[pe]}}}addSchema(P,F,q,E=this.opts.validateSchema){if(Array.isArray(P)){for(const $ of P)this.addSchema($,void 0,q,E);return this}let I;if(typeof P=="object"){const{schemaId:$}=this.opts;if(I=P[$],I!==void 0&&typeof I!="string")throw new Error(`schema ${$} must be string`)}return F=(0,c.normalizeId)(F||I),this._checkUnique(F),this.schemas[F]=this._addSchema(P,q,F,E,!0),this}addMetaSchema(P,F,q=this.opts.validateSchema){return this.addSchema(P,F,!0,q),this}validateSchema(P,F){if(typeof P=="boolean")return!0;let q;if(q=P.$schema,q!==void 0&&typeof q!="string")throw new Error("$schema must be a string");if(q=q||this.opts.defaultMeta||this.defaultMeta(),!q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(q,P);if(!E&&F){const I="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(I);else throw new Error(I)}return E}getSchema(P){let F;for(;typeof(F=S.call(this,P))=="string";)P=F;if(F===void 0){const{schemaId:q}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:q});if(F=a.resolveSchema.call(this,E,P),!F)return;this.refs[P]=F}return F.validate||this._compileSchemaEnv(F)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const F=S.call(this,P);return typeof F=="object"&&this._cache.delete(F.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const F=P;this._cache.delete(F);let q=P[this.opts.schemaId];return q&&(q=(0,c.normalizeId)(q),delete this.schemas[q],delete this.refs[q]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(P){for(const F of P)this.addKeyword(F);return this}addKeyword(P,F){let q;if(typeof P=="string")q=P,typeof F=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),F.keyword=q);else if(typeof P=="object"&&F===void 0){if(F=P,q=F.keyword,Array.isArray(q)&&!q.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(V.call(this,q,F),!F)return(0,u.eachItem)(q,I=>ne.call(this,I)),this;de.call(this,F);const E={...F,type:(0,l.getJSONTypes)(F.type),schemaType:(0,l.getJSONTypes)(F.schemaType)};return(0,u.eachItem)(q,E.type.length===0?I=>ne.call(this,I,E):I=>E.type.forEach($=>ne.call(this,I,E,$))),this}getKeyword(P){const F=this.RULES.all[P];return typeof F=="object"?F.definition:!!F}removeKeyword(P){const{RULES:F}=this;delete F.keywords[P],delete F.all[P];for(const q of F.rules){const E=q.rules.findIndex(I=>I.keyword===P);E>=0&&q.rules.splice(E,1)}return this}addFormat(P,F){return typeof F=="string"&&(F=new RegExp(F)),this.formats[P]=F,this}errorsText(P=this.errors,{separator:F=", ",dataVar:q="data"}={}){return!P||P.length===0?"No errors":P.map(E=>`${q}${E.instancePath} ${E.message}`).reduce((E,I)=>E+F+I)}$dataMetaSchema(P,F){const q=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const E of F){const I=E.split("/").slice(1);let $=P;for(const B of I)$=$[B];for(const B in q){const W=q[B];if(typeof W!="object")continue;const{$data:_e}=W.definition,pe=$[B];_e&&pe&&($[B]=ye(pe))}}return P}_removeAllSchemas(P,F){for(const q in P){const E=P[q];(!F||F.test(q))&&(typeof E=="string"?delete P[q]:E&&!E.meta&&(this._cache.delete(E.schema),delete P[q]))}}_addSchema(P,F,q,E=this.opts.validateSchema,I=this.opts.addUsedSchema){let $;const{schemaId:B}=this.opts;if(typeof P=="object")$=P[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let W=this._cache.get(P);if(W!==void 0)return W;q=(0,c.normalizeId)($||q);const _e=c.getSchemaRefs.call(this,P,q);return W=new a.SchemaEnv({schema:P,schemaId:B,meta:F,baseId:q,localRefs:_e}),this._cache.set(W.schema,W),I&&!q.startsWith("#")&&(q&&this._checkUnique(q),this.refs[q]=W),E&&this.validateSchema(P,!0),W}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){const F=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=F}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function k(H,P,F,q="error"){for(const E in H){const I=E;I in P&&this.logger[q](`${F}: option ${E}. ${H[I]}`)}}function S(H){return H=(0,c.normalizeId)(H),this.schemas[H]||this.refs[H]}function T(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const P in H)this.addSchema(H[P],P)}function x(){for(const H in this.opts.formats){const P=this.opts.formats[H];P&&this.addFormat(H,P)}}function R(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in H){const F=H[P];F.keyword||(F.keyword=P),this.addKeyword(F)}}function j(){const H={...this.opts};for(const P of f)delete H[P];return H}const O={log(){},warn(){},error(){}};function D(H){if(H===!1)return O;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function V(H,P){const{RULES:F}=this;if((0,u.eachItem)(H,q=>{if(F.keywords[q])throw new Error(`Keyword ${q} is already defined`);if(!U.test(q))throw new Error(`Keyword ${q} has invalid name`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function ne(H,P,F){var q;const E=P?.post;if(F&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:I}=this;let $=E?I.post:I.rules.find(({type:W})=>W===F);if($||($={type:F,rules:[]},I.rules.push($)),I.keywords[H]=!0,!P)return;const B={keyword:H,definition:{...P,type:(0,l.getJSONTypes)(P.type),schemaType:(0,l.getJSONTypes)(P.schemaType)}};P.before?fe.call(this,$,B,P.before):$.rules.push(B),I.all[H]=B,(q=P.implements)===null||q===void 0||q.forEach(W=>this.addKeyword(W))}function fe(H,P,F){const q=H.rules.findIndex(E=>E.keyword===F);q>=0?H.rules.splice(q,0,P):(H.rules.push(P),this.logger.warn(`rule ${F} is not defined`))}function de(H){let{metaSchema:P}=H;P!==void 0&&(H.$data&&this.opts.$data&&(P=ye(P)),H.validateSchema=this.compile(P,!0))}const te={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ye(H){return{anyOf:[H,te]}}})(Zi)),Zi}var Zo={},Fo={},Vo={},Xd;function M_(){if(Xd)return Vo;Xd=1,Object.defineProperty(Vo,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Vo.default=t,Vo}var jr={},ep;function N_(){if(ep)return jr;ep=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.callRef=jr.getValidate=void 0;const t=Do(),e=Vt(),r=Ce(),n=Lr(),s=Ki(),o=Ae(),a={keyword:"$ref",schemaType:"string",code(l){const{gen:u,schema:p,it:h}=l,{baseId:d,schemaEnv:f,validateName:v,opts:g,self:w}=h,{root:y}=f;if((p==="#"||p==="#/")&&d===y.baseId)return b();const _=s.resolveRef.call(w,y,d,p);if(_===void 0)throw new t.default(h.opts.uriResolver,d,p);if(_ instanceof s.SchemaEnv)return k(_);return S(_);function b(){if(f===y)return c(l,v,f,f.$async);const T=u.scopeValue("root",{ref:y});return c(l,(0,r._)`${T}.validate`,y,y.$async)}function k(T){const x=i(l,T);c(l,x,T,T.$async)}function S(T){const x=u.scopeValue("schema",g.code.source===!0?{ref:T,code:(0,r.stringify)(T)}:{ref:T}),R=u.name("valid"),j=l.subschema({schema:T,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:p},R);l.mergeEvaluated(j),l.ok(R)}}};function i(l,u){const{gen:p}=l;return u.validate?p.scopeValue("validate",{ref:u.validate}):(0,r._)`${p.scopeValue("wrapper",{ref:u})}.validate`}jr.getValidate=i;function c(l,u,p,h){const{gen:d,it:f}=l,{allErrors:v,schemaEnv:g,opts:w}=f,y=w.passContext?n.default.this:r.nil;h?_():b();function _(){if(!g.$async)throw new Error("async schema referenced by sync schema");const T=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,e.callValidateCode)(l,u,y)}`),S(u),v||d.assign(T,!0)},x=>{d.if((0,r._)`!(${x} instanceof ${f.ValidationError})`,()=>d.throw(x)),k(x),v||d.assign(T,!1)}),l.ok(T)}function b(){l.result((0,e.callValidateCode)(l,u,y),()=>S(u),()=>k(u))}function k(T){const x=(0,r._)`${T}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(T){var x;if(!f.opts.unevaluated)return;const R=(x=p?.validate)===null||x===void 0?void 0:x.evaluated;if(f.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(f.props=o.mergeEvaluated.props(d,R.props,f.props));else{const j=d.var("props",(0,r._)`${T}.evaluated.props`);f.props=o.mergeEvaluated.props(d,j,f.props,r.Name)}if(f.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(f.items=o.mergeEvaluated.items(d,R.items,f.items));else{const j=d.var("items",(0,r._)`${T}.evaluated.items`);f.items=o.mergeEvaluated.items(d,j,f.items,r.Name)}}}return jr.callRef=c,jr.default=a,jr}var tp;function L_(){if(tp)return Fo;tp=1,Object.defineProperty(Fo,"__esModule",{value:!0});const t=M_(),e=N_(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return Fo.default=r,Fo}var Ho={},Bo={},rp;function j_(){if(rp)return Bo;rp=1,Object.defineProperty(Bo,"__esModule",{value:!0});const t=Ce(),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:o,schemaCode:a})=>(0,t.str)`must be ${r[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,t._)`{comparison: ${r[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(o){const{keyword:a,data:i,schemaCode:c}=o;o.fail$data((0,t._)`${i} ${r[a].fail} ${c} || isNaN(${i})`)}};return Bo.default=s,Bo}var Jo={},np;function q_(){if(np)return Jo;np=1,Object.defineProperty(Jo,"__esModule",{value:!0});const t=Ce(),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:o,schemaCode:a,it:i}=n,c=i.opts.multipleOfPrecision,l=s.let("res"),u=c?(0,t._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${c}`:(0,t._)`${l} !== parseInt(${l})`;n.fail$data((0,t._)`(${a} === 0 || (${l} = ${o}/${a}, ${u}))`)}};return Jo.default=r,Jo}var Go={},Wo={},sp;function z_(){if(sp)return Wo;sp=1,Object.defineProperty(Wo,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,o;for(;s<r;)n++,o=e.charCodeAt(s++),o>=55296&&o<=56319&&s<r&&(o=e.charCodeAt(s),(o&64512)===56320&&s++);return n}return Wo.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',Wo}var op;function D_(){if(op)return Go;op=1,Object.defineProperty(Go,"__esModule",{value:!0});const t=Ce(),e=Ae(),r=z_(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:o,schemaCode:a}){const i=o==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:o})=>(0,t._)`{limit: ${o}}`},code(o){const{keyword:a,data:i,schemaCode:c,it:l}=o,u=a==="maxLength"?t.operators.GT:t.operators.LT,p=l.opts.unicode===!1?(0,t._)`${i}.length`:(0,t._)`${(0,e.useFunc)(o.gen,r.default)}(${i})`;o.fail$data((0,t._)`${p} ${u} ${c}`)}};return Go.default=s,Go}var Ko={},ap;function U_(){if(ap)return Ko;ap=1,Object.defineProperty(Ko,"__esModule",{value:!0});const t=Vt(),e=Ce(),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:o,$data:a,schema:i,schemaCode:c,it:l}=s,u=l.opts.unicodeRegExp?"u":"",p=a?(0,e._)`(new RegExp(${c}, ${u}))`:(0,t.usePattern)(s,i);s.fail$data((0,e._)`!${p}.test(${o})`)}};return Ko.default=n,Ko}var Yo={},ip;function Z_(){if(ip)return Yo;ip=1,Object.defineProperty(Yo,"__esModule",{value:!0});const t=Ce(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${o}).length ${i} ${a}`)}};return Yo.default=r,Yo}var Qo={},cp;function F_(){if(cp)return Qo;cp=1,Object.defineProperty(Qo,"__esModule",{value:!0});const t=Vt(),e=Ce(),r=Ae(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:o}})=>(0,e.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,e._)`{missingProperty: ${o}}`},code(o){const{gen:a,schema:i,schemaCode:c,data:l,$data:u,it:p}=o,{opts:h}=p;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(p.allErrors?f():v(),h.strictRequired){const y=o.parentSchema.properties,{definedProperties:_}=o.it;for(const b of i)if(y?.[b]===void 0&&!_.has(b)){const k=p.schemaEnv.baseId+p.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(p,S,p.opts.strictRequired)}}function f(){if(d||u)o.block$data(e.nil,g);else for(const y of i)(0,t.checkReportMissingProp)(o,y)}function v(){const y=a.let("missing");if(d||u){const _=a.let("valid",!0);o.block$data(_,()=>w(y,_)),o.ok(_)}else a.if((0,t.checkMissingProp)(o,i,y)),(0,t.reportMissingProp)(o,y),a.else()}function g(){a.forOf("prop",c,y=>{o.setParams({missingProperty:y}),a.if((0,t.noPropertyInData)(a,l,y,h.ownProperties),()=>o.error())})}function w(y,_){o.setParams({missingProperty:y}),a.forOf(y,c,()=>{a.assign(_,(0,t.propertyInData)(a,l,y,h.ownProperties)),a.if((0,e.not)(_),()=>{o.error(),a.break()})},e.nil)}}};return Qo.default=s,Qo}var Xo={},lp;function V_(){if(lp)return Xo;lp=1,Object.defineProperty(Xo,"__esModule",{value:!0});const t=Ce(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${o}.length ${i} ${a}`)}};return Xo.default=r,Xo}var ea={},ta={},up;function Xi(){if(up)return ta;up=1,Object.defineProperty(ta,"__esModule",{value:!0});const t=Dd();return t.code='require("ajv/dist/runtime/equal").default',ta.default=t,ta}var dp;function H_(){if(dp)return ea;dp=1,Object.defineProperty(ea,"__esModule",{value:!0});const t=No(),e=Ce(),r=Ae(),n=Xi(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,e.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,e._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:c,$data:l,schema:u,parentSchema:p,schemaCode:h,it:d}=a;if(!l&&!u)return;const f=i.let("valid"),v=p.items?(0,t.getSchemaTypes)(p.items):[];a.block$data(f,g,(0,e._)`${h} === false`),a.ok(f);function g(){const b=i.let("i",(0,e._)`${c}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(f,!0),i.if((0,e._)`${b} > 1`,()=>(w()?y:_)(b,k))}function w(){return v.length>0&&!v.some(b=>b==="object"||b==="array")}function y(b,k){const S=i.name("item"),T=(0,t.checkDataTypes)(v,S,d.opts.strictNumbers,t.DataType.Wrong),x=i.const("indices",(0,e._)`{}`);i.for((0,e._)`;${b}--;`,()=>{i.let(S,(0,e._)`${c}[${b}]`),i.if(T,(0,e._)`continue`),v.length>1&&i.if((0,e._)`typeof ${S} == "string"`,(0,e._)`${S} += "_"`),i.if((0,e._)`typeof ${x}[${S}] == "number"`,()=>{i.assign(k,(0,e._)`${x}[${S}]`),a.error(),i.assign(f,!1).break()}).code((0,e._)`${x}[${S}] = ${b}`)})}function _(b,k){const S=(0,r.useFunc)(i,n.default),T=i.name("outer");i.label(T).for((0,e._)`;${b}--;`,()=>i.for((0,e._)`${k} = ${b}; ${k}--;`,()=>i.if((0,e._)`${S}(${c}[${b}], ${c}[${k}])`,()=>{a.error(),i.assign(f,!1).break(T)})))}}};return ea.default=o,ea}var ra={},pp;function B_(){if(pp)return ra;pp=1,Object.defineProperty(ra,"__esModule",{value:!0});const t=Ce(),e=Ae(),r=Xi(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:o})=>(0,t._)`{allowedValue: ${o}}`},code(o){const{gen:a,data:i,$data:c,schemaCode:l,schema:u}=o;c||u&&typeof u=="object"?o.fail$data((0,t._)`!${(0,e.useFunc)(a,r.default)}(${i}, ${l})`):o.fail((0,t._)`${u} !== ${i}`)}};return ra.default=s,ra}var na={},fp;function J_(){if(fp)return na;fp=1,Object.defineProperty(na,"__esModule",{value:!0});const t=Ce(),e=Ae(),r=Xi(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,t._)`{allowedValues: ${o}}`},code(o){const{gen:a,data:i,$data:c,schema:l,schemaCode:u,it:p}=o;if(!c&&l.length===0)throw new Error("enum must have non-empty array");const h=l.length>=p.opts.loopEnum;let d;const f=()=>d??(d=(0,e.useFunc)(a,r.default));let v;if(h||c)v=a.let("valid"),o.block$data(v,g);else{if(!Array.isArray(l))throw new Error("ajv implementation error");const y=a.const("vSchema",u);v=(0,t.or)(...l.map((_,b)=>w(y,b)))}o.pass(v);function g(){a.assign(v,!1),a.forOf("v",u,y=>a.if((0,t._)`${f()}(${i}, ${y})`,()=>a.assign(v,!0).break()))}function w(y,_){const b=l[_];return typeof b=="object"&&b!==null?(0,t._)`${f()}(${i}, ${y}[${_}])`:(0,t._)`${i} === ${b}`}}};return na.default=s,na}var hp;function G_(){if(hp)return Ho;hp=1,Object.defineProperty(Ho,"__esModule",{value:!0});const t=j_(),e=q_(),r=D_(),n=U_(),s=Z_(),o=F_(),a=V_(),i=H_(),c=B_(),l=J_(),u=[t.default,e.default,r.default,n.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return Ho.default=u,Ho}var sa={},$n={},mp;function gp(){if(mp)return $n;mp=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.validateAdditionalItems=void 0;const t=Ce(),e=Ae(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){const{parentSchema:a,it:i}=o,{items:c}=a;if(!Array.isArray(c)){(0,e.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,c)}};function s(o,a){const{gen:i,schema:c,data:l,keyword:u,it:p}=o;p.items=!0;const h=i.const("len",(0,t._)`${l}.length`);if(c===!1)o.setParams({len:a.length}),o.pass((0,t._)`${h} <= ${a.length}`);else if(typeof c=="object"&&!(0,e.alwaysValidSchema)(p,c)){const f=i.var("valid",(0,t._)`${h} <= ${a.length}`);i.if((0,t.not)(f),()=>d(f)),o.ok(f)}function d(f){i.forRange("i",a.length,h,v=>{o.subschema({keyword:u,dataProp:v,dataPropType:e.Type.Num},f),p.allErrors||i.if((0,t.not)(f),()=>i.break())})}}return $n.validateAdditionalItems=s,$n.default=n,$n}var oa={},En={},yp;function _p(){if(yp)return En;yp=1,Object.defineProperty(En,"__esModule",{value:!0}),En.validateTuple=void 0;const t=Ce(),e=Ae(),r=Vt(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:a,it:i}=o;if(Array.isArray(a))return s(o,"additionalItems",a);i.items=!0,!(0,e.alwaysValidSchema)(i,a)&&o.ok((0,r.validateArray)(o))}};function s(o,a,i=o.schema){const{gen:c,parentSchema:l,data:u,keyword:p,it:h}=o;v(l),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=e.mergeEvaluated.items(c,i.length,h.items));const d=c.name("valid"),f=c.const("len",(0,t._)`${u}.length`);i.forEach((g,w)=>{(0,e.alwaysValidSchema)(h,g)||(c.if((0,t._)`${f} > ${w}`,()=>o.subschema({keyword:p,schemaProp:w,dataProp:w},d)),o.ok(d))});function v(g){const{opts:w,errSchemaPath:y}=h,_=i.length,b=_===g.minItems&&(_===g.maxItems||g[a]===!1);if(w.strictTuples&&!b){const k=`"${p}" is ${_}-tuple, but minItems or maxItems/${a} are not specified or different at path "${y}"`;(0,e.checkStrictMode)(h,k,w.strictTuples)}}}return En.validateTuple=s,En.default=n,En}var vp;function W_(){if(vp)return oa;vp=1,Object.defineProperty(oa,"__esModule",{value:!0});const t=_p(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return oa.default=e,oa}var aa={},wp;function K_(){if(wp)return aa;wp=1,Object.defineProperty(aa,"__esModule",{value:!0});const t=Ce(),e=Ae(),r=Vt(),n=gp(),o={keyword:"items",type:"array",schemaType:["object","boolean"],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{schema:i,parentSchema:c,it:l}=a,{prefixItems:u}=c;l.items=!0,!(0,e.alwaysValidSchema)(l,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return aa.default=o,aa}var ia={},bp;function Y_(){if(bp)return ia;bp=1,Object.defineProperty(ia,"__esModule",{value:!0});const t=Ce(),e=Ae(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:o}})=>o===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 ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${o}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:c,it:l}=s;let u,p;const{minContains:h,maxContains:d}=i;l.opts.next?(u=h===void 0?1:h,p=d):u=1;const f=o.const("len",(0,t._)`${c}.length`);if(s.setParams({min:u,max:p}),p===void 0&&u===0){(0,e.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&u>p){(0,e.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(l,a)){let _=(0,t._)`${f} >= ${u}`;p!==void 0&&(_=(0,t._)`${_} && ${f} <= ${p}`),s.pass(_);return}l.items=!0;const v=o.name("valid");p===void 0&&u===1?w(v,()=>o.if(v,()=>o.break())):u===0?(o.let(v,!0),p!==void 0&&o.if((0,t._)`${c}.length > 0`,g)):(o.let(v,!1),g()),s.result(v,()=>s.reset());function g(){const _=o.name("_valid"),b=o.let("count",0);w(_,()=>o.if(_,()=>y(b)))}function w(_,b){o.forRange("i",0,f,k=>{s.subschema({keyword:"contains",dataProp:k,dataPropType:e.Type.Num,compositeRule:!0},_),b()})}function y(_){o.code((0,t._)`${_}++`),p===void 0?o.if((0,t._)`${_} >= ${u}`,()=>o.assign(v,!0).break()):(o.if((0,t._)`${_} > ${p}`,()=>o.assign(v,!1).break()),u===1?o.assign(v,!0):o.if((0,t._)`${_} >= ${u}`,()=>o.assign(v,!0)))}}};return ia.default=n,ia}var ec={},kp;function Q_(){return kp||(kp=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Ce(),r=Ae(),n=Vt();t.error={message:({params:{property:c,depsCount:l,deps:u}})=>{const p=l===1?"property":"properties";return(0,e.str)`must have ${p} ${u} when property ${c} is present`},params:({params:{property:c,depsCount:l,deps:u,missingProperty:p}})=>(0,e._)`{property: ${c},
6
- missingProperty: ${p},
7
- depsCount: ${l},
8
- deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[l,u]=o(c);a(c,l),i(c,u)}};function o({schema:c}){const l={},u={};for(const p in c){if(p==="__proto__")continue;const h=Array.isArray(c[p])?l:u;h[p]=c[p]}return[l,u]}function a(c,l=c.schema){const{gen:u,data:p,it:h}=c;if(Object.keys(l).length===0)return;const d=u.let("missing");for(const f in l){const v=l[f];if(v.length===0)continue;const g=(0,n.propertyInData)(u,p,f,h.opts.ownProperties);c.setParams({property:f,depsCount:v.length,deps:v.join(", ")}),h.allErrors?u.if(g,()=>{for(const w of v)(0,n.checkReportMissingProp)(c,w)}):(u.if((0,e._)`${g} && (${(0,n.checkMissingProp)(c,v,d)})`),(0,n.reportMissingProp)(c,d),u.else())}}t.validatePropertyDeps=a;function i(c,l=c.schema){const{gen:u,data:p,keyword:h,it:d}=c,f=u.name("valid");for(const v in l)(0,r.alwaysValidSchema)(d,l[v])||(u.if((0,n.propertyInData)(u,p,v,d.opts.ownProperties),()=>{const g=c.subschema({keyword:h,schemaProp:v},f);c.mergeValidEvaluated(g,f)},()=>u.var(f,!0)),c.ok(f))}t.validateSchemaDeps=i,t.default=s})(ec)),ec}var ca={},Sp;function X_(){if(Sp)return ca;Sp=1,Object.defineProperty(ca,"__esModule",{value:!0});const t=Ce(),e=Ae(),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:o,schema:a,data:i,it:c}=s;if((0,e.alwaysValidSchema)(c,a))return;const l=o.name("valid");o.forIn("key",i,u=>{s.setParams({propertyName:u}),s.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},l),o.if((0,t.not)(l),()=>{s.error(!0),c.allErrors||o.break()})}),s.ok(l)}};return ca.default=n,ca}var la={},Tp;function Cp(){if(Tp)return la;Tp=1,Object.defineProperty(la,"__esModule",{value:!0});const t=Vt(),e=Ce(),r=Lr(),n=Ae(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:c,parentSchema:l,data:u,errsCount:p,it:h}=a;if(!p)throw new Error("ajv implementation error");const{allErrors:d,opts:f}=h;if(h.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,c))return;const v=(0,t.allSchemaProperties)(l.properties),g=(0,t.allSchemaProperties)(l.patternProperties);w(),a.ok((0,e._)`${p} === ${r.default.errors}`);function w(){i.forIn("key",u,S=>{!v.length&&!g.length?b(S):i.if(y(S),()=>b(S))})}function y(S){let T;if(v.length>8){const x=(0,n.schemaRefOrVal)(h,l.properties,"properties");T=(0,t.isOwnProperty)(i,x,S)}else v.length?T=(0,e.or)(...v.map(x=>(0,e._)`${S} === ${x}`)):T=e.nil;return g.length&&(T=(0,e.or)(T,...g.map(x=>(0,e._)`${(0,t.usePattern)(a,x)}.test(${S})`))),(0,e.not)(T)}function _(S){i.code((0,e._)`delete ${u}[${S}]`)}function b(S){if(f.removeAdditional==="all"||f.removeAdditional&&c===!1){_(S);return}if(c===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof c=="object"&&!(0,n.alwaysValidSchema)(h,c)){const T=i.name("valid");f.removeAdditional==="failing"?(k(S,T,!1),i.if((0,e.not)(T),()=>{a.reset(),_(S)})):(k(S,T),d||i.if((0,e.not)(T),()=>i.break()))}}function k(S,T,x){const R={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};x===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(R,T)}}};return la.default=o,la}var ua={},$p;function ev(){if($p)return ua;$p=1,Object.defineProperty(ua,"__esModule",{value:!0});const t=jo(),e=Vt(),r=Ae(),n=Cp(),s={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,parentSchema:c,data:l,it:u}=o;u.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(u,n.default,"additionalProperties"));const p=(0,e.allSchemaProperties)(i);for(const g of p)u.definedProperties.add(g);u.opts.unevaluated&&p.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(p),u.props));const h=p.filter(g=>!(0,r.alwaysValidSchema)(u,i[g]));if(h.length===0)return;const d=a.name("valid");for(const g of h)f(g)?v(g):(a.if((0,e.propertyInData)(a,l,g,u.opts.ownProperties)),v(g),u.allErrors||a.else().var(d,!0),a.endIf()),o.it.definedProperties.add(g),o.ok(d);function f(g){return u.opts.useDefaults&&!u.compositeRule&&i[g].default!==void 0}function v(g){o.subschema({keyword:"properties",schemaProp:g,dataProp:g},d)}}};return ua.default=s,ua}var da={},Ep;function tv(){if(Ep)return da;Ep=1,Object.defineProperty(da,"__esModule",{value:!0});const t=Vt(),e=Ce(),r=Ae(),n=Ae(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,data:c,parentSchema:l,it:u}=o,{opts:p}=u,h=(0,t.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const f=p.strictSchema&&!p.allowMatchingProperties&&l.properties,v=a.name("valid");u.props!==!0&&!(u.props instanceof e.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:g}=u;w();function w(){for(const b of h)f&&y(b),u.allErrors?_(b):(a.var(v,!0),_(b),a.if(v))}function y(b){for(const k in f)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function _(b){a.forIn("key",c,k=>{a.if((0,e._)`${(0,t.usePattern)(o,b)}.test(${k})`,()=>{const S=d.includes(b);S||o.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},v),u.opts.unevaluated&&g!==!0?a.assign((0,e._)`${g}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,e.not)(v),()=>a.break())})})}}};return da.default=s,da}var pa={},xp;function rv(){if(xp)return pa;xp=1,Object.defineProperty(pa,"__esModule",{value:!0});const t=Ae(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:o}=r;if((0,t.alwaysValidSchema)(o,s)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return pa.default=e,pa}var fa={},Ip;function nv(){if(Ip)return fa;Ip=1,Object.defineProperty(fa,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Vt().validateUnion,error:{message:"must match a schema in anyOf"}};return fa.default=e,fa}var ha={},Rp;function sv(){if(Rp)return ha;Rp=1,Object.defineProperty(ha,"__esModule",{value:!0});const t=Ce(),e=Ae(),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:o,schema:a,parentSchema:i,it:c}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(c.opts.discriminator&&i.discriminator)return;const l=a,u=o.let("valid",!1),p=o.let("passing",null),h=o.name("_valid");s.setParams({passing:p}),o.block(d),s.result(u,()=>s.reset(),()=>s.error(!0));function d(){l.forEach((f,v)=>{let g;(0,e.alwaysValidSchema)(c,f)?o.var(h,!0):g=s.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},h),v>0&&o.if((0,t._)`${h} && ${u}`).assign(u,!1).assign(p,(0,t._)`[${p}, ${v}]`).else(),o.if(h,()=>{o.assign(u,!0),o.assign(p,v),g&&s.mergeEvaluated(g,t.Name)})})}}};return ha.default=n,ha}var ma={},Pp;function ov(){if(Pp)return ma;Pp=1,Object.defineProperty(ma,"__esModule",{value:!0});const t=Ae(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:o}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((i,c)=>{if((0,t.alwaysValidSchema)(o,i))return;const l=r.subschema({keyword:"allOf",schemaProp:c},a);r.ok(a),r.mergeEvaluated(l)})}};return ma.default=e,ma}var ga={},Op;function av(){if(Op)return ga;Op=1,Object.defineProperty(ga,"__esModule",{value:!0});const t=Ce(),e=Ae(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:o})=>(0,t.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,t._)`{failingKeyword: ${o.ifClause}}`},code(o){const{gen:a,parentSchema:i,it:c}=o;i.then===void 0&&i.else===void 0&&(0,e.checkStrictMode)(c,'"if" without "then" and "else" is ignored');const l=s(c,"then"),u=s(c,"else");if(!l&&!u)return;const p=a.let("valid",!0),h=a.name("_valid");if(d(),o.reset(),l&&u){const v=a.let("ifClause");o.setParams({ifClause:v}),a.if(h,f("then",v),f("else",v))}else l?a.if(h,f("then")):a.if((0,t.not)(h),f("else"));o.pass(p,()=>o.error(!0));function d(){const v=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);o.mergeEvaluated(v)}function f(v,g){return()=>{const w=o.subschema({keyword:v},h);a.assign(p,h),o.mergeValidEvaluated(w,p),g?a.assign(g,(0,t._)`${v}`):o.setParams({ifClause:v})}}}};function s(o,a){const i=o.schema[a];return i!==void 0&&!(0,e.alwaysValidSchema)(o,i)}return ga.default=n,ga}var ya={},Ap;function iv(){if(Ap)return ya;Ap=1,Object.defineProperty(ya,"__esModule",{value:!0});const t=Ae(),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 ya.default=e,ya}var Mp;function cv(){if(Mp)return sa;Mp=1,Object.defineProperty(sa,"__esModule",{value:!0});const t=gp(),e=W_(),r=_p(),n=K_(),s=Y_(),o=Q_(),a=X_(),i=Cp(),c=ev(),l=tv(),u=rv(),p=nv(),h=sv(),d=ov(),f=av(),v=iv();function g(w=!1){const y=[u.default,p.default,h.default,d.default,f.default,v.default,a.default,i.default,o.default,c.default,l.default];return w?y.push(e.default,n.default):y.push(t.default,r.default),y.push(s.default),y}return sa.default=g,sa}var _a={},va={},Np;function lv(){if(Np)return va;Np=1,Object.defineProperty(va,"__esModule",{value:!0});const t=Ce(),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:o,data:a,$data:i,schema:c,schemaCode:l,it:u}=n,{opts:p,errSchemaPath:h,schemaEnv:d,self:f}=u;if(!p.validateFormats)return;i?v():g();function v(){const w=o.scopeValue("formats",{ref:f.formats,code:p.code.formats}),y=o.const("fDef",(0,t._)`${w}[${l}]`),_=o.let("fType"),b=o.let("format");o.if((0,t._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>o.assign(_,(0,t._)`${y}.type || "string"`).assign(b,(0,t._)`${y}.validate`),()=>o.assign(_,(0,t._)`"string"`).assign(b,y)),n.fail$data((0,t.or)(k(),S()));function k(){return p.strictSchema===!1?t.nil:(0,t._)`${l} && !${b}`}function S(){const T=d.$async?(0,t._)`(${y}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,t._)`${b}(${a})`,x=(0,t._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${a}))`;return(0,t._)`${b} && ${b} !== true && ${_} === ${s} && !${x}`}}function g(){const w=f.formats[c];if(!w){k();return}if(w===!0)return;const[y,_,b]=S(w);y===s&&n.pass(T());function k(){if(p.strictSchema===!1){f.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${c}" ignored in schema at path "${h}"`}}function S(x){const R=x instanceof RegExp?(0,t.regexpCode)(x):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(c)}`:void 0,j=o.scopeValue("formats",{key:c,ref:x,code:R});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,t._)`${j}.validate`]:["string",x,j]}function T(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!d.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${a})`}return typeof _=="function"?(0,t._)`${b}(${a})`:(0,t._)`${b}.test(${a})`}}}};return va.default=r,va}var Lp;function uv(){if(Lp)return _a;Lp=1,Object.defineProperty(_a,"__esModule",{value:!0});const e=[lv().default];return _a.default=e,_a}var on={},jp;function dv(){return jp||(jp=1,Object.defineProperty(on,"__esModule",{value:!0}),on.contentVocabulary=on.metadataVocabulary=void 0,on.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],on.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),on}var qp;function pv(){if(qp)return Zo;qp=1,Object.defineProperty(Zo,"__esModule",{value:!0});const t=L_(),e=G_(),r=cv(),n=uv(),s=dv(),o=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return Zo.default=o,Zo}var wa={},ms={},zp;function fv(){if(zp)return ms;zp=1,Object.defineProperty(ms,"__esModule",{value:!0}),ms.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||(ms.DiscrError=t={})),ms}var Dp;function hv(){if(Dp)return wa;Dp=1,Object.defineProperty(wa,"__esModule",{value:!0});const t=Ce(),e=fv(),r=Ki(),n=Do(),s=Ae(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:c}})=>i===e.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:i,tag:c,tagName:l}})=>(0,t._)`{error: ${i}, tag: ${l}, tagValue: ${c}}`},code(i){const{gen:c,data:l,schema:u,parentSchema:p,it:h}=i,{oneOf:d}=p;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const v=c.let("valid",!1),g=c.const("tag",(0,t._)`${l}${(0,t.getProperty)(f)}`);c.if((0,t._)`typeof ${g} == "string"`,()=>w(),()=>i.error(!1,{discrError:e.DiscrError.Tag,tag:g,tagName:f})),i.ok(v);function w(){const b=_();c.if(!1);for(const k in b)c.elseIf((0,t._)`${g} === ${k}`),c.assign(v,y(b[k]));c.else(),i.error(!1,{discrError:e.DiscrError.Mapping,tag:g,tagName:f}),c.endIf()}function y(b){const k=c.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,t.Name),k}function _(){var b;const k={},S=x(p);let T=!0;for(let O=0;O<d.length;O++){let D=d[O];if(D?.$ref&&!(0,s.schemaHasRulesButRef)(D,h.self.RULES)){const V=D.$ref;if(D=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,V),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(h.opts.uriResolver,h.baseId,V)}const U=(b=D?.properties)===null||b===void 0?void 0:b[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);T=T&&(S||x(D)),R(U,O)}if(!T)throw new Error(`discriminator: "${f}" must be required`);return k;function x({required:O}){return Array.isArray(O)&&O.includes(f)}function R(O,D){if(O.const)j(O.const,D);else if(O.enum)for(const U of O.enum)j(U,D);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function j(O,D){if(typeof O!="string"||O in k)throw new Error(`discriminator: "${f}" values must be unique strings`);k[O]=D}}}};return wa.default=a,wa}const mv={$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 Up;function Zp(){return Up||(Up=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=A_(),n=pv(),s=hv(),o=mv,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(f,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=jo();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Ce();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var p=Wi();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var h=Do();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})(Po,Po.exports)),Po.exports}var gv=Zp();const Fp=rn(gv);var Re;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(const a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Re||(Re={}));var tc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tc||(tc={}));const se=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),br=t=>{switch(typeof t){case"undefined":return se.undefined;case"string":return se.string;case"number":return Number.isNaN(t)?se.nan:se.number;case"boolean":return se.boolean;case"function":return se.function;case"bigint":return se.bigint;case"symbol":return se.symbol;case"object":return Array.isArray(t)?se.array:t===null?se.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?se.promise:typeof Map<"u"&&t instanceof Map?se.map:typeof Set<"u"&&t instanceof Set?se.set:typeof Date<"u"&&t instanceof Date?se.date:se.object;default:return se.unknown}},Y=Re.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"]),yv=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class It 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(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof It))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.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 o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}It.create=t=>new It(t);const xn=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===se.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Re.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Re.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Re.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Re.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.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}"`:Re.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.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 Y.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 Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Re.assertNever(t)}return{message:r}};let Vp=xn;function _v(t){Vp=t}function ba(){return Vp}const ka=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)i=l(a,{data:e,defaultError:i}).message;return{...s,path:o,message:i}},vv=[];function ee(t,e){const r=ba(),n=ka({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xn?void 0:xn].filter(s=>!!s)});t.common.issues.push(n)}class ut{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 ge;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 o=await s.key,a=await s.value;n.push({key:o,value:a})}return ut.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return ge;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const ge=Object.freeze({status:"aborted"}),In=t=>({status:"dirty",value:t}),ft=t=>({status:"valid",value:t}),rc=t=>t.status==="aborted",nc=t=>t.status==="dirty",an=t=>t.status==="valid",gs=t=>typeof Promise<"u"&&t instanceof Promise;var ce;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ce||(ce={}));class cr{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 Hp=(t,e)=>{if(an(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 It(t.common.issues);return this._error=r,this._error}}};function Se(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:(a,i)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??r??i.defaultError}},description:s}}let Te=class{get description(){return this._def.description}_getType(e){return br(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ut,ctx:{common:e.parent.common,data:e.data,parsedType:br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(gs(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:br(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Hp(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:br(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return an(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=>an(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:br(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(gs(s)?s:Promise.resolve(s));return Hp(n,o)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{const a=e(s),i=()=>o.addIssue({code:Y.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!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 Ht({schema:this,typeName:z.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 Bt.create(this,this._def)}nullable(){return zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return un.create(this)}promise(){return Mn.create(this,this._def)}or(e){return bs.create([this,e],this._def)}and(e){return ks.create(this,e,this._def)}transform(e){return new Ht({...Se(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Es({...Se(this._def),innerType:this,defaultValue:r,typeName:z.ZodDefault})}brand(){return new ac({typeName:z.ZodBranded,type:this,...Se(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new xs({...Se(this._def),innerType:this,catchValue:r,typeName:z.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Is.create(this,e)}readonly(){return Rs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const wv=/^c[^\s-]{8,}$/i,bv=/^[0-9a-z]+$/,kv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Sv=/^[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,Tv=/^[a-z0-9_-]{21}$/i,Cv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$v=/^[-+]?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)?)??$/,Ev=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let sc;const Iv=/^(?:(?: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])$/,Rv=/^(?:(?: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])$/,Pv=/^(([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]))$/,Ov=/^(([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])$/,Av=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bp="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Nv=new RegExp(`^${Bp}$`);function Jp(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 Lv(t){return new RegExp(`^${Jp(t)}$`)}function Gp(t){let e=`${Bp}T${Jp(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 jv(t,e){return!!((e==="v4"||!e)&&Iv.test(t)||(e==="v6"||!e)&&Pv.test(t))}function qv(t,e){if(!Cv.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 zv(t,e){return!!((e==="v4"||!e)&&Rv.test(t)||(e==="v6"||!e)&&Ov.test(t))}let Rn=class Ro extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==se.string){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.string,received:o.parsedType}),ge}const n=new ut;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?ee(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&ee(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Ev.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"email",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")sc||(sc=new RegExp(xv,"u")),sc.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"emoji",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Sv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"uuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Tv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"nanoid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")wv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")bv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cuid2",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")kv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"ulid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ee(s,{validation:"url",code:Y.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"regex",code:Y.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Gp(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Nv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Lv(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?$v.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"duration",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?jv(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"ip",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?qv(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"jwt",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?zv(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cidr",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Av.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"base64",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Mv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"base64url",code:Y.invalid_string,message:o.message}),n.dirty()):Re.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Y.invalid_string,...ce.errToObj(n)})}_addCheck(e){return new Ro({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ce.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ce.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ce.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ce.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ce.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ce.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ce.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ce.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ce.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ce.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ce.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ce.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ce.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,...ce.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,...ce.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ce.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ce.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ce.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ce.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ce.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ce.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ce.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ce.errToObj(r)})}nonempty(e){return this.min(1,ce.errToObj(e))}trim(){return new Ro({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ro({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ro({...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}};Rn.create=t=>new Rn({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...Se(t)});function Dv(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}let ys=class yd extends Te{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)!==se.number){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.number,received:o.parsedType}),ge}let n;const s=new ut;for(const o of this._def.checks)o.kind==="int"?Re.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Dv(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_finite,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ce.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ce.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ce.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ce.toString(r))}setLimit(e,r,n,s){return new yd({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new yd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ce.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ce.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ce.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ce.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ce.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"&&Re.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)}};ys.create=t=>new ys({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...Se(t)});class qr extends Te{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)!==se.bigint)return this._getInvalidInput(e);let n;const s=new ut;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return ee(r,{code:Y.invalid_type,expected:se.bigint,received:r.parsedType}),ge}gte(e,r){return this.setLimit("min",e,!0,ce.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ce.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ce.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ce.toString(r))}setLimit(e,r,n,s){return new qr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new qr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ce.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}}qr.create=t=>new qr({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...Se(t)});let _s=class extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==se.boolean){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.boolean,received:n.parsedType}),ge}return ft(e.data)}};_s.create=t=>new _s({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...Se(t)});class cn extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==se.date){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.date,received:o.parsedType}),ge}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_date}),ge}const n=new ut;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Re.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new cn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ce.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ce.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}}cn.create=t=>new cn({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...Se(t)});class Sa extends Te{_parse(e){if(this._getType(e)!==se.symbol){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.symbol,received:n.parsedType}),ge}return ft(e.data)}}Sa.create=t=>new Sa({typeName:z.ZodSymbol,...Se(t)});class vs extends Te{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.undefined,received:n.parsedType}),ge}return ft(e.data)}}vs.create=t=>new vs({typeName:z.ZodUndefined,...Se(t)});let ws=class extends Te{_parse(e){if(this._getType(e)!==se.null){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.null,received:n.parsedType}),ge}return ft(e.data)}};ws.create=t=>new ws({typeName:z.ZodNull,...Se(t)});let Pn=class extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return ft(e.data)}};Pn.create=t=>new Pn({typeName:z.ZodAny,...Se(t)});let ln=class extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ft(e.data)}};ln.create=t=>new ln({typeName:z.ZodUnknown,...Se(t)});let kr=class extends Te{_parse(e){const r=this._getOrReturnCtx(e);return ee(r,{code:Y.invalid_type,expected:se.never,received:r.parsedType}),ge}};kr.create=t=>new kr({typeName:z.ZodNever,...Se(t)});class Ta extends Te{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.void,received:n.parsedType}),ge}return ft(e.data)}}Ta.create=t=>new Ta({typeName:z.ZodVoid,...Se(t)});let un=class Ui extends Te{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==se.array)return ee(r,{code:Y.invalid_type,expected:se.array,received:r.parsedType}),ge;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,i=r.data.length<s.exactLength.value;(a||i)&&(ee(r,{code:a?Y.too_big:Y.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?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&&(ee(r,{code:Y.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&&(ee(r,{code:Y.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((a,i)=>s.type._parseAsync(new cr(r,a,r.path,i)))).then(a=>ut.mergeArray(n,a));const o=[...r.data].map((a,i)=>s.type._parseSync(new cr(r,a,r.path,i)));return ut.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new Ui({...this._def,minLength:{value:e,message:ce.toString(r)}})}max(e,r){return new Ui({...this._def,maxLength:{value:e,message:ce.toString(r)}})}length(e,r){return new Ui({...this._def,exactLength:{value:e,message:ce.toString(r)}})}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...Se(e)});function On(t){if(t instanceof Lt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Bt.create(On(n))}return new Lt({...t._def,shape:()=>e})}else return t instanceof un?new un({...t._def,type:On(t.element)}):t instanceof Bt?Bt.create(On(t.unwrap())):t instanceof zr?zr.create(On(t.unwrap())):t instanceof lr?lr.create(t.items.map(e=>On(e))):t}let Lt=class ir extends Te{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=Re.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==se.object){const l=this._getOrReturnCtx(e);return ee(l,{code:Y.invalid_type,expected:se.object,received:l.parsedType}),ge}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof kr&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||i.push(l);const c=[];for(const l of a){const u=o[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new cr(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof kr){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of i)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")i.length>0&&(ee(s,{code:Y.unrecognized_keys,keys:i}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of i){const p=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new cr(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of c){const p=await u.key,h=await u.value;l.push({key:p,value:h,alwaysSet:u.alwaysSet})}return l}).then(l=>ut.mergeObjectSync(n,l)):ut.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ce.errToObj,new ir({...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:ce.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ir({...this._def,unknownKeys:"strip"})}passthrough(){return new ir({...this._def,unknownKeys:"passthrough"})}extend(e){return new ir({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ir({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ir({...this._def,catchall:e})}pick(e){const r={};for(const n of Re.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ir({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Re.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ir({...this._def,shape:()=>r})}deepPartial(){return On(this)}partial(e){const r={};for(const n of Re.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new ir({...this._def,shape:()=>r})}required(e){const r={};for(const n of Re.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Bt;)o=o._def.innerType;r[n]=o}return new ir({...this._def,shape:()=>r})}keyof(){return Yp(Re.objectKeys(this.shape))}};Lt.create=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strip",catchall:kr.create(),typeName:z.ZodObject,...Se(e)}),Lt.strictCreate=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strict",catchall:kr.create(),typeName:z.ZodObject,...Se(e)}),Lt.lazycreate=(t,e)=>new Lt({shape:t,unknownKeys:"strip",catchall:kr.create(),typeName:z.ZodObject,...Se(e)});let bs=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new It(i.ctx.common.issues));return ee(r,{code:Y.invalid_union,unionErrors:a}),ge}if(r.common.async)return Promise.all(n.map(async o=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of n){const l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(c=>new It(c));return ee(r,{code:Y.invalid_union,unionErrors:i}),ge}}get options(){return this._def.options}};bs.create=(t,e)=>new bs({options:t,typeName:z.ZodUnion,...Se(e)});const Sr=t=>t instanceof Ss?Sr(t.schema):t instanceof Ht?Sr(t.innerType()):t instanceof Ts?[t.value]:t instanceof Cs?t.options:t instanceof $s?Re.objectValues(t.enum):t instanceof Es?Sr(t._def.innerType):t instanceof vs?[void 0]:t instanceof ws?[null]:t instanceof Bt?[void 0,...Sr(t.unwrap())]:t instanceof zr?[null,...Sr(t.unwrap())]:t instanceof ac||t instanceof Rs?Sr(t.unwrap()):t instanceof xs?Sr(t._def.innerType):[];let Wp=class v_ extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.object)return ee(r,{code:Y.invalid_type,expected:se.object,received:r.parsedType}),ge;const n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(ee(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ge)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const o of r){const a=Sr(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o)}}return new v_({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Se(n)})}};function oc(t,e){const r=br(t),n=br(e);if(t===e)return{valid:!0,data:t};if(r===se.object&&n===se.object){const s=Re.objectKeys(e),o=Re.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(const i of o){const c=oc(t[i],e[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(r===se.array&&n===se.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const a=t[o],i=e[o],c=oc(a,i);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===se.date&&n===se.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ks=class extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(rc(o)||rc(a))return ge;const i=oc(o.value,a.value);return i.valid?((nc(o)||nc(a))&&r.dirty(),{status:r.value,value:i.data}):(ee(n,{code:Y.invalid_intersection_types}),ge)};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(([o,a])=>s(o,a)):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}))}};ks.create=(t,e,r)=>new ks({left:t,right:e,typeName:z.ZodIntersection,...Se(r)});class lr extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.array)return ee(n,{code:Y.invalid_type,expected:se.array,received:n.parsedType}),ge;if(n.data.length<this._def.items.length)return ee(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ge;!this._def.rest&&n.data.length>this._def.items.length&&(ee(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((a,i)=>{const c=this._def.items[i]||this._def.rest;return c?c._parse(new cr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ut.mergeArray(r,a)):ut.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new lr({...this._def,rest:e})}}lr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lr({items:t,typeName:z.ZodTuple,rest:null,...Se(e)})};let Kp=class _d extends Te{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!==se.object)return ee(n,{code:Y.invalid_type,expected:se.object,received:n.parsedType}),ge;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in n.data)s.push({key:o._parse(new cr(n,i,n.path,i)),value:a._parse(new cr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ut.mergeObjectAsync(r,s):ut.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Te?new _d({keyType:e,valueType:r,typeName:z.ZodRecord,...Se(n)}):new _d({keyType:Rn.create(),valueType:e,typeName:z.ZodRecord,...Se(r)})}};class Ca extends Te{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!==se.map)return ee(n,{code:Y.invalid_type,expected:se.map,received:n.parsedType}),ge;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([i,c],l)=>({key:s._parse(new cr(n,i,n.path,[l,"key"])),value:o._parse(new cr(n,c,n.path,[l,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const c of a){const l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}}}}Ca.create=(t,e,r)=>new Ca({valueType:e,keyType:t,typeName:z.ZodMap,...Se(r)});class dn extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.set)return ee(n,{code:Y.invalid_type,expected:se.set,received:n.parsedType}),ge;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(ee(n,{code:Y.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&&(ee(n,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const o=this._def.valueType;function a(c){const l=new Set;for(const u of c){if(u.status==="aborted")return ge;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}const i=[...n.data.values()].map((c,l)=>o._parse(new cr(n,c,n.path,l)));return n.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(e,r){return new dn({...this._def,minSize:{value:e,message:ce.toString(r)}})}max(e,r){return new dn({...this._def,maxSize:{value:e,message:ce.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...Se(e)});class An extends Te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.function)return ee(r,{code:Y.invalid_type,expected:se.function,received:r.parsedType}),ge;function n(i,c){return ka({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ba(),xn].filter(l=>!!l),issueData:{code:Y.invalid_arguments,argumentsError:c}})}function s(i,c){return ka({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ba(),xn].filter(l=>!!l),issueData:{code:Y.invalid_return_type,returnTypeError:c}})}const o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mn){const i=this;return ft(async function(...c){const l=new It([]),u=await i._def.args.parseAsync(c,o).catch(d=>{throw l.addIssue(n(c,d)),l}),p=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(p,o).catch(d=>{throw l.addIssue(s(p,d)),l})})}else{const i=this;return ft(function(...c){const l=i._def.args.safeParse(c,o);if(!l.success)throw new It([n(c,l.error)]);const u=Reflect.apply(a,this,l.data),p=i._def.returns.safeParse(u,o);if(!p.success)throw new It([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new An({...this._def,args:lr.create(e).rest(ln.create())})}returns(e){return new An({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new An({args:e||lr.create([]).rest(ln.create()),returns:r||ln.create(),typeName:z.ZodFunction,...Se(n)})}}let Ss=class extends Te{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})}};Ss.create=(t,e)=>new Ss({getter:t,typeName:z.ZodLazy,...Se(e)});let Ts=class extends Te{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return ee(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),ge}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ts.create=(t,e)=>new Ts({value:t,typeName:z.ZodLiteral,...Se(e)});function Yp(t,e){return new Cs({values:t,typeName:z.ZodEnum,...Se(e)})}let Cs=class vd extends Te{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return ee(r,{expected:Re.joinValues(n),received:r.parsedType,code:Y.invalid_type}),ge}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 ee(r,{received:r.data,code:Y.invalid_enum_value,options:n}),ge}return ft(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 vd.create(e,{...this._def,...r})}exclude(e,r=this._def){return vd.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Cs.create=Yp;class $s extends Te{_parse(e){const r=Re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==se.string&&n.parsedType!==se.number){const s=Re.objectValues(r);return ee(n,{expected:Re.joinValues(s),received:n.parsedType,code:Y.invalid_type}),ge}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Re.objectValues(r);return ee(n,{received:n.data,code:Y.invalid_enum_value,options:s}),ge}return ft(e.data)}get enum(){return this._def.values}}$s.create=(t,e)=>new $s({values:t,typeName:z.ZodNativeEnum,...Se(e)});class Mn extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.promise&&r.common.async===!1)return ee(r,{code:Y.invalid_type,expected:se.promise,received:r.parsedType}),ge;const n=r.parsedType===se.promise?r.data:Promise.resolve(r.data);return ft(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Mn.create=(t,e)=>new Mn({type:t,typeName:z.ZodPromise,...Se(e)});class Ht extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{ee(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return ge;const c=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return c.status==="aborted"?ge:c.status==="dirty"||r.value==="dirty"?In(c.value):c});{if(r.value==="aborted")return ge;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?ge:i.status==="dirty"||r.value==="dirty"?In(i.value):i}}if(s.type==="refinement"){const a=i=>{const c=s.refinement(i,o);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 i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!an(a))return ge;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>an(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:r.value,value:i})):ge);Re.assertNever(s)}}Ht.create=(t,e,r)=>new Ht({schema:t,typeName:z.ZodEffects,effect:e,...Se(r)}),Ht.createWithPreprocess=(t,e,r)=>new Ht({schema:e,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...Se(r)});let Bt=class extends Te{_parse(e){return this._getType(e)===se.undefined?ft(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:z.ZodOptional,...Se(e)});let zr=class extends Te{_parse(e){return this._getType(e)===se.null?ft(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:z.ZodNullable,...Se(e)});let Es=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===se.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Es.create=(t,e)=>new Es({innerType:t,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Se(e)});let xs=class extends Te{_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 gs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new It(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new It(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xs.create=(t,e)=>new xs({innerType:t,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Se(e)});class $a extends Te{_parse(e){if(this._getType(e)!==se.nan){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.nan,received:n.parsedType}),ge}return{status:"valid",value:e.data}}}$a.create=t=>new $a({typeName:z.ZodNaN,...Se(t)});const Uv=Symbol("zod_brand");class ac extends Te{_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 Is extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ge:o.status==="dirty"?(r.dirty(),In(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ge: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 Is({in:e,out:r,typeName:z.ZodPipeline})}}let Rs=class extends Te{_parse(e){const r=this._def.innerType._parse(e),n=s=>(an(s)&&(s.value=Object.freeze(s.value)),s);return gs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Rs.create=(t,e)=>new Rs({innerType:t,typeName:z.ZodReadonly,...Se(e)});function Qp(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Xp(t,e={},r){return t?Pn.create().superRefine((n,s)=>{const o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){const i=Qp(e,n),c=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:c})}});if(!o){const a=Qp(e,n),i=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:i})}}):Pn.create()}const Zv={object:Lt.lazycreate};var z;(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"})(z||(z={}));const Fv=(t,e={message:`Input not instance of ${t.name}`})=>Xp(r=>r instanceof t,e),ef=Rn.create,tf=ys.create,Vv=$a.create,Hv=qr.create,rf=_s.create,Bv=cn.create,Jv=Sa.create,Gv=vs.create,Wv=ws.create,Kv=Pn.create,Yv=ln.create,Qv=kr.create,Xv=Ta.create,ew=un.create,nf=Lt.create,tw=Lt.strictCreate,rw=bs.create,nw=Wp.create,sw=ks.create,ow=lr.create,aw=Kp.create,iw=Ca.create,cw=dn.create,lw=An.create,uw=Ss.create,dw=Ts.create,pw=Cs.create,fw=$s.create,hw=Mn.create,sf=Ht.create,mw=Bt.create,gw=zr.create,yw=Ht.createWithPreprocess,_w=Is.create,vw=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Uv,DIRTY:In,EMPTY_PATH:vv,INVALID:ge,NEVER:ge,OK:ft,ParseStatus:ut,Schema:Te,ZodAny:Pn,ZodArray:un,ZodBigInt:qr,ZodBoolean:_s,ZodBranded:ac,ZodCatch:xs,ZodDate:cn,ZodDefault:Es,ZodDiscriminatedUnion:Wp,ZodEffects:Ht,ZodEnum:Cs,ZodError:It,get ZodFirstPartyTypeKind(){return z},ZodFunction:An,ZodIntersection:ks,ZodIssueCode:Y,ZodLazy:Ss,ZodLiteral:Ts,ZodMap:Ca,ZodNaN:$a,ZodNativeEnum:$s,ZodNever:kr,ZodNull:ws,ZodNullable:zr,ZodNumber:ys,ZodObject:Lt,ZodOptional:Bt,ZodParsedType:se,ZodPipeline:Is,ZodPromise:Mn,ZodReadonly:Rs,ZodRecord:Kp,ZodSchema:Te,ZodSet:dn,ZodString:Rn,ZodSymbol:Sa,ZodTransformer:Ht,ZodTuple:lr,ZodType:Te,ZodUndefined:vs,ZodUnion:bs,ZodUnknown:ln,ZodVoid:Ta,addIssueToContext:ee,any:Kv,array:ew,bigint:Hv,boolean:rf,coerce:{string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ys.create({...t,coerce:!0})),boolean:(t=>_s.create({...t,coerce:!0})),bigint:(t=>qr.create({...t,coerce:!0})),date:(t=>cn.create({...t,coerce:!0}))},custom:Xp,date:Bv,datetimeRegex:Gp,defaultErrorMap:xn,discriminatedUnion:nw,effect:sf,enum:pw,function:lw,getErrorMap:ba,getParsedType:br,instanceof:Fv,intersection:sw,isAborted:rc,isAsync:gs,isDirty:nc,isValid:an,late:Zv,lazy:uw,literal:dw,makeIssue:ka,map:iw,nan:Vv,nativeEnum:fw,never:Qv,null:Wv,nullable:gw,number:tf,object:nf,get objectUtil(){return tc},oboolean:()=>rf().optional(),onumber:()=>tf().optional(),optional:mw,ostring:()=>ef().optional(),pipeline:_w,preprocess:yw,promise:hw,quotelessJson:yv,record:aw,set:cw,setErrorMap:_v,strictObject:tw,string:ef,symbol:Jv,transformer:sf,tuple:ow,undefined:Gv,union:rw,unknown:Yv,get util(){return Re},void:Xv},Symbol.toStringTag,{value:"Module"})),of=Object.freeze({status:"aborted"});function J(t,e,r){function n(i,c){var l;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(l=i._zod).traits??(l.traits=new Set),i._zod.traits.add(t),e(i,c);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=c}const s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function a(i){var c;const l=r?.Parent?new o:this;n(l,i),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}class Ps extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const af={};function Dr(t){return af}function cf(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 ww(t,e){return typeof e=="bigint"?e.toString():e}function ic(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function cc(t){return t==null}function lc(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function bw(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function Me(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 Os(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function As(t){return JSON.stringify(t)}const lf=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ea(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const kw=ic(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function xa(t){if(Ea(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ea(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Sw=new Set(["string","number","symbol"]);function Ms(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ur(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(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 Tw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Cw={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 $w(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 Ur(t,{...t._zod.def,shape:r,checks:[]})}function Ew(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 Ur(t,{...t._zod.def,shape:r,checks:[]})}function xw(t,e){if(!xa(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 Os(this,"shape",n),n},checks:[]};return Ur(t,r)}function Iw(t,e){return Ur(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Os(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Rw(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(const o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Ur(e,{...e._zod.def,shape:s,checks:[]})}function Pw(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(const o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Ur(e,{...e._zod.def,shape:s,checks:[]})}function Ns(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function pn(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ia(t){return typeof t=="string"?t:t?.message}function Zr(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Ia(t.inst?._zod.def?.error?.(t))??Ia(e?.error?.(t))??Ia(r.customError?.(t))??Ia(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function uc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ls(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const uf=(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,ww,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},df=J("$ZodError",uf),Ra=J("$ZodError",uf,{Parent:Error});function Ow(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 Aw(t,e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(t),n}const pf=t=>(e,r,n,s)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Ps;if(a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Zr(c,o,Dr())));throw lf(i,s?.callee),i}return a.value},Mw=pf(Ra),ff=t=>async(e,r,n,s)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Zr(c,o,Dr())));throw lf(i,s?.callee),i}return a.value},Nw=ff(Ra),hf=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Ps;return o.issues.length?{success:!1,error:new(t??df)(o.issues.map(a=>Zr(a,s,Dr())))}:{success:!0,data:o.value}},dc=hf(Ra),mf=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>Zr(a,s,Dr())))}:{success:!0,data:o.value}},pc=mf(Ra),Lw=/^[cC][^\s-]{8,}$/,jw=/^[0-9a-z]+$/,qw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zw=/^[0-9a-vA-V]{20}$/,Dw=/^[A-Za-z0-9]{27}$/,Uw=/^[a-zA-Z0-9_-]{21}$/,Zw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Fw=/^([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})$/,gf=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)$/,Vw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bw(){return new RegExp(Hw,"u")}const Jw=/^(?:(?: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])$/,Gw=/^(([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})$/,Ww=/^((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])$/,Kw=/^(([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])$/,Yw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yf=/^[A-Za-z0-9_-]*$/,Qw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Xw=/^\+(?:[0-9]){6,14}[0-9]$/,_f="(?:(?:\\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])))",eb=new RegExp(`^${_f}$`);function vf(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 tb(t){return new RegExp(`^${vf(t)}$`)}function rb(t){const e=vf({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(`^${_f}T(?:${n})$`)}const nb=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},sb=/^\d+$/,ob=/^-?\d+(?:\.\d+)?/i,ab=/true|false/i,ib=/null/i,cb=/^[^A-Z]*$/,lb=/^[^a-z]*$/,kt=J("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),wf={number:"number",bigint:"bigint",object:"date"},bf=J("$ZodCheckLessThan",(t,e)=>{kt.init(t,e);const r=wf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(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})}}),kf=J("$ZodCheckGreaterThan",(t,e)=>{kt.init(t,e);const r=wf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(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})}}),ub=J("$ZodCheckMultipleOf",(t,e)=>{kt.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):bw(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})}}),db=J("$ZodCheckNumberFormat",(t,e)=>{kt.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Cw[e.format];t._zod.onattach.push(a=>{const i=a._zod.bag;i.format=e.format,i.minimum=s,i.maximum=o,r&&(i.pattern=sb)}),t._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:i,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}}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}}),pb=J("$ZodCheckMaxLength",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(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 a=uc(s);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),fb=J("$ZodCheckMinLength",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(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 a=uc(s);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),hb=J("$ZodCheckLengthEquals",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(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,o=s.length;if(o===e.length)return;const a=uc(s),i=o>e.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Pa=J("$ZodCheckStringFormat",(t,e)=>{var r,n;kt.init(t,e),t._zod.onattach.push(s=>{const o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.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=()=>{})}),mb=J("$ZodCheckRegex",(t,e)=>{Pa.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})}}),gb=J("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=cb),Pa.init(t,e)}),yb=J("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=lb),Pa.init(t,e)}),_b=J("$ZodCheckIncludes",(t,e)=>{kt.init(t,e);const r=Ms(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.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})}}),vb=J("$ZodCheckStartsWith",(t,e)=>{kt.init(t,e);const r=new RegExp(`^${Ms(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})}}),wb=J("$ZodCheckEndsWith",(t,e)=>{kt.init(t,e);const r=new RegExp(`.*${Ms(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})}}),bb=J("$ZodCheckOverwrite",(t,e)=>{kt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class kb{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(a=>a),s=Math.min(...n.map(a=>a.length-a.trimStart().length)),o=n.map(a=>a.slice(s)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
10
- `))}}const Sb={major:4,minor:0,patch:0},Ze=J("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Sb;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const s of n)for(const o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,a,i)=>{let c=Ns(o),l;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(c)continue;const p=o.issues.length,h=u._zod.check(o);if(h instanceof Promise&&i?.async===!1)throw new Ps;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,o.issues.length!==p&&(c||(c=Ns(o,p)))});else{if(o.issues.length===p)continue;c||(c=Ns(o,p))}}return l?l.then(()=>o):o};t._zod.run=(o,a)=>{const i=t._zod.parse(o,a);if(i instanceof Promise){if(a.async===!1)throw new Ps;return i.then(c=>s(c,n,a))}return s(i,n,a)}}t["~standard"]={validate:s=>{try{const o=dc(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return pc(t,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),fc=J("$ZodString",(t,e)=>{Ze.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??nb(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}}),Je=J("$ZodStringFormat",(t,e)=>{Pa.init(t,e),fc.init(t,e)}),Tb=J("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Fw),Je.init(t,e)}),Cb=J("$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=gf(n))}else e.pattern??(e.pattern=gf());Je.init(t,e)}),$b=J("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Vw),Je.init(t,e)}),Eb=J("$ZodURL",(t,e)=>{Je.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),o=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:Qw.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("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),xb=J("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Bw()),Je.init(t,e)}),Ib=J("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Uw),Je.init(t,e)}),Rb=J("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Lw),Je.init(t,e)}),Pb=J("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=jw),Je.init(t,e)}),Ob=J("$ZodULID",(t,e)=>{e.pattern??(e.pattern=qw),Je.init(t,e)}),Ab=J("$ZodXID",(t,e)=>{e.pattern??(e.pattern=zw),Je.init(t,e)}),Mb=J("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Dw),Je.init(t,e)}),Nb=J("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=rb(e)),Je.init(t,e)}),Lb=J("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=eb),Je.init(t,e)}),jb=J("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=tb(e)),Je.init(t,e)}),qb=J("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Zw),Je.init(t,e)}),zb=J("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Jw),Je.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),Db=J("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Gw),Je.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})}}}),Ub=J("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ww),Je.init(t,e)}),Zb=J("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Kw),Je.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>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 Sf(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Fb=J("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Yw),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Sf(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Vb(t){if(!yf.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Sf(r)}const Hb=J("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=yf),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Vb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Bb=J("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Xw),Je.init(t,e)});function Jb(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 Gb=J("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=r=>{Jb(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Tf=J("$ZodNumber",(t,e)=>{Ze.init(t,e),t._zod.pattern=t._zod.bag.pattern??ob,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 o=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,...o?{received:o}:{}}),r}}),Wb=J("$ZodNumber",(t,e)=>{db.init(t,e),Tf.init(t,e)}),Kb=J("$ZodBoolean",(t,e)=>{Ze.init(t,e),t._zod.pattern=ab,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}}),Yb=J("$ZodNull",(t,e)=>{Ze.init(t,e),t._zod.pattern=ib,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}}),Qb=J("$ZodAny",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),Xb=J("$ZodUnknown",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),e3=J("$ZodNever",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Cf(t,e,r){t.issues.length&&e.issues.push(...pn(r,t.issues)),e.value[r]=t.value}const t3=J("$ZodArray",(t,e)=>{Ze.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 o=[];for(let a=0;a<s.length;a++){const i=s[a],c=e.element._zod.run({value:i,issues:[]},n);c instanceof Promise?o.push(c.then(l=>Cf(l,r,a))):Cf(c,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function Oa(t,e,r){t.issues.length&&e.issues.push(...pn(r,t.issues)),e.value[r]=t.value}function $f(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(...pn(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const Ef=J("$ZodObject",(t,e)=>{Ze.init(t,e);const r=ic(()=>{const p=Object.keys(e.shape);for(const d of p)if(!(e.shape[d]instanceof Ze))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=Tw(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(h)}});Me(t._zod,"propValues",()=>{const p=e.shape,h={};for(const d in p){const f=p[d]._zod;if(f.values){h[d]??(h[d]=new Set);for(const v of f.values)h[d].add(v)}}return h});const n=p=>{const h=new kb(["shape","payload","ctx"]),d=r.value,f=y=>{const _=As(y);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let g=0;for(const y of d.keys)v[y]=`key_${g++}`;h.write("const newResult = {}");for(const y of d.keys)if(d.optionalKeys.has(y)){const _=v[y];h.write(`const ${_} = ${f(y)};`);const b=As(y);h.write(`
11
- if (${_}.issues.length) {
12
- if (input[${b}] === undefined) {
13
- if (${b} in input) {
14
- newResult[${b}] = undefined;
1
+ (function(Re,Pn){typeof exports=="object"&&typeof module<"u"?Pn(exports):typeof define=="function"&&define.amd?define(["exports"],Pn):(Re=typeof globalThis<"u"?globalThis:Re||self,Pn(Re.WebMCP={}))})(this,(function(Re){"use strict";function Pn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ga={exports:{}},Ml={},Fr={},Mn={},Ol={},Nl={},Al={},hp;function ya(){return hp||(hp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((m,S)=>`${m}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((m,S)=>(S instanceof r&&(m[S.str]=(m[S.str]||0)+1),m),{})}}e._Code=n,e.nil=new n("");function o(w,...v){const m=[w[0]];let S=0;for(;S<v.length;)i(m,v[S]),m.push(w[++S]);return new n(m)}e._=o;const s=new n("+");function a(w,...v){const m=[f(w[0])];let S=0;for(;S<v.length;)m.push(s),i(m,v[S]),m.push(s,f(w[++S]));return l(m),new n(m)}e.str=a;function i(w,v){v instanceof n?w.push(...v._items):v instanceof r?w.push(v):w.push(h(v))}e.addCodeArg=i;function l(w){let v=1;for(;v<w.length-1;){if(w[v]===s){const m=c(w[v-1],w[v+1]);if(m!==void 0){w.splice(v-1,3,m);continue}w[v++]="+"}v++}}function c(w,v){if(v==='""')return w;if(w==='""')return v;if(typeof w=="string")return v instanceof r||w[w.length-1]!=='"'?void 0:typeof v!="string"?`${w.slice(0,-1)}${v}"`:v[0]==='"'?w.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(w instanceof r))return`"${w}${v.slice(1)}`}function u(w,v){return v.emptyStr()?w:w.emptyStr()?v:a`${w}${v}`}e.strConcat=u;function h(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:f(Array.isArray(w)?w.join(","):w)}function p(w){return new n(f(w))}e.stringify=p;function f(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function g(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=g;function _(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=_;function y(w){return new n(w.toString())}e.regexpCode=y})(Al)),Al}var ql={},mp;function gp(){return mp||(mp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ya();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${h}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:f}=p,g=(h=u.key)!==null&&h!==void 0?h:u.ref;let _=this._values[f];if(_){const v=_.get(g);if(v)return v}else _=this._values[f]=new Map;_.set(g,p);const y=this._scope[f]||(this._scope[f]=[]),w=y.length;return y[w]=u.ref,p.setValue(u,{property:f,itemIndex:w}),p}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,t._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,h)}_reduceValues(c,u,h={},p){let f=t.nil;for(const g in c){const _=c[g];if(!_)continue;const y=h[g]=h[g]||new Map;_.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let v=u(w);if(v){const m=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${m} ${w} = ${v};${this.opts._n}`}else if(v=p?.(w))f=(0,t._)`${f}${v}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(ql)),ql}var yp;function Ae(){return yp||(yp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=ya(),r=gp();var n=ya();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=gp();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,M){return this}}class a extends s{constructor(E,M,D){super(),this.varKind=E,this.name=M,this.rhs=D}render({es5:E,_n:M}){const D=E?r.varKinds.var:this.varKind,K=this.rhs===void 0?"":` = ${this.rhs}`;return`${D} ${this.name}${K};`+M}optimizeNames(E,M){if(E[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,E,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,M,D){super(),this.lhs=E,this.rhs=M,this.sideEffects=D}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,M){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,E,M),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return N(E,this.rhs)}}class l extends i{constructor(E,M,D,K){super(E,D,K),this.op=M}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class h extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class p extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,M){return this.code=U(this.code,E,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((M,D)=>M+D.render(E),"")}optimizeNodes(){const{nodes:E}=this;let M=E.length;for(;M--;){const D=E[M].optimizeNodes();Array.isArray(D)?E.splice(M,1,...D):D?E[M]=D:E.splice(M,1)}return E.length>0?this:void 0}optimizeNames(E,M){const{nodes:D}=this;let K=D.length;for(;K--;){const ne=D[K];ne.optimizeNames(E,M)||(G(E,ne.names),D.splice(K,1))}return D.length>0?this:void 0}get names(){return this.nodes.reduce((E,M)=>A(E,M.names),{})}}class g extends f{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class _ extends f{}class y extends g{}y.kind="else";class w extends g{constructor(E,M){super(M),this.condition=E}render(E){let M=`if(${this.condition})`+super.render(E);return this.else&&(M+="else "+this.else.render(E)),M}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let M=this.else;if(M){const D=M.optimizeNodes();M=this.else=Array.isArray(D)?new y(D):D}if(M)return E===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(J(E),M instanceof w?[M]:M.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,M){var D;if(this.else=(D=this.else)===null||D===void 0?void 0:D.optimizeNames(E,M),!!(super.optimizeNames(E,M)||this.else))return this.condition=U(this.condition,E,M),this}get names(){const E=super.names;return N(E,this.condition),this.else&&A(E,this.else.names),E}}w.kind="if";class v extends g{}v.kind="for";class m extends v{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iteration=U(this.iteration,E,M),this}get names(){return A(super.names,this.iteration.names)}}class S extends v{constructor(E,M,D,K){super(),this.varKind=E,this.name=M,this.from=D,this.to=K}render(E){const M=E.es5?r.varKinds.var:this.varKind,{name:D,from:K,to:ne}=this;return`for(${M} ${D}=${K}; ${D}<${ne}; ${D}++)`+super.render(E)}get names(){const E=N(super.names,this.from);return N(E,this.to)}}class k extends v{constructor(E,M,D,K){super(),this.loop=E,this.varKind=M,this.name=D,this.iterable=K}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iterable=U(this.iterable,E,M),this}get names(){return A(super.names,this.iterable.names)}}class T extends g{constructor(E,M,D){super(),this.name=E,this.args=M,this.async=D}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}T.kind="func";class b extends f{render(E){return"return "+super.render(E)}}b.kind="return";class x extends g{render(E){let M="try"+super.render(E);return this.catch&&(M+=this.catch.render(E)),this.finally&&(M+=this.finally.render(E)),M}optimizeNodes(){var E,M;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(E,M){var D,K;return super.optimizeNames(E,M),(D=this.catch)===null||D===void 0||D.optimizeNames(E,M),(K=this.finally)===null||K===void 0||K.optimizeNames(E,M),this}get names(){const E=super.names;return this.catch&&A(E,this.catch.names),this.finally&&A(E,this.finally.names),E}}class I extends g{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}I.kind="catch";class L extends g{render(E){return"finally"+super.render(E)}}L.kind="finally";class O{constructor(E,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
2
+ `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,M){const D=this._extScope.value(E,M);return(this._values[D.prefix]||(this._values[D.prefix]=new Set)).add(D),D}getScopeValue(E,M){return this._extScope.getValue(E,M)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,M,D,K){const ne=this._scope.toName(M);return D!==void 0&&K&&(this._constants[ne.str]=D),this._leafNode(new a(E,ne,D)),ne}const(E,M,D){return this._def(r.varKinds.const,E,M,D)}let(E,M,D){return this._def(r.varKinds.let,E,M,D)}var(E,M,D){return this._def(r.varKinds.var,E,M,D)}assign(E,M,D){return this._leafNode(new i(E,M,D))}add(E,M){return this._leafNode(new l(E,e.operators.ADD,M))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const M=["{"];for(const[D,K]of E)M.length>1&&M.push(","),M.push(D),(D!==K||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,K));return M.push("}"),new t._Code(M)}if(E,M,D){if(this._blockNode(new w(E)),M&&D)this.code(M).else().code(D).endIf();else if(M)this.code(M).endIf();else if(D)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,M){return this._blockNode(E),M&&this.code(M).endFor(),this}for(E,M){return this._for(new m(E),M)}forRange(E,M,D,K,ne=this.opts.es5?r.varKinds.var:r.varKinds.let){const ae=this._scope.toName(E);return this._for(new S(ne,ae,M,D),()=>K(ae))}forOf(E,M,D,K=r.varKinds.const){const ne=this._scope.toName(E);if(this.opts.es5){const ae=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${ae}.length`,Ie=>{this.var(ne,(0,t._)`${ae}[${Ie}]`),D(ne)})}return this._for(new k("of",K,ne,M),()=>D(ne))}forIn(E,M,D,K=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${M})`,D);const ne=this._scope.toName(E);return this._for(new k("in",K,ne,M),()=>D(ne))}endFor(){return this._endBlockNode(v)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const M=new b;if(this._blockNode(M),this.code(E),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(b)}try(E,M,D){if(!M&&!D)throw new Error('CodeGen: "try" without "catch" and "finally"');const K=new x;if(this._blockNode(K),this.code(E),M){const ne=this.name("e");this._currNode=K.catch=new I(ne),M(ne)}return D&&(this._currNode=K.finally=new L,this.code(D)),this._endBlockNode(I,L)}throw(E){return this._leafNode(new h(E))}block(E,M){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(M),this}endBlock(E){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const D=this._nodes.length-M;if(D<0||E!==void 0&&D!==E)throw new Error(`CodeGen: wrong number of nodes: ${D} vs ${E} expected`);return this._nodes.length=M,this}func(E,M=t.nil,D,K){return this._blockNode(new T(E,M,D)),K&&this.code(K).endFunc(),this}endFunc(){return this._endBlockNode(T)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,M){const D=this._currNode;if(D instanceof E||M&&D instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${E.kind}/${M.kind}`:E.kind}"`)}_elseNode(E){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const M=this._nodes;M[M.length-1]=E}}e.CodeGen=O;function A(Z,E){for(const M in E)Z[M]=(Z[M]||0)+(E[M]||0);return Z}function N(Z,E){return E instanceof t._CodeOrName?A(Z,E.names):Z}function U(Z,E,M){if(Z instanceof t.Name)return D(Z);if(!K(Z))return Z;return new t._Code(Z._items.reduce((ne,ae)=>(ae instanceof t.Name&&(ae=D(ae)),ae instanceof t._Code?ne.push(...ae._items):ne.push(ae),ne),[]));function D(ne){const ae=M[ne.str];return ae===void 0||E[ne.str]!==1?ne:(delete E[ne.str],ae)}function K(ne){return ne instanceof t._Code&&ne._items.some(ae=>ae instanceof t.Name&&E[ae.str]===1&&M[ae.str]!==void 0)}}function G(Z,E){for(const M in E)Z[M]=(Z[M]||0)-(E[M]||0)}function J(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${H(Z)}`}e.not=J;const ue=R(e.operators.AND);function re(...Z){return Z.reduce(ue)}e.and=re;const ge=R(e.operators.OR);function V(...Z){return Z.reduce(ge)}e.or=V;function R(Z){return(E,M)=>E===t.nil?M:M===t.nil?E:(0,t._)`${H(E)} ${Z} ${H(M)}`}function H(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(Nl)),Nl}var qe={},vp;function Ue(){if(vp)return qe;vp=1,Object.defineProperty(qe,"__esModule",{value:!0}),qe.checkStrictMode=qe.getErrorPath=qe.Type=qe.useFunc=qe.setEvaluated=qe.evaluatedPropsToName=qe.mergeEvaluated=qe.eachItem=qe.unescapeJsonPointer=qe.escapeJsonPointer=qe.escapeFragment=qe.unescapeFragment=qe.schemaRefOrVal=qe.schemaHasRulesButRef=qe.schemaHasRules=qe.checkUnknownRules=qe.alwaysValidSchema=qe.toHash=void 0;const e=Ae(),t=ya();function r(k){const T={};for(const b of k)T[b]=!0;return T}qe.toHash=r;function n(k,T){return typeof T=="boolean"?T:Object.keys(T).length===0?!0:(o(k,T),!s(T,k.self.RULES.all))}qe.alwaysValidSchema=n;function o(k,T=k.schema){const{opts:b,self:x}=k;if(!b.strictSchema||typeof T=="boolean")return;const I=x.RULES.keywords;for(const L in T)I[L]||S(k,`unknown keyword: "${L}"`)}qe.checkUnknownRules=o;function s(k,T){if(typeof k=="boolean")return!k;for(const b in k)if(T[b])return!0;return!1}qe.schemaHasRules=s;function a(k,T){if(typeof k=="boolean")return!k;for(const b in k)if(b!=="$ref"&&T.all[b])return!0;return!1}qe.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:T},b,x,I){if(!I){if(typeof b=="number"||typeof b=="boolean")return b;if(typeof b=="string")return(0,e._)`${b}`}return(0,e._)`${k}${T}${(0,e.getProperty)(x)}`}qe.schemaRefOrVal=i;function l(k){return h(decodeURIComponent(k))}qe.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}qe.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}qe.escapeJsonPointer=u;function h(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}qe.unescapeJsonPointer=h;function p(k,T){if(Array.isArray(k))for(const b of k)T(b);else T(k)}qe.eachItem=p;function f({mergeNames:k,mergeToName:T,mergeValues:b,resultToName:x}){return(I,L,O,A)=>{const N=O===void 0?L:O instanceof e.Name?(L instanceof e.Name?k(I,L,O):T(I,L,O),O):L instanceof e.Name?(T(I,O,L),L):b(L,O);return A===e.Name&&!(N instanceof e.Name)?x(I,N):N}}qe.mergeEvaluated={props:f({mergeNames:(k,T,b)=>k.if((0,e._)`${b} !== true && ${T} !== undefined`,()=>{k.if((0,e._)`${T} === true`,()=>k.assign(b,!0),()=>k.assign(b,(0,e._)`${b} || {}`).code((0,e._)`Object.assign(${b}, ${T})`))}),mergeToName:(k,T,b)=>k.if((0,e._)`${b} !== true`,()=>{T===!0?k.assign(b,!0):(k.assign(b,(0,e._)`${b} || {}`),_(k,b,T))}),mergeValues:(k,T)=>k===!0?!0:{...k,...T},resultToName:g}),items:f({mergeNames:(k,T,b)=>k.if((0,e._)`${b} !== true && ${T} !== undefined`,()=>k.assign(b,(0,e._)`${T} === true ? true : ${b} > ${T} ? ${b} : ${T}`)),mergeToName:(k,T,b)=>k.if((0,e._)`${b} !== true`,()=>k.assign(b,T===!0?!0:(0,e._)`${b} > ${T} ? ${b} : ${T}`)),mergeValues:(k,T)=>k===!0?!0:Math.max(k,T),resultToName:(k,T)=>k.var("items",T)})};function g(k,T){if(T===!0)return k.var("props",!0);const b=k.var("props",(0,e._)`{}`);return T!==void 0&&_(k,b,T),b}qe.evaluatedPropsToName=g;function _(k,T,b){Object.keys(b).forEach(x=>k.assign((0,e._)`${T}${(0,e.getProperty)(x)}`,!0))}qe.setEvaluated=_;const y={};function w(k,T){return k.scopeValue("func",{ref:T,code:y[T.code]||(y[T.code]=new t._Code(T.code))})}qe.useFunc=w;var v;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(v||(qe.Type=v={}));function m(k,T,b){if(k instanceof e.Name){const x=T===v.Num;return b?x?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:x?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return b?(0,e.getProperty)(k).toString():"/"+u(k)}qe.getErrorPath=m;function S(k,T,b=k.opts.strictSchema){if(b){if(T=`strict mode: ${T}`,b===!0)throw new Error(T);k.self.logger.warn(T)}}return qe.checkStrictMode=S,qe}var va={},_p;function dn(){if(_p)return va;_p=1,Object.defineProperty(va,"__esModule",{value:!0});const e=Ae(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return va.default=t,va}var wp;function _a(){return wp||(wp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ae(),r=Ue(),n=dn();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,v,m){const{it:S}=y,{gen:k,compositeRule:T,allErrors:b}=S,x=h(y,w,v);m??(T||b)?l(k,x):c(S,(0,t._)`[${x}]`)}e.reportError=o;function s(y,w=e.keywordError,v){const{it:m}=y,{gen:S,compositeRule:k,allErrors:T}=m,b=h(y,w,v);l(S,b),k||T||c(m,n.default.vErrors)}e.reportExtraError=s;function a(y,w){y.assign(n.default.errors,w),y.if((0,t._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,t._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:y,keyword:w,schemaValue:v,data:m,errsCount:S,it:k}){if(S===void 0)throw new Error("ajv implementation error");const T=y.name("err");y.forRange("i",S,n.default.errors,b=>{y.const(T,(0,t._)`${n.default.vErrors}[${b}]`),y.if((0,t._)`${T}.instancePath === undefined`,()=>y.assign((0,t._)`${T}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),y.assign((0,t._)`${T}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(y.assign((0,t._)`${T}.schema`,v),y.assign((0,t._)`${T}.data`,m))})}e.extendErrors=i;function l(y,w){const v=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:v,validateName:m,schemaEnv:S}=y;S.$async?v.throw((0,t._)`new ${y.ValidationError}(${w})`):(v.assign((0,t._)`${m}.errors`,w),v.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(y,w,v){const{createErrors:m}=y.it;return m===!1?(0,t._)`{}`:p(y,w,v)}function p(y,w,v={}){const{gen:m,it:S}=y,k=[f(S,v),g(y,v)];return _(y,w,k),m.object(...k)}function f({errorPath:y},{instancePath:w}){const v=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:v,parentSchema:m}){let S=m?w:(0,t.str)`${w}/${y}`;return v&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,S]}function _(y,{params:w,message:v},m){const{keyword:S,data:k,schemaValue:T,it:b}=y,{opts:x,propertyName:I,topSchemaRef:L,schemaPath:O}=b;m.push([u.keyword,S],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),x.messages&&m.push([u.message,typeof v=="function"?v(y):v]),x.verbose&&m.push([u.schema,T],[u.parentSchema,(0,t._)`${L}${O}`],[n.default.data,k]),I&&m.push([u.propertyName,I])}})(Ol)),Ol}var bp;function V1(){if(bp)return Mn;bp=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.boolOrEmptySchema=Mn.topBoolOrEmptySchema=void 0;const e=_a(),t=Ae(),r=dn(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Mn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Mn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,h={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(h,n,void 0,l)}return Mn}var It={},On={},kp;function Tp(){if(kp)return On;kp=1,Object.defineProperty(On,"__esModule",{value:!0}),On.getRules=On.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}On.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return On.getRules=n,On}var Vr={},Cp;function Sp(){if(Cp)return Vr;Cp=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.shouldUseRule=Vr.shouldUseGroup=Vr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Vr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Vr.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return Vr.shouldUseRule=r,Vr}var Ip;function wa(){if(Ip)return It;Ip=1,Object.defineProperty(It,"__esModule",{value:!0}),It.reportTypeError=It.checkDataTypes=It.checkDataType=It.coerceAndCheckDataType=It.getJSONTypes=It.getSchemaTypes=It.DataType=void 0;const e=Tp(),t=Sp(),r=_a(),n=Ae(),o=Ue();var s;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(s||(It.DataType=s={}));function a(v){const m=i(v.type);if(m.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!m.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&m.push("null")}return m}It.getSchemaTypes=a;function i(v){const m=Array.isArray(v)?v:v?[v]:[];if(m.every(e.isJSONType))return m;throw new Error("type must be JSONType or JSONType[]: "+m.join(","))}It.getJSONTypes=i;function l(v,m){const{gen:S,data:k,opts:T}=v,b=u(m,T.coerceTypes),x=m.length>0&&!(b.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(v,m[0]));if(x){const I=g(m,k,T.strictNumbers,s.Wrong);S.if(I,()=>{b.length?h(v,m,b):y(v)})}return x}It.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,m){return m?v.filter(S=>c.has(S)||m==="array"&&S==="array"):[]}function h(v,m,S){const{gen:k,data:T,opts:b}=v,x=k.let("dataType",(0,n._)`typeof ${T}`),I=k.let("coerced",(0,n._)`undefined`);b.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${T}) && ${T}.length == 1`,()=>k.assign(T,(0,n._)`${T}[0]`).assign(x,(0,n._)`typeof ${T}`).if(g(m,T,b.strictNumbers),()=>k.assign(I,T))),k.if((0,n._)`${I} !== undefined`);for(const O of S)(c.has(O)||O==="array"&&b.coerceTypes==="array")&&L(O);k.else(),y(v),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(T,I),p(v,I)});function L(O){switch(O){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(I,(0,n._)`"" + ${T}`).elseIf((0,n._)`${T} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${T} === null
3
+ || (${x} == "string" && ${T} && ${T} == +${T})`).assign(I,(0,n._)`+${T}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${T} === null
4
+ || (${x} === "string" && ${T} && ${T} == +${T} && !(${T} % 1))`).assign(I,(0,n._)`+${T}`);return;case"boolean":k.elseIf((0,n._)`${T} === "false" || ${T} === 0 || ${T} === null`).assign(I,!1).elseIf((0,n._)`${T} === "true" || ${T} === 1`).assign(I,!0);return;case"null":k.elseIf((0,n._)`${T} === "" || ${T} === 0 || ${T} === false`),k.assign(I,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
5
+ || ${x} === "boolean" || ${T} === null`).assign(I,(0,n._)`[${T}]`)}}}function p({gen:v,parentData:m,parentDataProperty:S},k){v.if((0,n._)`${m} !== undefined`,()=>v.assign((0,n._)`${m}[${S}]`,k))}function f(v,m,S,k=s.Correct){const T=k===s.Correct?n.operators.EQ:n.operators.NEQ;let b;switch(v){case"null":return(0,n._)`${m} ${T} null`;case"array":b=(0,n._)`Array.isArray(${m})`;break;case"object":b=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":b=x((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":b=x();break;default:return(0,n._)`typeof ${m} ${T} ${v}`}return k===s.Correct?b:(0,n.not)(b);function x(I=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,I,S?(0,n._)`isFinite(${m})`:n.nil)}}It.checkDataType=f;function g(v,m,S,k){if(v.length===1)return f(v[0],m,S,k);let T;const b=(0,o.toHash)(v);if(b.array&&b.object){const x=(0,n._)`typeof ${m} != "object"`;T=b.null?x:(0,n._)`!${m} || ${x}`,delete b.null,delete b.array,delete b.object}else T=n.nil;b.number&&delete b.integer;for(const x in b)T=(0,n.and)(T,f(x,m,S,k));return T}It.checkDataTypes=g;const _={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:m})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${m}}`};function y(v){const m=w(v);(0,r.reportError)(m,_)}It.reportTypeError=y;function w(v){const{gen:m,data:S,schema:k}=v,T=(0,o.schemaRefOrVal)(v,k,"type");return{gen:m,keyword:"type",data:S,schema:k.type,schemaCode:T,schemaValue:T,parentSchema:k,params:{},it:v}}return It}var Zo={},Ep;function H1(){if(Ep)return Zo;Ep=1,Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.assignDefaults=void 0;const e=Ae(),t=Ue();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}Zo.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const h=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${h}`);return}let p=(0,e._)`${h} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${h} === null || ${h} === ""`),i.if(p,(0,e._)`${h} = ${(0,e.stringify)(a)}`)}return Zo}var fr={},Be={},xp;function hr(){if(xp)return Be;xp=1,Object.defineProperty(Be,"__esModule",{value:!0}),Be.validateUnion=Be.validateArray=Be.usePattern=Be.callValidateCode=Be.schemaProperties=Be.allSchemaProperties=Be.noPropertyInData=Be.propertyInData=Be.isOwnProperty=Be.hasPropFunc=Be.reportMissingProp=Be.checkMissingProp=Be.checkReportMissingProp=void 0;const e=Ae(),t=Ue(),r=dn(),n=Ue();function o(v,m){const{gen:S,data:k,it:T}=v;S.if(u(S,k,m,T.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${m}`},!0),v.error()})}Be.checkReportMissingProp=o;function s({gen:v,data:m,it:{opts:S}},k,T){return(0,e.or)(...k.map(b=>(0,e.and)(u(v,m,b,S.ownProperties),(0,e._)`${T} = ${b}`)))}Be.checkMissingProp=s;function a(v,m){v.setParams({missingProperty:m},!0),v.error()}Be.reportMissingProp=a;function i(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Be.hasPropFunc=i;function l(v,m,S){return(0,e._)`${i(v)}.call(${m}, ${S})`}Be.isOwnProperty=l;function c(v,m,S,k){const T=(0,e._)`${m}${(0,e.getProperty)(S)} !== undefined`;return k?(0,e._)`${T} && ${l(v,m,S)}`:T}Be.propertyInData=c;function u(v,m,S,k){const T=(0,e._)`${m}${(0,e.getProperty)(S)} === undefined`;return k?(0,e.or)(T,(0,e.not)(l(v,m,S))):T}Be.noPropertyInData=u;function h(v){return v?Object.keys(v).filter(m=>m!=="__proto__"):[]}Be.allSchemaProperties=h;function p(v,m){return h(m).filter(S=>!(0,t.alwaysValidSchema)(v,m[S]))}Be.schemaProperties=p;function f({schemaCode:v,data:m,it:{gen:S,topSchemaRef:k,schemaPath:T,errorPath:b},it:x},I,L,O){const A=O?(0,e._)`${v}, ${m}, ${k}${T}`:m,N=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,b)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&N.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const U=(0,e._)`${A}, ${S.object(...N)}`;return L!==e.nil?(0,e._)`${I}.call(${L}, ${U})`:(0,e._)`${I}(${U})`}Be.callValidateCode=f;const g=(0,e._)`new RegExp`;function _({gen:v,it:{opts:m}},S){const k=m.unicodeRegExp?"u":"",{regExp:T}=m.code,b=T(S,k);return v.scopeValue("pattern",{key:b.toString(),ref:b,code:(0,e._)`${T.code==="new RegExp"?g:(0,n.useFunc)(v,T)}(${S}, ${k})`})}Be.usePattern=_;function y(v){const{gen:m,data:S,keyword:k,it:T}=v,b=m.name("valid");if(T.allErrors){const I=m.let("valid",!0);return x(()=>m.assign(I,!1)),I}return m.var(b,!0),x(()=>m.break()),b;function x(I){const L=m.const("len",(0,e._)`${S}.length`);m.forRange("i",0,L,O=>{v.subschema({keyword:k,dataProp:O,dataPropType:t.Type.Num},b),m.if((0,e.not)(b),I)})}}Be.validateArray=y;function w(v){const{gen:m,schema:S,keyword:k,it:T}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(L=>(0,t.alwaysValidSchema)(T,L))&&!T.opts.unevaluated)return;const x=m.let("valid",!1),I=m.name("_valid");m.block(()=>S.forEach((L,O)=>{const A=v.subschema({keyword:k,schemaProp:O,compositeRule:!0},I);m.assign(x,(0,e._)`${x} || ${I}`),v.mergeValidEvaluated(A,I)||m.if((0,e.not)(x))})),v.result(x,()=>v.reset(),()=>v.error(!0))}return Be.validateUnion=w,Be}var $p;function B1(){if($p)return fr;$p=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.validateKeywordUsage=fr.validSchemaType=fr.funcKeywordCode=fr.macroKeywordCode=void 0;const e=Ae(),t=dn(),r=hr(),n=_a();function o(p,f){const{gen:g,keyword:_,schema:y,parentSchema:w,it:v}=p,m=f.macro.call(v.self,y,w,v),S=c(g,_,m);v.opts.validateSchema!==!1&&v.self.validateSchema(m,!0);const k=g.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${_}`,topSchemaRef:S,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}fr.macroKeywordCode=o;function s(p,f){var g;const{gen:_,keyword:y,schema:w,parentSchema:v,$data:m,it:S}=p;l(S,f);const k=!m&&f.compile?f.compile.call(S.self,w,v,S):f.validate,T=c(_,y,k),b=_.let("valid");p.block$data(b,x),p.ok((g=f.valid)!==null&&g!==void 0?g:b);function x(){if(f.errors===!1)O(),f.modifying&&a(p),A(()=>p.error());else{const N=f.async?I():L();f.modifying&&a(p),A(()=>i(p,N))}}function I(){const N=_.let("ruleErrs",null);return _.try(()=>O((0,e._)`await `),U=>_.assign(b,!1).if((0,e._)`${U} instanceof ${S.ValidationError}`,()=>_.assign(N,(0,e._)`${U}.errors`),()=>_.throw(U))),N}function L(){const N=(0,e._)`${T}.errors`;return _.assign(N,null),O(e.nil),N}function O(N=f.async?(0,e._)`await `:e.nil){const U=S.opts.passContext?t.default.this:t.default.self,G=!("compile"in f&&!m||f.schema===!1);_.assign(b,(0,e._)`${N}${(0,r.callValidateCode)(p,T,U,G)}`,f.modifying)}function A(N){var U;_.if((0,e.not)((U=f.valid)!==null&&U!==void 0?U:b),N)}}fr.funcKeywordCode=s;function a(p){const{gen:f,data:g,it:_}=p;f.if(_.parentData,()=>f.assign(g,(0,e._)`${_.parentData}[${_.parentDataProperty}]`))}function i(p,f){const{gen:g}=p;g.if((0,e._)`Array.isArray(${f})`,()=>{g.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${f} : ${t.default.vErrors}.concat(${f})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},f){if(f.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,f,g){if(g===void 0)throw new Error(`keyword "${f}" failed to compile`);return p.scopeValue("keyword",typeof g=="function"?{ref:g}:{ref:g,code:(0,e.stringify)(g)})}function u(p,f,g=!1){return!f.length||f.some(_=>_==="array"?Array.isArray(p):_==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==_||g&&typeof p>"u")}fr.validSchemaType=u;function h({schema:p,opts:f,self:g,errSchemaPath:_},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const v=y.dependencies;if(v?.some(m=>!Object.prototype.hasOwnProperty.call(p,m)))throw new Error(`parent schema must have dependencies of ${w}: ${v.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const S=`keyword "${w}" value is invalid at path "${_}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(S);else throw new Error(S)}}return fr.validateKeywordUsage=h,fr}var Hr={},Rp;function J1(){if(Rp)return Hr;Rp=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.extendSubschemaMode=Hr.extendSubschemaData=Hr.getSubschema=void 0;const e=Ae(),t=Ue();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:h}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||h===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:h,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Hr.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:h}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:g,dataPathArr:_,opts:y}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);f(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[..._,s.parentDataProperty]}if(c!==void 0){const g=c instanceof e.Name?c:p.let("data",c,!0);f(g),h!==void 0&&(s.propertyName=h)}u&&(s.dataTypes=u);function f(g){s.data=g,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,g]}}Hr.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return Hr.extendSubschemaMode=o,Hr}var Lt={},Ll,Pp;function Mp(){return Pp||(Pp=1,Ll=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),Ll}var jl={exports:{}},Op;function W1(){if(Op)return jl.exports;Op=1;var e=jl.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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 t(n,o,s,a,i,l,c,u,h,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,h,p);for(var f in a){var g=a[f];if(Array.isArray(g)){if(f in e.arrayKeywords)for(var _=0;_<g.length;_++)t(n,o,s,g[_],i+"/"+f+"/"+_,l,i,f,a,_)}else if(f in e.propsKeywords){if(g&&typeof g=="object")for(var y in g)t(n,o,s,g[y],i+"/"+f+"/"+r(y),l,i,f,a,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,s,g,i+"/"+f,l,i,f,a)}s(a,i,l,c,u,h,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return jl.exports}var Np;function ba(){if(Np)return Lt;Np=1,Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.getSchemaRefs=Lt.resolveUrl=Lt.normalizeId=Lt._getFullPath=Lt.getFullPath=Lt.inlineRef=void 0;const e=Ue(),t=Mp(),r=W1(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(_,y=!0){return typeof _=="boolean"?!0:y===!0?!a(_):y?i(_)<=y:!1}Lt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(_){for(const y in _){if(s.has(y))return!0;const w=_[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(_){let y=0;for(const w in _){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof _[w]=="object"&&(0,e.eachItem)(_[w],v=>y+=i(v)),y===1/0))return 1/0}return y}function l(_,y="",w){w!==!1&&(y=h(y));const v=_.parse(y);return c(_,v)}Lt.getFullPath=l;function c(_,y){return _.serialize(y).split("#")[0]+"#"}Lt._getFullPath=c;const u=/#\/?$/;function h(_){return _?_.replace(u,""):""}Lt.normalizeId=h;function p(_,y,w){return w=h(w),_.resolve(y,w)}Lt.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(_,y){if(typeof _=="boolean")return{};const{schemaId:w,uriResolver:v}=this.opts,m=h(_[w]||y),S={"":m},k=l(v,m,!1),T={},b=new Set;return r(_,{allKeys:!0},(L,O,A,N)=>{if(N===void 0)return;const U=k+O;let G=S[N];typeof L[w]=="string"&&(G=J.call(this,L[w])),ue.call(this,L.$anchor),ue.call(this,L.$dynamicAnchor),S[O]=G;function J(re){const ge=this.opts.uriResolver.resolve;if(re=h(G?ge(G,re):re),b.has(re))throw I(re);b.add(re);let V=this.refs[re];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?x(L,V.schema,re):re!==h(U)&&(re[0]==="#"?(x(L,T[re],re),T[re]=L):this.refs[re]=U),re}function ue(re){if(typeof re=="string"){if(!f.test(re))throw new Error(`invalid anchor "${re}"`);J.call(this,`#${re}`)}}}),T;function x(L,O,A){if(O!==void 0&&!t(L,O))throw I(A)}function I(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return Lt.getSchemaRefs=g,Lt}var Ap;function ka(){if(Ap)return Fr;Ap=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.getData=Fr.KeywordCxt=Fr.validateFunctionCode=void 0;const e=V1(),t=wa(),r=Sp(),n=wa(),o=H1(),s=B1(),a=J1(),i=Ae(),l=dn(),c=ba(),u=Ue(),h=_a();function p(z){if(k(z)&&(b(z),S(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Fr.validateFunctionCode=p;function f({gen:z,validateName:F,schema:Y,schemaEnv:ee,opts:le},be){le.code.es5?z.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,ee.$async,()=>{z.code((0,i._)`"use strict"; ${v(Y,le)}`),_(z,le),z.code(be)}):z.func(F,(0,i._)`${l.default.data}, ${g(le)}`,ee.$async,()=>z.code(v(Y,le)).code(be))}function g(z){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${z.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function _(z,F){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,i._)`""`),z.var(l.default.parentData,(0,i._)`undefined`),z.var(l.default.parentDataProperty,(0,i._)`undefined`),z.var(l.default.rootData,l.default.data),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(z){const{schema:F,opts:Y,gen:ee}=z;f(z,()=>{Y.$comment&&F.$comment&&N(z),L(z),ee.let(l.default.vErrors,null),ee.let(l.default.errors,0),Y.unevaluated&&w(z),x(z),U(z)})}function w(z){const{gen:F,validateName:Y}=z;z.evaluated=F.const("evaluated",(0,i._)`${Y}.evaluated`),F.if((0,i._)`${z.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${z.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${z.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${z.evaluated}.items`,(0,i._)`undefined`))}function v(z,F){const Y=typeof z=="object"&&z[F.schemaId];return Y&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${Y} */`:i.nil}function m(z,F){if(k(z)&&(b(z),S(z))){T(z,F);return}(0,e.boolOrEmptySchema)(z,F)}function S({schema:z,self:F}){if(typeof z=="boolean")return!z;for(const Y in z)if(F.RULES.all[Y])return!0;return!1}function k(z){return typeof z.schema!="boolean"}function T(z,F){const{schema:Y,gen:ee,opts:le}=z;le.$comment&&Y.$comment&&N(z),O(z),A(z);const be=ee.const("_errs",l.default.errors);x(z,be),ee.var(F,(0,i._)`${be} === ${l.default.errors}`)}function b(z){(0,u.checkUnknownRules)(z),I(z)}function x(z,F){if(z.opts.jtd)return J(z,[],!1,F);const Y=(0,t.getSchemaTypes)(z.schema),ee=(0,t.coerceAndCheckDataType)(z,Y);J(z,Y,!ee,F)}function I(z){const{schema:F,errSchemaPath:Y,opts:ee,self:le}=z;F.$ref&&ee.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,le.RULES)&&le.logger.warn(`$ref: keywords ignored in schema at path "${Y}"`)}function L(z){const{schema:F,opts:Y}=z;F.default!==void 0&&Y.useDefaults&&Y.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function O(z){const F=z.schema[z.opts.schemaId];F&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,F))}function A(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function N({gen:z,schemaEnv:F,schema:Y,errSchemaPath:ee,opts:le}){const be=Y.$comment;if(le.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${be})`);else if(typeof le.$comment=="function"){const tt=(0,i.str)`${ee}/$comment`,P=z.scopeValue("root",{ref:F.root});z.code((0,i._)`${l.default.self}.opts.$comment(${be}, ${tt}, ${P}.schema)`)}}function U(z){const{gen:F,schemaEnv:Y,validateName:ee,ValidationError:le,opts:be}=z;Y.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${le}(${l.default.vErrors})`)):(F.assign((0,i._)`${ee}.errors`,l.default.vErrors),be.unevaluated&&G(z),F.return((0,i._)`${l.default.errors} === 0`))}function G({gen:z,evaluated:F,props:Y,items:ee}){Y instanceof i.Name&&z.assign((0,i._)`${F}.props`,Y),ee instanceof i.Name&&z.assign((0,i._)`${F}.items`,ee)}function J(z,F,Y,ee){const{gen:le,schema:be,data:tt,allErrors:P,opts:te,self:Oe}=z,{RULES:je}=Oe;if(be.$ref&&(te.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(be,je))){le.block(()=>K(z,"$ref",je.all.$ref.definition));return}te.jtd||re(z,F),le.block(()=>{for(const gt of je.rules)Kt(gt);Kt(je.post)});function Kt(gt){(0,r.shouldUseGroup)(be,gt)&&(gt.type?(le.if((0,n.checkDataType)(gt.type,tt,te.strictNumbers)),ue(z,gt),F.length===1&&F[0]===gt.type&&Y&&(le.else(),(0,n.reportTypeError)(z)),le.endIf()):ue(z,gt),P||le.if((0,i._)`${l.default.errors} === ${ee||0}`))}}function ue(z,F){const{gen:Y,schema:ee,opts:{useDefaults:le}}=z;le&&(0,o.assignDefaults)(z,F.type),Y.block(()=>{for(const be of F.rules)(0,r.shouldUseRule)(ee,be)&&K(z,be.keyword,be.definition,F.type)})}function re(z,F){z.schemaEnv.meta||!z.opts.strictTypes||(ge(z,F),z.opts.allowUnionTypes||V(z,F),R(z,z.dataTypes))}function ge(z,F){if(F.length){if(!z.dataTypes.length){z.dataTypes=F;return}F.forEach(Y=>{Z(z.dataTypes,Y)||M(z,`type "${Y}" not allowed by context "${z.dataTypes.join(",")}"`)}),E(z,F)}}function V(z,F){F.length>1&&!(F.length===2&&F.includes("null"))&&M(z,"use allowUnionTypes to allow union type keyword")}function R(z,F){const Y=z.self.RULES.all;for(const ee in Y){const le=Y[ee];if(typeof le=="object"&&(0,r.shouldUseRule)(z.schema,le)){const{type:be}=le.definition;be.length&&!be.some(tt=>H(F,tt))&&M(z,`missing type "${be.join(",")}" for keyword "${ee}"`)}}}function H(z,F){return z.includes(F)||F==="number"&&z.includes("integer")}function Z(z,F){return z.includes(F)||F==="integer"&&z.includes("number")}function E(z,F){const Y=[];for(const ee of z.dataTypes)Z(F,ee)?Y.push(ee):F.includes("integer")&&ee==="number"&&Y.push("integer");z.dataTypes=Y}function M(z,F){const Y=z.schemaEnv.baseId+z.errSchemaPath;F+=` at "${Y}" (strictTypes)`,(0,u.checkStrictMode)(z,F,z.opts.strictTypes)}class D{constructor(F,Y,ee){if((0,s.validateKeywordUsage)(F,Y,ee),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=ee,this.data=F.data,this.schema=F.schema[ee],this.$data=Y.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,ee,this.$data),this.schemaType=Y.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=Y,this.$data)this.schemaCode=F.gen.const("vSchema",Ie(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,Y.schemaType,Y.allowUndefined))throw new Error(`${ee} value must be ${JSON.stringify(Y.schemaType)}`);("code"in Y?Y.trackErrors:Y.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,Y,ee){this.failResult((0,i.not)(F),Y,ee)}failResult(F,Y,ee){this.gen.if(F),ee?ee():this.error(),Y?(this.gen.else(),Y(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,Y){this.failResult((0,i.not)(F),void 0,Y)}fail(F){if(F===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(F),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(F){if(!this.$data)return this.fail(F);const{schemaCode:Y}=this;this.fail((0,i._)`${Y} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,Y,ee){if(Y){this.setParams(Y),this._error(F,ee),this.setParams({});return}this._error(F,ee)}_error(F,Y){(F?h.reportExtraError:h.reportError)(this,this.def.error,Y)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,Y){Y?Object.assign(this.params,F):this.params=F}block$data(F,Y,ee=i.nil){this.gen.block(()=>{this.check$data(F,ee),Y()})}check$data(F=i.nil,Y=i.nil){if(!this.$data)return;const{gen:ee,schemaCode:le,schemaType:be,def:tt}=this;ee.if((0,i.or)((0,i._)`${le} === undefined`,Y)),F!==i.nil&&ee.assign(F,!0),(be.length||tt.validateSchema)&&(ee.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&ee.assign(F,!1)),ee.else()}invalid$data(){const{gen:F,schemaCode:Y,schemaType:ee,def:le,it:be}=this;return(0,i.or)(tt(),P());function tt(){if(ee.length){if(!(Y instanceof i.Name))throw new Error("ajv implementation error");const te=Array.isArray(ee)?ee:[ee];return(0,i._)`${(0,n.checkDataTypes)(te,Y,be.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function P(){if(le.validateSchema){const te=F.scopeValue("validate$data",{ref:le.validateSchema});return(0,i._)`!${te}(${Y})`}return i.nil}}subschema(F,Y){const ee=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(ee,this.it,F),(0,a.extendSubschemaMode)(ee,F);const le={...this.it,...ee,items:void 0,props:void 0};return m(le,Y),le}mergeEvaluated(F,Y){const{it:ee,gen:le}=this;ee.opts.unevaluated&&(ee.props!==!0&&F.props!==void 0&&(ee.props=u.mergeEvaluated.props(le,F.props,ee.props,Y)),ee.items!==!0&&F.items!==void 0&&(ee.items=u.mergeEvaluated.items(le,F.items,ee.items,Y)))}mergeValidEvaluated(F,Y){const{it:ee,gen:le}=this;if(ee.opts.unevaluated&&(ee.props!==!0||ee.items!==!0))return le.if(Y,()=>this.mergeEvaluated(F,i.Name)),!0}}Fr.KeywordCxt=D;function K(z,F,Y,ee){const le=new D(z,Y,F);"code"in Y?Y.code(le,ee):le.$data&&Y.validate?(0,s.funcKeywordCode)(le,Y):"macro"in Y?(0,s.macroKeywordCode)(le,Y):(Y.compile||Y.validate)&&(0,s.funcKeywordCode)(le,Y)}const ne=/^\/(?:[^~]|~0|~1)*$/,ae=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ie(z,{dataLevel:F,dataNames:Y,dataPathArr:ee}){let le,be;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!ne.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);le=z,be=l.default.rootData}else{const Oe=ae.exec(z);if(!Oe)throw new Error(`Invalid JSON-pointer: ${z}`);const je=+Oe[1];if(le=Oe[2],le==="#"){if(je>=F)throw new Error(te("property/index",je));return ee[F-je]}if(je>F)throw new Error(te("data",je));if(be=Y[F-je],!le)return be}let tt=be;const P=le.split("/");for(const Oe of P)Oe&&(be=(0,i._)`${be}${(0,i.getProperty)((0,u.unescapeJsonPointer)(Oe))}`,tt=(0,i._)`${tt} && ${be}`);return tt;function te(Oe,je){return`Cannot access ${Oe} ${je} levels up, current level is ${F}`}}return Fr.getData=Ie,Fr}var Ta={},qp;function Dl(){if(qp)return Ta;qp=1,Object.defineProperty(Ta,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ta.default=e,Ta}var Ca={},Lp;function Sa(){if(Lp)return Ca;Lp=1,Object.defineProperty(Ca,"__esModule",{value:!0});const e=ba();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return Ca.default=t,Ca}var Yt={},jp;function Ul(){if(jp)return Yt;jp=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;const e=Ae(),t=Dl(),r=dn(),n=ba(),o=Ue(),s=ka();class a{constructor(w){var v;this.refs={},this.dynamicAnchors={};let m;typeof w.schema=="object"&&(m=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(v=w.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(m?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=m?.$async,this.refs={}}}Yt.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const v=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:m,lines:S}=this.opts.code,{ownProperties:k}=this.opts,T=new e.CodeGen(this.scope,{es5:m,lines:S,ownProperties:k});let b;y.$async&&(b=T.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const x=T.scopeName("validate");y.validateName=x;const I={gen:T,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:T.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:x,ValidationError:b,schema:y.schema,schemaEnv:y,rootId:v,baseId:y.baseId||v,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(y),(0,s.validateFunctionCode)(I),T.optimize(this.opts.code.optimize);const O=T.toString();L=`${T.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(L=this.opts.code.process(L,y));const N=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(x,{ref:N}),N.errors=null,N.schema=y.schema,N.schemaEnv=y,y.$async&&(N.$async=!0),this.opts.code.source===!0&&(N.source={validateName:x,validateCode:O,scopeValues:T._values}),this.opts.unevaluated){const{props:U,items:G}=I;N.evaluated={props:U instanceof e.Name?void 0:U,items:G instanceof e.Name?void 0:G,dynamicProps:U instanceof e.Name,dynamicItems:G instanceof e.Name},N.source&&(N.source.evaluated=(0,e.stringify)(N.evaluated))}return y.validate=N,y}catch(O){throw delete y.validate,delete y.validateName,L&&this.logger.error("Error compiling schema, function code:",L),O}finally{this._compilations.delete(y)}}Yt.compileSchema=i;function l(y,w,v){var m;v=(0,n.resolveUrl)(this.opts.uriResolver,w,v);const S=y.refs[v];if(S)return S;let k=p.call(this,y,v);if(k===void 0){const T=(m=y.localRefs)===null||m===void 0?void 0:m[v],{schemaId:b}=this.opts;T&&(k=new a({schema:T,schemaId:b,root:y,baseId:w}))}if(k!==void 0)return y.refs[v]=c.call(this,k)}Yt.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:i.call(this,y)}function u(y){for(const w of this._compilations)if(h(w,y))return w}Yt.getCompilingSchema=u;function h(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let v;for(;typeof(v=this.refs[w])=="string";)w=v;return v||this.schemas[w]||f.call(this,y,w)}function f(y,w){const v=this.opts.uriResolver.parse(w),m=(0,n._getFullPath)(this.opts.uriResolver,v);let S=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&m===S)return _.call(this,v,y);const k=(0,n.normalizeId)(m),T=this.refs[k]||this.schemas[k];if(typeof T=="string"){const b=f.call(this,y,T);return typeof b?.schema!="object"?void 0:_.call(this,v,b)}if(typeof T?.schema=="object"){if(T.validate||i.call(this,T),k===(0,n.normalizeId)(w)){const{schema:b}=T,{schemaId:x}=this.opts,I=b[x];return I&&(S=(0,n.resolveUrl)(this.opts.uriResolver,S,I)),new a({schema:b,schemaId:x,root:y,baseId:S})}return _.call(this,v,T)}}Yt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(y,{baseId:w,schema:v,root:m}){var S;if(((S=y.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(const b of y.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const x=v[(0,o.unescapeFragment)(b)];if(x===void 0)return;v=x;const I=typeof v=="object"&&v[this.opts.schemaId];!g.has(b)&&I&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,I))}let k;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const b=(0,n.resolveUrl)(this.opts.uriResolver,w,v.$ref);k=f.call(this,m,b)}const{schemaId:T}=this.opts;if(k=k||new a({schema:v,schemaId:T,root:m,baseId:w}),k.schema!==k.root.schema)return k}return Yt}const G1={$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 Ia={},Fo={exports:{}},zl,Dp;function Up(){if(Dp)return zl;Dp=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=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(p){let f="",g=0,_=0;for(_=0;_<p.length;_++)if(g=p[_].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[_];break}for(_+=1;_<p.length;_++){if(g=p[_].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[_]}return f}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,f,g){if(p.length){const _=r(p);if(_!=="")f.push(_);else return g.error=!0,!1;p.length=0}return!0}function a(p){let f=0;const g={error:!1,address:"",zone:""},_=[],y=[];let w=!1,v=!1,m=s;for(let S=0;S<p.length;S++){const k=p[S];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(v=!0),!m(y,_,g))break;if(++f>7){g.error=!0;break}S>0&&p[S-1]===":"&&(w=!0),_.push(":");continue}else if(k==="%"){if(!m(y,_,g))break;m=o}else{y.push(k);continue}}return y.length&&(m===o?g.zone=y.join(""):v?_.push(y.join("")):_.push(r(y))),g.address=_.join(""),g}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const f=a(p);if(f.error)return{host:p,isIPV6:!1};{let g=f.address,_=f.address;return f.zone&&(g+="%"+f.zone,_+="%25"+f.zone),{host:g,isIPV6:!0,escapedHost:_}}}function l(p,f){let g=0;for(let _=0;_<p.length;_++)p[_]===f&&g++;return g}function c(p){let f=p;const g=[];let _=-1,y=0;for(;y=f.length;){if(y===1){if(f===".")break;if(f==="/"){g.push("/");break}else{g.push(f);break}}else if(y===2){if(f[0]==="."){if(f[1]===".")break;if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&(f[1]==="."||f[1]==="/")){g.push("/");break}}else if(y===3&&f==="/.."){g.length!==0&&g.pop(),g.push("/");break}if(f[0]==="."){if(f[1]==="."){if(f[2]==="/"){f=f.slice(3);continue}}else if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&f[1]==="."){if(f[2]==="/"){f=f.slice(2);continue}else if(f[2]==="."&&f[3]==="/"){f=f.slice(3),g.length!==0&&g.pop();continue}}if((_=f.indexOf("/",1))===-1){g.push(f);break}else g.push(f.slice(0,_)),f=f.slice(_)}return g.join("")}function u(p,f){const g=f!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=g(p.scheme)),p.userinfo!==void 0&&(p.userinfo=g(p.userinfo)),p.host!==void 0&&(p.host=g(p.host)),p.path!==void 0&&(p.path=g(p.path)),p.query!==void 0&&(p.query=g(p.query)),p.fragment!==void 0&&(p.fragment=g(p.fragment)),p}function h(p){const f=[];if(p.userinfo!==void 0&&(f.push(p.userinfo),f.push("@")),p.host!==void 0){let g=unescape(p.host);if(!t(g)){const _=i(g);_.isIPV6===!0?g=`[${_.escapedHost}]`:g=p.host}f.push(g)}return(typeof p.port=="number"||typeof p.port=="string")&&(f.push(":"),f.push(String(p.port))),f.length?f.join(""):void 0}return zl={nonSimpleDomain:n,recomposeAuthority:h,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},zl}var Zl,zp;function K1(){if(zp)return Zl;zp=1;const{isUUID:e}=Up(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function o(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function s(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const T=String(k.scheme).toLowerCase()==="https";return(k.port===(T?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=o(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(o(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[T,b]=k.resourceName.split("?");k.path=T&&T!=="/"?T:void 0,k.query=b,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,T){if(!k.path)return k.error="URN can not be parsed",k;const b=k.path.match(t);if(b){const x=T.scheme||k.scheme||"urn";k.nid=b[1].toLowerCase(),k.nss=b[2];const I=`${x}:${T.nid||k.nid}`,L=S(I);k.path=void 0,L&&(k=L.parse(k,T))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,T){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const b=T.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),I=`${b}:${T.nid||x}`,L=S(I);L&&(k=L.serialize(k,T));const O=k,A=k.nss;return O.path=`${x||T.nid}:${A}`,T.skipEscape=!0,O}function h(k,T){const b=k;return b.uuid=b.nss,b.nss=void 0,!T.tolerant&&(!b.uuid||!e(b.uuid))&&(b.error=b.error||"UUID is not valid."),b}function p(k){const T=k;return T.nss=(k.uuid||"").toLowerCase(),T}const f={scheme:"http",domainHost:!0,parse:s,serialize:a},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:a},_={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},m={http:f,https:g,ws:_,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(m,null);function S(k){return k&&(m[k]||m[k.toLowerCase()])||void 0}return Zl={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:S},Zl}var Zp;function Y1(){if(Zp)return Fo.exports;Zp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Up(),{SCHEMES:a,getSchemeHandler:i}=K1();function l(y,w){return typeof y=="string"?y=p(g(y,w),w):typeof y=="object"&&(y=g(p(y,w),w)),y}function c(y,w,v){const m=v?Object.assign({scheme:"null"},v):{scheme:"null"},S=u(g(y,m),g(w,m),m,!0);return m.skipEscape=!0,p(S,m)}function u(y,w,v,m){const S={};return m||(y=g(p(y,v),v),w=g(p(w,v),v)),v=v||{},!v.tolerant&&w.scheme?(S.scheme=w.scheme,S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.path?(w.path[0]==="/"?S.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?S.path="/"+w.path:y.path?S.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:S.path=w.path,S.path=t(S.path)),S.query=w.query):(S.path=y.path,w.query!==void 0?S.query=w.query:S.query=y.query),S.userinfo=y.userinfo,S.host=y.host,S.port=y.port),S.scheme=y.scheme),S.fragment=w.fragment,S}function h(y,w,v){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,v),!0),{...v,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{...v,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,v),!0),{...v,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{...v,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const v={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},m=Object.assign({},w),S=[],k=i(m.scheme||v.scheme);k&&k.serialize&&k.serialize(v,m),v.path!==void 0&&(m.skipEscape?v.path=unescape(v.path):(v.path=escape(v.path),v.scheme!==void 0&&(v.path=v.path.split("%3A").join(":")))),m.reference!=="suffix"&&v.scheme&&S.push(v.scheme,":");const T=r(v);if(T!==void 0&&(m.reference!=="suffix"&&S.push("//"),S.push(T),v.path&&v.path[0]!=="/"&&S.push("/")),v.path!==void 0){let b=v.path;!m.absolutePath&&(!k||!k.absolutePath)&&(b=t(b)),T===void 0&&b[0]==="/"&&b[1]==="/"&&(b="/%2F"+b.slice(2)),S.push(b)}return v.query!==void 0&&S.push("?",v.query),v.fragment!==void 0&&S.push("#",v.fragment),S.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const v=Object.assign({},w),m={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let S=!1;v.reference==="suffix"&&(v.scheme?y=v.scheme+":"+y:y="//"+y);const k=y.match(f);if(k){if(m.scheme=k[1],m.userinfo=k[3],m.host=k[4],m.port=parseInt(k[5],10),m.path=k[6]||"",m.query=k[7],m.fragment=k[8],isNaN(m.port)&&(m.port=k[5]),m.host)if(o(m.host)===!1){const x=e(m.host);m.host=x.host.toLowerCase(),S=x.isIPV6}else S=!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",v.reference&&v.reference!=="suffix"&&v.reference!==m.reference&&(m.error=m.error||"URI is not a "+v.reference+" reference.");const T=i(v.scheme||m.scheme);if(!v.unicodeSupport&&(!T||!T.unicodeSupport)&&m.host&&(v.domainHost||T&&T.domainHost)&&S===!1&&s(m.host))try{m.host=URL.domainToASCII(m.host.toLowerCase())}catch(b){m.error=m.error||"Host's domain name can not be converted to ASCII: "+b}(!T||T&&!T.skipNormalize)&&(y.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)))),T&&T.parse&&T.parse(m,v)}else m.error=m.error||"URI can not be parsed.";return m}const _={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:h,serialize:p,parse:g};return Fo.exports=_,Fo.exports.default=_,Fo.exports.fastUri=_,Fo.exports}var Fp;function Q1(){if(Fp)return Ia;Fp=1,Object.defineProperty(Ia,"__esModule",{value:!0});const e=Y1();return e.code='require("ajv/dist/runtime/uri").default',Ia.default=e,Ia}var Vp;function X1(){return Vp||(Vp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=ka();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ae();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Dl(),o=Sa(),s=Tp(),a=Ul(),i=Ae(),l=ba(),c=wa(),u=Ue(),h=G1,p=Q1(),f=(V,R)=>new RegExp(V,R);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={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."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function m(V){var R,H,Z,E,M,D,K,ne,ae,Ie,z,F,Y,ee,le,be,tt,P,te,Oe,je,Kt,gt,Xe,sn;const rt=V.strict,nr=(R=V.code)===null||R===void 0?void 0:R.optimize,an=nr===!0||nr===void 0?1:nr||0,nt=(Z=(H=V.code)===null||H===void 0?void 0:H.regExp)!==null&&Z!==void 0?Z:f,Ee=(E=V.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(D=(M=V.strictSchema)!==null&&M!==void 0?M:rt)!==null&&D!==void 0?D:!0,strictNumbers:(ne=(K=V.strictNumbers)!==null&&K!==void 0?K:rt)!==null&&ne!==void 0?ne:!0,strictTypes:(Ie=(ae=V.strictTypes)!==null&&ae!==void 0?ae:rt)!==null&&Ie!==void 0?Ie:"log",strictTuples:(F=(z=V.strictTuples)!==null&&z!==void 0?z:rt)!==null&&F!==void 0?F:"log",strictRequired:(ee=(Y=V.strictRequired)!==null&&Y!==void 0?Y:rt)!==null&&ee!==void 0?ee:!1,code:V.code?{...V.code,optimize:an,regExp:nt}:{optimize:an,regExp:nt},loopRequired:(le=V.loopRequired)!==null&&le!==void 0?le:v,loopEnum:(be=V.loopEnum)!==null&&be!==void 0?be:v,meta:(tt=V.meta)!==null&&tt!==void 0?tt:!0,messages:(P=V.messages)!==null&&P!==void 0?P:!0,inlineRefs:(te=V.inlineRefs)!==null&&te!==void 0?te:!0,schemaId:(Oe=V.schemaId)!==null&&Oe!==void 0?Oe:"$id",addUsedSchema:(je=V.addUsedSchema)!==null&&je!==void 0?je:!0,validateSchema:(Kt=V.validateSchema)!==null&&Kt!==void 0?Kt:!0,validateFormats:(gt=V.validateFormats)!==null&&gt!==void 0?gt:!0,unicodeRegExp:(Xe=V.unicodeRegExp)!==null&&Xe!==void 0?Xe:!0,int32range:(sn=V.int32range)!==null&&sn!==void 0?sn:!0,uriResolver:Ee}}class S{constructor(R={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,R=this.opts={...R,...m(R)};const{es5:H,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:_,es5:H,lines:Z}),this.logger=A(R.logger);const E=R.validateFormats;R.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,y,R,"NOT SUPPORTED"),k.call(this,w,R,"DEPRECATED","warn"),this._metaOpts=L.call(this),R.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),R.keywords&&I.call(this,R.keywords),typeof R.meta=="object"&&this.addMetaSchema(R.meta),b.call(this),R.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:R,meta:H,schemaId:Z}=this.opts;let E=h;Z==="id"&&(E={...h},E.id=E.$id,delete E.$id),H&&R&&this.addMetaSchema(E,E[Z],!1)}defaultMeta(){const{meta:R,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof R=="object"?R[H]||R:void 0}validate(R,H){let Z;if(typeof R=="string"){if(Z=this.getSchema(R),!Z)throw new Error(`no schema with key or ref "${R}"`)}else Z=this.compile(R);const E=Z(H);return"$async"in Z||(this.errors=Z.errors),E}compile(R,H){const Z=this._addSchema(R,H);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(R,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return E.call(this,R,H);async function E(Ie,z){await M.call(this,Ie.$schema);const F=this._addSchema(Ie,z);return F.validate||D.call(this,F)}async function M(Ie){Ie&&!this.getSchema(Ie)&&await E.call(this,{$ref:Ie},!0)}async function D(Ie){try{return this._compileSchemaEnv(Ie)}catch(z){if(!(z instanceof o.default))throw z;return K.call(this,z),await ne.call(this,z.missingSchema),D.call(this,Ie)}}function K({missingSchema:Ie,missingRef:z}){if(this.refs[Ie])throw new Error(`AnySchema ${Ie} is loaded but ${z} cannot be resolved`)}async function ne(Ie){const z=await ae.call(this,Ie);this.refs[Ie]||await M.call(this,z.$schema),this.refs[Ie]||this.addSchema(z,Ie,H)}async function ae(Ie){const z=this._loading[Ie];if(z)return z;try{return await(this._loading[Ie]=Z(Ie))}finally{delete this._loading[Ie]}}}addSchema(R,H,Z,E=this.opts.validateSchema){if(Array.isArray(R)){for(const D of R)this.addSchema(D,void 0,Z,E);return this}let M;if(typeof R=="object"){const{schemaId:D}=this.opts;if(M=R[D],M!==void 0&&typeof M!="string")throw new Error(`schema ${D} must be string`)}return H=(0,l.normalizeId)(H||M),this._checkUnique(H),this.schemas[H]=this._addSchema(R,Z,H,E,!0),this}addMetaSchema(R,H,Z=this.opts.validateSchema){return this.addSchema(R,H,!0,Z),this}validateSchema(R,H){if(typeof R=="boolean")return!0;let Z;if(Z=R.$schema,Z!==void 0&&typeof Z!="string")throw new Error("$schema must be a string");if(Z=Z||this.opts.defaultMeta||this.defaultMeta(),!Z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(Z,R);if(!E&&H){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return E}getSchema(R){let H;for(;typeof(H=T.call(this,R))=="string";)R=H;if(H===void 0){const{schemaId:Z}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:Z});if(H=a.resolveSchema.call(this,E,R),!H)return;this.refs[R]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(R){if(R instanceof RegExp)return this._removeAllSchemas(this.schemas,R),this._removeAllSchemas(this.refs,R),this;switch(typeof R){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const H=T.call(this,R);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[R],delete this.refs[R],this}case"object":{const H=R;this._cache.delete(H);let Z=R[this.opts.schemaId];return Z&&(Z=(0,l.normalizeId)(Z),delete this.schemas[Z],delete this.refs[Z]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(R){for(const H of R)this.addKeyword(H);return this}addKeyword(R,H){let Z;if(typeof R=="string")Z=R,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=Z);else if(typeof R=="object"&&H===void 0){if(H=R,Z=H.keyword,Array.isArray(Z)&&!Z.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,Z,H),!H)return(0,u.eachItem)(Z,M=>G.call(this,M)),this;ue.call(this,H);const E={...H,type:(0,c.getJSONTypes)(H.type),schemaType:(0,c.getJSONTypes)(H.schemaType)};return(0,u.eachItem)(Z,E.type.length===0?M=>G.call(this,M,E):M=>E.type.forEach(D=>G.call(this,M,E,D))),this}getKeyword(R){const H=this.RULES.all[R];return typeof H=="object"?H.definition:!!H}removeKeyword(R){const{RULES:H}=this;delete H.keywords[R],delete H.all[R];for(const Z of H.rules){const E=Z.rules.findIndex(M=>M.keyword===R);E>=0&&Z.rules.splice(E,1)}return this}addFormat(R,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[R]=H,this}errorsText(R=this.errors,{separator:H=", ",dataVar:Z="data"}={}){return!R||R.length===0?"No errors":R.map(E=>`${Z}${E.instancePath} ${E.message}`).reduce((E,M)=>E+H+M)}$dataMetaSchema(R,H){const Z=this.RULES.all;R=JSON.parse(JSON.stringify(R));for(const E of H){const M=E.split("/").slice(1);let D=R;for(const K of M)D=D[K];for(const K in Z){const ne=Z[K];if(typeof ne!="object")continue;const{$data:ae}=ne.definition,Ie=D[K];ae&&Ie&&(D[K]=ge(Ie))}}return R}_removeAllSchemas(R,H){for(const Z in R){const E=R[Z];(!H||H.test(Z))&&(typeof E=="string"?delete R[Z]:E&&!E.meta&&(this._cache.delete(E.schema),delete R[Z]))}}_addSchema(R,H,Z,E=this.opts.validateSchema,M=this.opts.addUsedSchema){let D;const{schemaId:K}=this.opts;if(typeof R=="object")D=R[K];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof R!="boolean")throw new Error("schema must be object or boolean")}let ne=this._cache.get(R);if(ne!==void 0)return ne;Z=(0,l.normalizeId)(D||Z);const ae=l.getSchemaRefs.call(this,R,Z);return ne=new a.SchemaEnv({schema:R,schemaId:K,meta:H,baseId:Z,localRefs:ae}),this._cache.set(ne.schema,ne),M&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=ne),E&&this.validateSchema(R,!0),ne}_checkUnique(R){if(this.schemas[R]||this.refs[R])throw new Error(`schema with key or id "${R}" already exists`)}_compileSchemaEnv(R){if(R.meta?this._compileMetaSchema(R):a.compileSchema.call(this,R),!R.validate)throw new Error("ajv implementation error");return R.validate}_compileMetaSchema(R){const H=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,R)}finally{this.opts=H}}}S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function k(V,R,H,Z="error"){for(const E in V){const M=E;M in R&&this.logger[Z](`${H}: option ${E}. ${V[M]}`)}}function T(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function b(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const R in V)this.addSchema(V[R],R)}function x(){for(const V in this.opts.formats){const R=this.opts.formats[V];R&&this.addFormat(V,R)}}function I(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const R in V){const H=V[R];H.keyword||(H.keyword=R),this.addKeyword(H)}}function L(){const V={...this.opts};for(const R of g)delete V[R];return V}const O={log(){},warn(){},error(){}};function A(V){if(V===!1)return O;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const N=/^[a-z_$][a-z0-9_$:-]*$/i;function U(V,R){const{RULES:H}=this;if((0,u.eachItem)(V,Z=>{if(H.keywords[Z])throw new Error(`Keyword ${Z} is already defined`);if(!N.test(Z))throw new Error(`Keyword ${Z} has invalid name`)}),!!R&&R.$data&&!("code"in R||"validate"in R))throw new Error('$data keyword must have "code" or "validate" function')}function G(V,R,H){var Z;const E=R?.post;if(H&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let D=E?M.post:M.rules.find(({type:ne})=>ne===H);if(D||(D={type:H,rules:[]},M.rules.push(D)),M.keywords[V]=!0,!R)return;const K={keyword:V,definition:{...R,type:(0,c.getJSONTypes)(R.type),schemaType:(0,c.getJSONTypes)(R.schemaType)}};R.before?J.call(this,D,K,R.before):D.rules.push(K),M.all[V]=K,(Z=R.implements)===null||Z===void 0||Z.forEach(ne=>this.addKeyword(ne))}function J(V,R,H){const Z=V.rules.findIndex(E=>E.keyword===H);Z>=0?V.rules.splice(Z,0,R):(V.rules.push(R),this.logger.warn(`rule ${H} is not defined`))}function ue(V){let{metaSchema:R}=V;R!==void 0&&(V.$data&&this.opts.$data&&(R=ge(R)),V.validateSchema=this.compile(R,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ge(V){return{anyOf:[V,re]}}})(Ml)),Ml}var Ea={},xa={},$a={},Hp;function ew(){if(Hp)return $a;Hp=1,Object.defineProperty($a,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return $a.default=e,$a}var pn={},Bp;function tw(){if(Bp)return pn;Bp=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.callRef=pn.getValidate=void 0;const e=Sa(),t=hr(),r=Ae(),n=dn(),o=Ul(),s=Ue(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:h,it:p}=c,{baseId:f,schemaEnv:g,validateName:_,opts:y,self:w}=p,{root:v}=g;if((h==="#"||h==="#/")&&f===v.baseId)return S();const m=o.resolveRef.call(w,v,f,h);if(m===void 0)throw new e.default(p.opts.uriResolver,f,h);if(m instanceof o.SchemaEnv)return k(m);return T(m);function S(){if(g===v)return l(c,_,g,g.$async);const b=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${b}.validate`,v,v.$async)}function k(b){const x=i(c,b);l(c,x,b,b.$async)}function T(b){const x=u.scopeValue("schema",y.code.source===!0?{ref:b,code:(0,r.stringify)(b)}:{ref:b}),I=u.name("valid"),L=c.subschema({schema:b,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:h},I);c.mergeEvaluated(L),c.ok(I)}}};function i(c,u){const{gen:h}=c;return u.validate?h.scopeValue("validate",{ref:u.validate}):(0,r._)`${h.scopeValue("wrapper",{ref:u})}.validate`}pn.getValidate=i;function l(c,u,h,p){const{gen:f,it:g}=c,{allErrors:_,schemaEnv:y,opts:w}=g,v=w.passContext?n.default.this:r.nil;p?m():S();function m(){if(!y.$async)throw new Error("async schema referenced by sync schema");const b=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),T(u),_||f.assign(b,!0)},x=>{f.if((0,r._)`!(${x} instanceof ${g.ValidationError})`,()=>f.throw(x)),k(x),_||f.assign(b,!1)}),c.ok(b)}function S(){c.result((0,t.callValidateCode)(c,u,v),()=>T(u),()=>k(u))}function k(b){const x=(0,r._)`${b}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function T(b){var x;if(!g.opts.unevaluated)return;const I=(x=h?.validate)===null||x===void 0?void 0:x.evaluated;if(g.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(g.props=s.mergeEvaluated.props(f,I.props,g.props));else{const L=f.var("props",(0,r._)`${b}.evaluated.props`);g.props=s.mergeEvaluated.props(f,L,g.props,r.Name)}if(g.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(g.items=s.mergeEvaluated.items(f,I.items,g.items));else{const L=f.var("items",(0,r._)`${b}.evaluated.items`);g.items=s.mergeEvaluated.items(f,L,g.items,r.Name)}}}return pn.callRef=l,pn.default=a,pn}var Jp;function rw(){if(Jp)return xa;Jp=1,Object.defineProperty(xa,"__esModule",{value:!0});const e=ew(),t=tw(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return xa.default=r,xa}var Ra={},Pa={},Wp;function nw(){if(Wp)return Pa;Wp=1,Object.defineProperty(Pa,"__esModule",{value:!0});const e=Ae(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return Pa.default=o,Pa}var Ma={},Gp;function ow(){if(Gp)return Ma;Gp=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=Ae(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return Ma.default=r,Ma}var Oa={},Na={},Kp;function sw(){if(Kp)return Na;Kp=1,Object.defineProperty(Na,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return Na.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Na}var Yp;function aw(){if(Yp)return Oa;Yp=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=Ae(),t=Ue(),r=sw(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,h=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${h} ${u} ${l}`)}};return Oa.default=o,Oa}var Aa={},Qp;function iw(){if(Qp)return Aa;Qp=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=hr(),t=Ue(),r=Ae(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:h}=s,p=h.opts.unicodeRegExp?"u":"";if(l){const{regExp:f}=h.opts.code,g=f.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,f),_=a.let("valid");a.try(()=>a.assign(_,(0,r._)`${g}(${u}, ${p}).test(${i})`),()=>a.assign(_,!1)),s.fail$data((0,r._)`!${_}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${i})`)}}};return Aa.default=o,Aa}var qa={},Xp;function lw(){if(Xp)return qa;Xp=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=Ae(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return qa.default=r,qa}var La={},ef;function cw(){if(ef)return La;ef=1,Object.defineProperty(La,"__esModule",{value:!0});const e=hr(),t=Ae(),r=Ue(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:h}=s,{opts:p}=h;if(!u&&i.length===0)return;const f=i.length>=p.loopRequired;if(h.allErrors?g():_(),p.strictRequired){const v=s.parentSchema.properties,{definedProperties:m}=s.it;for(const S of i)if(v?.[S]===void 0&&!m.has(S)){const k=h.schemaEnv.baseId+h.errSchemaPath,T=`required property "${S}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(h,T,h.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const v of i)(0,e.checkReportMissingProp)(s,v)}function _(){const v=a.let("missing");if(f||u){const m=a.let("valid",!0);s.block$data(m,()=>w(v,m)),s.ok(m)}else a.if((0,e.checkMissingProp)(s,i,v)),(0,e.reportMissingProp)(s,v),a.else()}function y(){a.forOf("prop",l,v=>{s.setParams({missingProperty:v}),a.if((0,e.noPropertyInData)(a,c,v,p.ownProperties),()=>s.error())})}function w(v,m){s.setParams({missingProperty:v}),a.forOf(v,l,()=>{a.assign(m,(0,e.propertyInData)(a,c,v,p.ownProperties)),a.if((0,t.not)(m),()=>{s.error(),a.break()})},t.nil)}}};return La.default=o,La}var ja={},tf;function uw(){if(tf)return ja;tf=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=Ae(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return ja.default=r,ja}var Da={},Ua={},rf;function Fl(){if(rf)return Ua;rf=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=Mp();return e.code='require("ajv/dist/runtime/equal").default',Ua.default=e,Ua}var nf;function dw(){if(nf)return Da;nf=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=wa(),t=Ae(),r=Ue(),n=Fl(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:h,schemaCode:p,it:f}=a;if(!c&&!u)return;const g=i.let("valid"),_=h.items?(0,e.getSchemaTypes)(h.items):[];a.block$data(g,y,(0,t._)`${p} === false`),a.ok(g);function y(){const S=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:S,j:k}),i.assign(g,!0),i.if((0,t._)`${S} > 1`,()=>(w()?v:m)(S,k))}function w(){return _.length>0&&!_.some(S=>S==="object"||S==="array")}function v(S,k){const T=i.name("item"),b=(0,e.checkDataTypes)(_,T,f.opts.strictNumbers,e.DataType.Wrong),x=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${S}--;`,()=>{i.let(T,(0,t._)`${l}[${S}]`),i.if(b,(0,t._)`continue`),_.length>1&&i.if((0,t._)`typeof ${T} == "string"`,(0,t._)`${T} += "_"`),i.if((0,t._)`typeof ${x}[${T}] == "number"`,()=>{i.assign(k,(0,t._)`${x}[${T}]`),a.error(),i.assign(g,!1).break()}).code((0,t._)`${x}[${T}] = ${S}`)})}function m(S,k){const T=(0,r.useFunc)(i,n.default),b=i.name("outer");i.label(b).for((0,t._)`;${S}--;`,()=>i.for((0,t._)`${k} = ${S}; ${k}--;`,()=>i.if((0,t._)`${T}(${l}[${S}], ${l}[${k}])`,()=>{a.error(),i.assign(g,!1).break(b)})))}}};return Da.default=s,Da}var za={},of;function pw(){if(of)return za;of=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Ae(),t=Ue(),r=Fl(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return za.default=o,za}var Za={},sf;function fw(){if(sf)return Za;sf=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Ae(),t=Ue(),r=Fl(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:h}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=h.opts.loopEnum;let f;const g=()=>f??(f=(0,t.useFunc)(a,r.default));let _;if(p||l)_=a.let("valid"),s.block$data(_,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=a.const("vSchema",u);_=(0,e.or)(...c.map((m,S)=>w(v,S)))}s.pass(_);function y(){a.assign(_,!1),a.forOf("v",u,v=>a.if((0,e._)`${g()}(${i}, ${v})`,()=>a.assign(_,!0).break()))}function w(v,m){const S=c[m];return typeof S=="object"&&S!==null?(0,e._)`${g()}(${i}, ${v}[${m}])`:(0,e._)`${i} === ${S}`}}};return Za.default=o,Za}var af;function hw(){if(af)return Ra;af=1,Object.defineProperty(Ra,"__esModule",{value:!0});const e=nw(),t=ow(),r=aw(),n=iw(),o=lw(),s=cw(),a=uw(),i=dw(),l=pw(),c=fw(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return Ra.default=u,Ra}var Fa={},oo={},lf;function cf(){if(lf)return oo;lf=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.validateAdditionalItems=void 0;const e=Ae(),t=Ue(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:h}=s;h.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(h,l)){const g=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(g),()=>f(g)),s.ok(g)}function f(g){i.forRange("i",a.length,p,_=>{s.subschema({keyword:u,dataProp:_,dataPropType:t.Type.Num},g),h.allErrors||i.if((0,e.not)(g),()=>i.break())})}}return oo.validateAdditionalItems=o,oo.default=n,oo}var Va={},so={},uf;function df(){if(uf)return so;uf=1,Object.defineProperty(so,"__esModule",{value:!0}),so.validateTuple=void 0;const e=Ae(),t=Ue(),r=hr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:h,it:p}=s;_(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const f=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${g} > ${w}`,()=>s.subschema({keyword:h,schemaProp:w,dataProp:w},f)),s.ok(f))});function _(y){const{opts:w,errSchemaPath:v}=p,m=i.length,S=m===y.minItems&&(m===y.maxItems||y[a]===!1);if(w.strictTuples&&!S){const k=`"${h}" is ${m}-tuple, but minItems or maxItems/${a} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,k,w.strictTuples)}}}return so.validateTuple=o,so.default=n,so}var pf;function mw(){if(pf)return Va;pf=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=df(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Va.default=t,Va}var Ha={},ff;function gw(){if(ff)return Ha;ff=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=Ae(),t=Ue(),r=hr(),n=cf(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return Ha.default=s,Ha}var Ba={},hf;function yw(){if(hf)return Ba;hf=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Ae(),t=Ue(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,h;const{minContains:p,maxContains:f}=i;c.opts.next?(u=p===void 0?1:p,h=f):u=1;const g=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:h}),h===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(h!==void 0&&u>h){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let m=(0,e._)`${g} >= ${u}`;h!==void 0&&(m=(0,e._)`${m} && ${g} <= ${h}`),o.pass(m);return}c.items=!0;const _=s.name("valid");h===void 0&&u===1?w(_,()=>s.if(_,()=>s.break())):u===0?(s.let(_,!0),h!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(_,!1),y()),o.result(_,()=>o.reset());function y(){const m=s.name("_valid"),S=s.let("count",0);w(m,()=>s.if(m,()=>v(S)))}function w(m,S){s.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},m),S()})}function v(m){s.code((0,e._)`${m}++`),h===void 0?s.if((0,e._)`${m} >= ${u}`,()=>s.assign(_,!0).break()):(s.if((0,e._)`${m} > ${h}`,()=>s.assign(_,!1).break()),u===1?s.assign(_,!0):s.if((0,e._)`${m} >= ${u}`,()=>s.assign(_,!0)))}}};return Ba.default=n,Ba}var Vl={},mf;function vw(){return mf||(mf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ae(),r=Ue(),n=hr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,t.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,t._)`{property: ${l},
6
+ missingProperty: ${h},
7
+ depsCount: ${c},
8
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const p=Array.isArray(l[h])?c:u;p[h]=l[h]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:h,it:p}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const g in c){const _=c[g];if(_.length===0)continue;const y=(0,n.propertyInData)(u,h,g,p.opts.ownProperties);l.setParams({property:g,depsCount:_.length,deps:_.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of _)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,_,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:h,keyword:p,it:f}=l,g=u.name("valid");for(const _ in c)(0,r.alwaysValidSchema)(f,c[_])||(u.if((0,n.propertyInData)(u,h,_,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:_},g);l.mergeValidEvaluated(y,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=i,e.default=o})(Vl)),Vl}var Ja={},gf;function _w(){if(gf)return Ja;gf=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Ae(),t=Ue(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return Ja.default=n,Ja}var Wa={},yf;function vf(){if(yf)return Wa;yf=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=hr(),t=Ae(),r=dn(),n=Ue(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:h,it:p}=a;if(!h)throw new Error("ajv implementation error");const{allErrors:f,opts:g}=p;if(p.props=!0,g.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const _=(0,e.allSchemaProperties)(c.properties),y=(0,e.allSchemaProperties)(c.patternProperties);w(),a.ok((0,t._)`${h} === ${r.default.errors}`);function w(){i.forIn("key",u,T=>{!_.length&&!y.length?S(T):i.if(v(T),()=>S(T))})}function v(T){let b;if(_.length>8){const x=(0,n.schemaRefOrVal)(p,c.properties,"properties");b=(0,e.isOwnProperty)(i,x,T)}else _.length?b=(0,t.or)(..._.map(x=>(0,t._)`${T} === ${x}`)):b=t.nil;return y.length&&(b=(0,t.or)(b,...y.map(x=>(0,t._)`${(0,e.usePattern)(a,x)}.test(${T})`))),(0,t.not)(b)}function m(T){i.code((0,t._)`delete ${u}[${T}]`)}function S(T){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){m(T);return}if(l===!1){a.setParams({additionalProperty:T}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const b=i.name("valid");g.removeAdditional==="failing"?(k(T,b,!1),i.if((0,t.not)(b),()=>{a.reset(),m(T)})):(k(T,b),f||i.if((0,t.not)(b),()=>i.break()))}}function k(T,b,x){const I={keyword:"additionalProperties",dataProp:T,dataPropType:n.Type.Str};x===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,b)}}};return Wa.default=s,Wa}var Ga={},_f;function ww(){if(_f)return Ga;_f=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=ka(),t=hr(),r=Ue(),n=vf(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const h=(0,t.allSchemaProperties)(i);for(const y of h)u.definedProperties.add(y);u.opts.unevaluated&&h.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(h),u.props));const p=h.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(p.length===0)return;const f=a.name("valid");for(const y of p)g(y)?_(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),_(y),u.allErrors||a.else().var(f,!0),a.endIf()),s.it.definedProperties.add(y),s.ok(f);function g(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function _(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return Ga.default=o,Ga}var Ka={},wf;function bw(){if(wf)return Ka;wf=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=hr(),t=Ae(),r=Ue(),n=Ue(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:h}=u,p=(0,e.allSchemaProperties)(i),f=p.filter(S=>(0,r.alwaysValidSchema)(u,i[S]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=h.strictSchema&&!h.allowMatchingProperties&&c.properties,_=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:y}=u;w();function w(){for(const S of p)g&&v(S),u.allErrors?m(S):(a.var(_,!0),m(S),a.if(_))}function v(S){for(const k in g)new RegExp(S).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${S} (use allowMatchingProperties)`)}function m(S){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,S)}.test(${k})`,()=>{const T=f.includes(S);T||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:k,dataPropType:n.Type.Str},_),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${k}]`,!0):!T&&!u.allErrors&&a.if((0,t.not)(_),()=>a.break())})})}}};return Ka.default=o,Ka}var Ya={},bf;function kw(){if(bf)return Ya;bf=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Ue(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return Ya.default=t,Ya}var Qa={},kf;function Tw(){if(kf)return Qa;kf=1,Object.defineProperty(Qa,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:hr().validateUnion,error:{message:"must match a schema in anyOf"}};return Qa.default=t,Qa}var Xa={},Tf;function Cw(){if(Tf)return Xa;Tf=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=Ae(),t=Ue(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),h=s.let("passing",null),p=s.name("_valid");o.setParams({passing:h}),s.block(f),o.result(u,()=>o.reset(),()=>o.error(!0));function f(){c.forEach((g,_)=>{let y;(0,t.alwaysValidSchema)(l,g)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:_,compositeRule:!0},p),_>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(h,(0,e._)`[${h}, ${_}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(h,_),y&&o.mergeEvaluated(y,e.Name)})})}}};return Xa.default=n,Xa}var ei={},Cf;function Sw(){if(Cf)return ei;Cf=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ue(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return ei.default=t,ei}var ti={},Sf;function Iw(){if(Sf)return ti;Sf=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Ae(),t=Ue(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const h=a.let("valid",!0),p=a.name("_valid");if(f(),s.reset(),c&&u){const _=a.let("ifClause");s.setParams({ifClause:_}),a.if(p,g("then",_),g("else",_))}else c?a.if(p,g("then")):a.if((0,e.not)(p),g("else"));s.pass(h,()=>s.error(!0));function f(){const _=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(_)}function g(_,y){return()=>{const w=s.subschema({keyword:_},p);a.assign(h,p),s.mergeValidEvaluated(w,h),y?a.assign(y,(0,e._)`${_}`):s.setParams({ifClause:_})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return ti.default=n,ti}var ri={},If;function Ew(){if(If)return ri;If=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Ue(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return ri.default=t,ri}var Ef;function xw(){if(Ef)return Fa;Ef=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=cf(),t=mw(),r=df(),n=gw(),o=yw(),s=vw(),a=_w(),i=vf(),l=ww(),c=bw(),u=kw(),h=Tw(),p=Cw(),f=Sw(),g=Iw(),_=Ew();function y(w=!1){const v=[u.default,h.default,p.default,f.default,g.default,_.default,a.default,i.default,s.default,l.default,c.default];return w?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return Fa.default=y,Fa}var ni={},oi={},xf;function $w(){if(xf)return oi;xf=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Ae(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:h,errSchemaPath:p,schemaEnv:f,self:g}=u;if(!h.validateFormats)return;i?_():y();function _(){const w=s.scopeValue("formats",{ref:g.formats,code:h.code.formats}),v=s.const("fDef",(0,e._)`${w}[${c}]`),m=s.let("fType"),S=s.let("format");s.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>s.assign(m,(0,e._)`${v}.type || "string"`).assign(S,(0,e._)`${v}.validate`),()=>s.assign(m,(0,e._)`"string"`).assign(S,v)),n.fail$data((0,e.or)(k(),T()));function k(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${S}`}function T(){const b=f.$async?(0,e._)`(${v}.async ? await ${S}(${a}) : ${S}(${a}))`:(0,e._)`${S}(${a})`,x=(0,e._)`(typeof ${S} == "function" ? ${b} : ${S}.test(${a}))`;return(0,e._)`${S} && ${S} !== true && ${m} === ${o} && !${x}`}}function y(){const w=g.formats[l];if(!w){k();return}if(w===!0)return;const[v,m,S]=T(w);v===o&&n.pass(b());function k(){if(h.strictSchema===!1){g.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function T(x){const I=x instanceof RegExp?(0,e.regexpCode)(x):h.code.formats?(0,e._)`${h.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:x,code:I});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,e._)`${L}.validate`]:["string",x,L]}function b(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${a})`}return typeof m=="function"?(0,e._)`${S}(${a})`:(0,e._)`${S}.test(${a})`}}}};return oi.default=r,oi}var $f;function Rw(){if($f)return ni;$f=1,Object.defineProperty(ni,"__esModule",{value:!0});const t=[$w().default];return ni.default=t,ni}var Nn={},Rf;function Pw(){return Rf||(Rf=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.contentVocabulary=Nn.metadataVocabulary=void 0,Nn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Nn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Nn}var Pf;function Mw(){if(Pf)return Ea;Pf=1,Object.defineProperty(Ea,"__esModule",{value:!0});const e=rw(),t=hw(),r=xw(),n=Rw(),o=Pw(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Ea.default=s,Ea}var si={},Vo={},Mf;function Ow(){if(Mf)return Vo;Mf=1,Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Vo.DiscrError=e={})),Vo}var Of;function Nw(){if(Of)return si;Of=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Ae(),t=Ow(),r=Ul(),n=Sa(),o=Ue(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:h,it:p}=i,{oneOf:f}=h;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const g=u.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!f)throw new Error("discriminator: requires oneOf keyword");const _=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(g)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:g})),i.ok(_);function w(){const S=m();l.if(!1);for(const k in S)l.elseIf((0,e._)`${y} === ${k}`),l.assign(_,v(S[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function v(S){const k=l.name("valid"),T=i.subschema({keyword:"oneOf",schemaProp:S},k);return i.mergeEvaluated(T,e.Name),k}function m(){var S;const k={},T=x(h);let b=!0;for(let O=0;O<f.length;O++){let A=f[O];if(A?.$ref&&!(0,o.schemaHasRulesButRef)(A,p.self.RULES)){const U=A.$ref;if(A=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,U),A instanceof r.SchemaEnv&&(A=A.schema),A===void 0)throw new n.default(p.opts.uriResolver,p.baseId,U)}const N=(S=A?.properties)===null||S===void 0?void 0:S[g];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);b=b&&(T||x(A)),I(N,O)}if(!b)throw new Error(`discriminator: "${g}" must be required`);return k;function x({required:O}){return Array.isArray(O)&&O.includes(g)}function I(O,A){if(O.const)L(O.const,A);else if(O.enum)for(const N of O.enum)L(N,A);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function L(O,A){if(typeof O!="string"||O in k)throw new Error(`discriminator: "${g}" values must be unique strings`);k[O]=A}}}};return si.default=a,si}const Aw={$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 Nf;function Af(){return Nf||(Nf=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=X1(),n=Mw(),o=Nw(),s=Aw,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const g=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(g,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=ka();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ae();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=Dl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=Sa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(ga,ga.exports)),ga.exports}var qw=Af();const qf=Pn(qw);var De;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(De||(De={}));var Hl;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Hl||(Hl={}));const ce=De.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Br=e=>{switch(typeof e){case"undefined":return ce.undefined;case"string":return ce.string;case"number":return Number.isNaN(e)?ce.nan:ce.number;case"boolean":return ce.boolean;case"function":return ce.function;case"bigint":return ce.bigint;case"symbol":return ce.symbol;case"object":return Array.isArray(e)?ce.array:e===null?ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ce.promise:typeof Map<"u"&&e instanceof Map?ce.map:typeof Set<"u"&&e instanceof Set?ce.set:typeof Date<"u"&&e instanceof Date?ce.date:ce.object;default:return ce.unknown}},X=De.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"]),Lw=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Qt extends Error{get errors(){return this.issues}constructor(t){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=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Qt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,De.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Qt.create=e=>new Qt(e);const ao=(e,t)=>{let r;switch(e.code){case X.invalid_type:e.received===ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,De.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:r=`Unrecognized key(s) in object: ${De.joinValues(e.keys,", ")}`;break;case X.invalid_union:r="Invalid input";break;case X.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${De.joinValues(e.options)}`;break;case X.invalid_enum_value:r=`Invalid enum value. Expected ${De.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:r="Invalid function arguments";break;case X.invalid_return_type:r="Invalid function return type";break;case X.invalid_date:r="Invalid date";break;case X.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:De.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case X.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case X.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case X.custom:r="Invalid input";break;case X.invalid_intersection_types:r="Intersection results could not be merged";break;case X.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:r="Number must be finite";break;default:r=t.defaultError,De.assertNever(e)}return{message:r}};let Lf=ao;function jw(e){Lf=e}function ai(){return Lf}const ii=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}},Dw=[];function se(e,t){const r=ai(),n=ii({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ao?void 0:ao].filter(o=>!!o)});e.common.issues.push(n)}class Ot{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return ke;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return Ot.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return ke;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const ke=Object.freeze({status:"aborted"}),io=e=>({status:"dirty",value:e}),jt=e=>({status:"valid",value:e}),Bl=e=>e.status==="aborted",Jl=e=>e.status==="dirty",An=e=>e.status==="valid",Ho=e=>typeof Promise<"u"&&e instanceof Promise;var he;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(he||(he={}));class Or{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const jf=(e,t)=>{if(An(t))return{success:!0,data:t.value};if(!e.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 Qt(e.common.issues);return this._error=r,this._error}}};function $e(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}let Pe=class{get description(){return this._def.description}_getType(t){return Br(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Br(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ot,ctx:{common:t.parent.common,data:t.data,parsedType:Br(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Ho(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Br(t)},o=this._parseSync({data:t,path:n.path,parent:n});return jf(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Br(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return An(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:t,path:[],parent:r}).then(n=>An(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Br(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Ho(o)?o:Promise.resolve(o));return jf(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:X.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new mr({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return gr.create(this,this._def)}nullable(){return hn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jn.create(this)}promise(){return fo.create(this,this._def)}or(t){return Ko.create([this,t],this._def)}and(t){return Yo.create(this,t,this._def)}transform(t){return new mr({...$e(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new rs({...$e(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new Kl({typeName:B.ZodBranded,type:this,...$e(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ns({...$e(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return os.create(this,t)}readonly(){return ss.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Uw=/^c[^\s-]{8,}$/i,zw=/^[0-9a-z]+$/,Zw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fw=/^[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,Vw=/^[a-z0-9_-]{21}$/i,Hw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bw=/^[-+]?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)?)??$/,Jw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ww="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Wl;const Gw=/^(?:(?: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])$/,Kw=/^(?:(?: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])$/,Yw=/^(([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]))$/,Qw=/^(([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])$/,Xw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,eb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Df="((\\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])))",tb=new RegExp(`^${Df}$`);function Uf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function rb(e){return new RegExp(`^${Uf(e)}$`)}function zf(e){let t=`${Df}T${Uf(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function nb(e,t){return!!((t==="v4"||!t)&&Gw.test(e)||(t==="v6"||!t)&&Yw.test(e))}function ob(e,t){if(!Hw.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function sb(e,t){return!!((t==="v4"||!t)&&Kw.test(e)||(t==="v6"||!t)&&Qw.test(e))}let lo=class ma extends Pe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ce.string){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ce.string,received:s.parsedType}),ke}const n=new Ot;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?se(o,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&se(o,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Jw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"email",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Wl||(Wl=new RegExp(Ww,"u")),Wl.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"emoji",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Fw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"uuid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Vw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"nanoid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Uw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cuid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")zw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cuid2",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Zw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"ulid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),se(o,{validation:"url",code:X.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"regex",code:X.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?zf(s).test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?tb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?rb(s).test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Bw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"duration",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?nb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"ip",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ob(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"jwt",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?sb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cidr",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Xw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?eb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64url",code:X.invalid_string,message:s.message}),n.dirty()):De.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:X.invalid_string,...he.errToObj(n)})}_addCheck(t){return new ma({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...he.errToObj(t)})}url(t){return this._addCheck({kind:"url",...he.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...he.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...he.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...he.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...he.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...he.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...he.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...he.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...he.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...he.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...he.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...he.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...he.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...he.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...he.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...he.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...he.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...he.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...he.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...he.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...he.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...he.errToObj(r)})}nonempty(t){return this.min(1,he.errToObj(t))}trim(){return new ma({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ma({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ma({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};lo.create=e=>new lo({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...$e(e)});function ab(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}let Bo=class cp extends Pe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ce.number){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ce.number,received:s.parsedType}),ke}let n;const o=new Ot;for(const s of this._def.checks)s.kind==="int"?De.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),se(n,{code:X.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ab(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_finite,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,he.toString(r))}gt(t,r){return this.setLimit("min",t,!1,he.toString(r))}lte(t,r){return this.setLimit("max",t,!0,he.toString(r))}lt(t,r){return this.setLimit("max",t,!1,he.toString(r))}setLimit(t,r,n,o){return new cp({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new cp({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:he.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:he.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:he.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&De.isInteger(t.value))}get isFinite(){let t=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"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Bo.create=e=>new Bo({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...$e(e)});class fn extends Pe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ce.bigint)return this._getInvalidInput(t);let n;const o=new Ot;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:ce.bigint,received:r.parsedType}),ke}gte(t,r){return this.setLimit("min",t,!0,he.toString(r))}gt(t,r){return this.setLimit("min",t,!1,he.toString(r))}lte(t,r){return this.setLimit("max",t,!0,he.toString(r))}lt(t,r){return this.setLimit("max",t,!1,he.toString(r))}setLimit(t,r,n,o){return new fn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new fn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:he.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:he.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}fn.create=e=>new fn({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...$e(e)});let Jo=class extends Pe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ce.boolean){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.boolean,received:n.parsedType}),ke}return jt(t.data)}};Jo.create=e=>new Jo({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...$e(e)});class qn extends Pe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ce.date){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ce.date,received:s.parsedType}),ke}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_date}),ke}const n=new Ot;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):De.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new qn({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:he.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:he.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}qn.create=e=>new qn({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...$e(e)});class li extends Pe{_parse(t){if(this._getType(t)!==ce.symbol){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.symbol,received:n.parsedType}),ke}return jt(t.data)}}li.create=e=>new li({typeName:B.ZodSymbol,...$e(e)});class Wo extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.undefined,received:n.parsedType}),ke}return jt(t.data)}}Wo.create=e=>new Wo({typeName:B.ZodUndefined,...$e(e)});let Go=class extends Pe{_parse(t){if(this._getType(t)!==ce.null){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.null,received:n.parsedType}),ke}return jt(t.data)}};Go.create=e=>new Go({typeName:B.ZodNull,...$e(e)});let co=class extends Pe{constructor(){super(...arguments),this._any=!0}_parse(t){return jt(t.data)}};co.create=e=>new co({typeName:B.ZodAny,...$e(e)});let Ln=class extends Pe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return jt(t.data)}};Ln.create=e=>new Ln({typeName:B.ZodUnknown,...$e(e)});let Jr=class extends Pe{_parse(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:ce.never,received:r.parsedType}),ke}};Jr.create=e=>new Jr({typeName:B.ZodNever,...$e(e)});class ci extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.void,received:n.parsedType}),ke}return jt(t.data)}}ci.create=e=>new ci({typeName:B.ZodVoid,...$e(e)});let jn=class Pl extends Pe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ce.array)return se(r,{code:X.invalid_type,expected:ce.array,received:r.parsedType}),ke;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(se(r,{code:a?X.too_big:X.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(se(r,{code:X.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(se(r,{code:X.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Or(r,a,r.path,i)))).then(a=>Ot.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Or(r,a,r.path,i)));return Ot.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Pl({...this._def,minLength:{value:t,message:he.toString(r)}})}max(t,r){return new Pl({...this._def,maxLength:{value:t,message:he.toString(r)}})}length(t,r){return new Pl({...this._def,exactLength:{value:t,message:he.toString(r)}})}nonempty(t){return this.min(1,t)}};jn.create=(e,t)=>new jn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...$e(t)});function uo(e){if(e instanceof or){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=gr.create(uo(n))}return new or({...e._def,shape:()=>t})}else return e instanceof jn?new jn({...e._def,type:uo(e.element)}):e instanceof gr?gr.create(uo(e.unwrap())):e instanceof hn?hn.create(uo(e.unwrap())):e instanceof Nr?Nr.create(e.items.map(t=>uo(t))):e}let or=class Mr extends Pe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=De.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ce.object){const c=this._getOrReturnCtx(t);return se(c,{code:X.invalid_type,expected:ce.object,received:c.parsedType}),ke}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Jr&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],h=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Or(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Jr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(se(o,{code:X.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const h=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Or(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,p=await u.value;c.push({key:h,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Ot.mergeObjectSync(n,c)):Ot.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return he.errToObj,new Mr({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:he.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Mr({...this._def,unknownKeys:"strip"})}passthrough(){return new Mr({...this._def,unknownKeys:"passthrough"})}extend(t){return new Mr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Mr({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:B.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Mr({...this._def,catchall:t})}pick(t){const r={};for(const n of De.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Mr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of De.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Mr({...this._def,shape:()=>r})}deepPartial(){return uo(this)}partial(t){const r={};for(const n of De.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Mr({...this._def,shape:()=>r})}required(t){const r={};for(const n of De.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof gr;)s=s._def.innerType;r[n]=s}return new Mr({...this._def,shape:()=>r})}keyof(){return Vf(De.objectKeys(this.shape))}};or.create=(e,t)=>new or({shape:()=>e,unknownKeys:"strip",catchall:Jr.create(),typeName:B.ZodObject,...$e(t)}),or.strictCreate=(e,t)=>new or({shape:()=>e,unknownKeys:"strict",catchall:Jr.create(),typeName:B.ZodObject,...$e(t)}),or.lazycreate=(e,t)=>new or({shape:e,unknownKeys:"strip",catchall:Jr.create(),typeName:B.ZodObject,...$e(t)});let Ko=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new Qt(i.ctx.common.issues));return se(r,{code:X.invalid_union,unionErrors:a}),ke}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new Qt(l));return se(r,{code:X.invalid_union,unionErrors:i}),ke}}get options(){return this._def.options}};Ko.create=(e,t)=>new Ko({options:e,typeName:B.ZodUnion,...$e(t)});const Wr=e=>e instanceof Qo?Wr(e.schema):e instanceof mr?Wr(e.innerType()):e instanceof Xo?[e.value]:e instanceof es?e.options:e instanceof ts?De.objectValues(e.enum):e instanceof rs?Wr(e._def.innerType):e instanceof Wo?[void 0]:e instanceof Go?[null]:e instanceof gr?[void 0,...Wr(e.unwrap())]:e instanceof hn?[null,...Wr(e.unwrap())]:e instanceof Kl||e instanceof ss?Wr(e.unwrap()):e instanceof ns?Wr(e._def.innerType):[];let Zf=class j1 extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.object)return se(r,{code:X.invalid_type,expected:ce.object,received:r.parsedType}),ke;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(se(r,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ke)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const s of r){const a=Wr(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new j1({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...$e(n)})}};function Gl(e,t){const r=Br(e),n=Br(t);if(e===t)return{valid:!0,data:e};if(r===ce.object&&n===ce.object){const o=De.objectKeys(t),s=De.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Gl(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===ce.array&&n===ce.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=Gl(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ce.date&&n===ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let Yo=class extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Bl(s)||Bl(a))return ke;const i=Gl(s.value,a.value);return i.valid?((Jl(s)||Jl(a))&&r.dirty(),{status:r.value,value:i.data}):(se(n,{code:X.invalid_intersection_types}),ke)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Yo.create=(e,t,r)=>new Yo({left:e,right:t,typeName:B.ZodIntersection,...$e(r)});class Nr extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.array)return se(n,{code:X.invalid_type,expected:ce.array,received:n.parsedType}),ke;if(n.data.length<this._def.items.length)return se(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ke;!this._def.rest&&n.data.length>this._def.items.length&&(se(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Or(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Ot.mergeArray(r,a)):Ot.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Nr({...this._def,rest:t})}}Nr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nr({items:e,typeName:B.ZodTuple,rest:null,...$e(t)})};let Ff=class up extends Pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.object)return se(n,{code:X.invalid_type,expected:ce.object,received:n.parsedType}),ke;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Or(n,i,n.path,i)),value:a._parse(new Or(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?Ot.mergeObjectAsync(r,o):Ot.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Pe?new up({keyType:t,valueType:r,typeName:B.ZodRecord,...$e(n)}):new up({keyType:lo.create(),valueType:t,typeName:B.ZodRecord,...$e(r)})}};class ui extends Pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.map)return se(n,{code:X.invalid_type,expected:ce.map,received:n.parsedType}),ke;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Or(n,i,n.path,[c,"key"])),value:s._parse(new Or(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return ke;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return ke;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}ui.create=(e,t,r)=>new ui({valueType:t,keyType:e,typeName:B.ZodMap,...$e(r)});class Dn extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.set)return se(n,{code:X.invalid_type,expected:ce.set,received:n.parsedType}),ke;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(se(n,{code:X.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(se(n,{code:X.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return ke;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Or(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Dn({...this._def,minSize:{value:t,message:he.toString(r)}})}max(t,r){return new Dn({...this._def,maxSize:{value:t,message:he.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Dn.create=(e,t)=>new Dn({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...$e(t)});class po extends Pe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.function)return se(r,{code:X.invalid_type,expected:ce.function,received:r.parsedType}),ke;function n(i,l){return ii({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ai(),ao].filter(c=>!!c),issueData:{code:X.invalid_arguments,argumentsError:l}})}function o(i,l){return ii({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ai(),ao].filter(c=>!!c),issueData:{code:X.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof fo){const i=this;return jt(async function(...l){const c=new Qt([]),u=await i._def.args.parseAsync(l,s).catch(f=>{throw c.addIssue(n(l,f)),c}),h=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(h,s).catch(f=>{throw c.addIssue(o(h,f)),c})})}else{const i=this;return jt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new Qt([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),h=i._def.returns.safeParse(u,s);if(!h.success)throw new Qt([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new po({...this._def,args:Nr.create(t).rest(Ln.create())})}returns(t){return new po({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new po({args:t||Nr.create([]).rest(Ln.create()),returns:r||Ln.create(),typeName:B.ZodFunction,...$e(n)})}}let Qo=class extends Pe{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Qo.create=(e,t)=>new Qo({getter:e,typeName:B.ZodLazy,...$e(t)});let Xo=class extends Pe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return se(r,{received:r.data,code:X.invalid_literal,expected:this._def.value}),ke}return{status:"valid",value:t.data}}get value(){return this._def.value}};Xo.create=(e,t)=>new Xo({value:e,typeName:B.ZodLiteral,...$e(t)});function Vf(e,t){return new es({values:e,typeName:B.ZodEnum,...$e(t)})}let es=class dp extends Pe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return se(r,{expected:De.joinValues(n),received:r.parsedType,code:X.invalid_type}),ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return se(r,{received:r.data,code:X.invalid_enum_value,options:n}),ke}return jt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return dp.create(t,{...this._def,...r})}exclude(t,r=this._def){return dp.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};es.create=Vf;class ts extends Pe{_parse(t){const r=De.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ce.string&&n.parsedType!==ce.number){const o=De.objectValues(r);return se(n,{expected:De.joinValues(o),received:n.parsedType,code:X.invalid_type}),ke}if(this._cache||(this._cache=new Set(De.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=De.objectValues(r);return se(n,{received:n.data,code:X.invalid_enum_value,options:o}),ke}return jt(t.data)}get enum(){return this._def.values}}ts.create=(e,t)=>new ts({values:e,typeName:B.ZodNativeEnum,...$e(t)});class fo extends Pe{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.promise&&r.common.async===!1)return se(r,{code:X.invalid_type,expected:ce.promise,received:r.parsedType}),ke;const n=r.parsedType===ce.promise?r.data:Promise.resolve(r.data);return jt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}fo.create=(e,t)=>new fo({type:e,typeName:B.ZodPromise,...$e(t)});class mr extends Pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{se(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return ke;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?ke:l.status==="dirty"||r.value==="dirty"?io(l.value):l});{if(r.value==="aborted")return ke;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?ke:i.status==="dirty"||r.value==="dirty"?io(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ke:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?ke:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!An(a))return ke;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>An(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):ke);De.assertNever(o)}}mr.create=(e,t,r)=>new mr({schema:e,typeName:B.ZodEffects,effect:t,...$e(r)}),mr.createWithPreprocess=(e,t,r)=>new mr({schema:t,effect:{type:"preprocess",transform:e},typeName:B.ZodEffects,...$e(r)});let gr=class extends Pe{_parse(t){return this._getType(t)===ce.undefined?jt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};gr.create=(e,t)=>new gr({innerType:e,typeName:B.ZodOptional,...$e(t)});let hn=class extends Pe{_parse(t){return this._getType(t)===ce.null?jt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};hn.create=(e,t)=>new hn({innerType:e,typeName:B.ZodNullable,...$e(t)});let rs=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rs.create=(e,t)=>new rs({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$e(t)});let ns=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ho(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Qt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ns.create=(e,t)=>new ns({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$e(t)});class di extends Pe{_parse(t){if(this._getType(t)!==ce.nan){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ce.nan,received:n.parsedType}),ke}return{status:"valid",value:t.data}}}di.create=e=>new di({typeName:B.ZodNaN,...$e(e)});const ib=Symbol("zod_brand");class Kl extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class os extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ke:s.status==="dirty"?(r.dirty(),io(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ke:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new os({in:t,out:r,typeName:B.ZodPipeline})}}let ss=class extends Pe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(An(o)&&(o.value=Object.freeze(o.value)),o);return Ho(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};ss.create=(e,t)=>new ss({innerType:e,typeName:B.ZodReadonly,...$e(t)});function Hf(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Bf(e,t={},r){return e?co.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=Hf(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=Hf(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):co.create()}const lb={object:or.lazycreate};var B;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(B||(B={}));const cb=(e,t={message:`Input not instance of ${e.name}`})=>Bf(r=>r instanceof e,t),Fe=lo.create,sr=Bo.create,ub=di.create,db=fn.create,Jf=Jo.create,pb=qn.create,fb=li.create,hb=Wo.create,mb=Go.create,gb=co.create,yb=Ln.create,vb=Jr.create,_b=ci.create,Gr=jn.create,Ft=or.create,wb=or.strictCreate,pi=Ko.create,bb=Zf.create,kb=Yo.create,Tb=Nr.create,Cb=Ff.create,Sb=ui.create,Ib=Dn.create,Eb=po.create,xb=Qo.create,$b=Xo.create,as=es.create,Rb=ts.create,Pb=fo.create,Wf=mr.create,Mb=gr.create,Ob=hn.create,Nb=mr.createWithPreprocess,Ab=os.create,qb=Object.freeze(Object.defineProperty({__proto__:null,BRAND:ib,DIRTY:io,EMPTY_PATH:Dw,INVALID:ke,NEVER:ke,OK:jt,ParseStatus:Ot,Schema:Pe,ZodAny:co,ZodArray:jn,ZodBigInt:fn,ZodBoolean:Jo,ZodBranded:Kl,ZodCatch:ns,ZodDate:qn,ZodDefault:rs,ZodDiscriminatedUnion:Zf,ZodEffects:mr,ZodEnum:es,ZodError:Qt,get ZodFirstPartyTypeKind(){return B},ZodFunction:po,ZodIntersection:Yo,ZodIssueCode:X,ZodLazy:Qo,ZodLiteral:Xo,ZodMap:ui,ZodNaN:di,ZodNativeEnum:ts,ZodNever:Jr,ZodNull:Go,ZodNullable:hn,ZodNumber:Bo,ZodObject:or,ZodOptional:gr,ZodParsedType:ce,ZodPipeline:os,ZodPromise:fo,ZodReadonly:ss,ZodRecord:Ff,ZodSchema:Pe,ZodSet:Dn,ZodString:lo,ZodSymbol:li,ZodTransformer:mr,ZodTuple:Nr,ZodType:Pe,ZodUndefined:Wo,ZodUnion:Ko,ZodUnknown:Ln,ZodVoid:ci,addIssueToContext:se,any:gb,array:Gr,bigint:db,boolean:Jf,coerce:{string:(e=>lo.create({...e,coerce:!0})),number:(e=>Bo.create({...e,coerce:!0})),boolean:(e=>Jo.create({...e,coerce:!0})),bigint:(e=>fn.create({...e,coerce:!0})),date:(e=>qn.create({...e,coerce:!0}))},custom:Bf,date:pb,datetimeRegex:zf,defaultErrorMap:ao,discriminatedUnion:bb,effect:Wf,enum:as,function:Eb,getErrorMap:ai,getParsedType:Br,instanceof:cb,intersection:kb,isAborted:Bl,isAsync:Ho,isDirty:Jl,isValid:An,late:lb,lazy:xb,literal:$b,makeIssue:ii,map:Sb,nan:ub,nativeEnum:Rb,never:vb,null:mb,nullable:Ob,number:sr,object:Ft,get objectUtil(){return Hl},oboolean:()=>Jf().optional(),onumber:()=>sr().optional(),optional:Mb,ostring:()=>Fe().optional(),pipeline:Ab,preprocess:Nb,promise:Pb,quotelessJson:Lw,record:Cb,set:Ib,setErrorMap:jw,strictObject:wb,string:Fe,symbol:fb,transformer:Wf,tuple:Tb,undefined:hb,union:pi,unknown:yb,get util(){return De},void:_b},Symbol.toStringTag,{value:"Module"})),Gf=Object.freeze({status:"aborted"});function W(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class is extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Kf={};function mn(e){return Kf}function Yf(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Lb(e,t){return typeof t=="bigint"?t.toString():t}function Yl(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ql(e){return e==null}function Xl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function jb(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Ve(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ls(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cs(e){return JSON.stringify(e)}const Qf=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Db=Yl(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function hi(e){if(fi(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(fi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Ub=new Set(["string","number","symbol"]);function us(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function fe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function zb(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zb={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 Fb(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return gn(e,{...e._zod.def,shape:r,checks:[]})}function Vb(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return gn(e,{...e._zod.def,shape:r,checks:[]})}function Hb(e,t){if(!hi(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return ls(this,"shape",n),n},checks:[]};return gn(e,r)}function Bb(e,t){return gn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ls(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Jb(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return gn(t,{...t._zod.def,shape:o,checks:[]})}function Wb(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return gn(t,{...t._zod.def,shape:o,checks:[]})}function ds(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Un(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function mi(e){return typeof e=="string"?e:e?.message}function yn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=mi(e.inst?._zod.def?.error?.(e))??mi(t?.error?.(e))??mi(r.customError?.(e))??mi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function ec(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ps(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Xf=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Lb,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},eh=W("$ZodError",Xf),gi=W("$ZodError",Xf,{Parent:Error});function Gb(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Kb(e,t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const th=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new is;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>yn(l,s,mn())));throw Qf(i,o?.callee),i}return a.value},Yb=th(gi),rh=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>yn(l,s,mn())));throw Qf(i,o?.callee),i}return a.value},Qb=rh(gi),nh=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new is;return s.issues.length?{success:!1,error:new(e??eh)(s.issues.map(a=>yn(a,o,mn())))}:{success:!0,data:s.value}},tc=nh(gi),oh=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>yn(a,o,mn())))}:{success:!0,data:s.value}},rc=oh(gi),Xb=/^[cC][^\s-]{8,}$/,e3=/^[0-9a-z]+$/,t3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,r3=/^[0-9a-vA-V]{20}$/,n3=/^[A-Za-z0-9]{27}$/,o3=/^[a-zA-Z0-9_-]{21}$/,s3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,a3=/^([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})$/,sh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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)$/,i3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,l3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function c3(){return new RegExp(l3,"u")}const u3=/^(?:(?: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])$/,d3=/^(([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})$/,p3=/^((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])$/,f3=/^(([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])$/,h3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ah=/^[A-Za-z0-9_-]*$/,m3=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,g3=/^\+(?:[0-9]){6,14}[0-9]$/,ih="(?:(?:\\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])))",y3=new RegExp(`^${ih}$`);function lh(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function v3(e){return new RegExp(`^${lh(e)}$`)}function _3(e){const t=lh({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${ih}T(?:${n})$`)}const w3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},b3=/^\d+$/,k3=/^-?\d+(?:\.\d+)?/i,T3=/true|false/i,C3=/null/i,S3=/^[^A-Z]*$/,I3=/^[^a-z]*$/,Vt=W("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ch={number:"number",bigint:"bigint",object:"date"},uh=W("$ZodCheckLessThan",(e,t)=>{Vt.init(e,t);const r=ch[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),dh=W("$ZodCheckGreaterThan",(e,t)=>{Vt.init(e,t);const r=ch[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),E3=W("$ZodCheckMultipleOf",(e,t)=>{Vt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):jb(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),x3=W("$ZodCheckNumberFormat",(e,t)=>{Vt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Zb[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=b3)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),$3=W("$ZodCheckMaxLength",(e,t)=>{var r;Vt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=ec(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),R3=W("$ZodCheckMinLength",(e,t)=>{var r;Vt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=ec(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),P3=W("$ZodCheckLengthEquals",(e,t)=>{var r;Vt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=ec(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),yi=W("$ZodCheckStringFormat",(e,t)=>{var r,n;Vt.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),M3=W("$ZodCheckRegex",(e,t)=>{yi.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),O3=W("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=S3),yi.init(e,t)}),N3=W("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=I3),yi.init(e,t)}),A3=W("$ZodCheckIncludes",(e,t)=>{Vt.init(e,t);const r=us(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),q3=W("$ZodCheckStartsWith",(e,t)=>{Vt.init(e,t);const r=new RegExp(`^${us(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),L3=W("$ZodCheckEndsWith",(e,t)=>{Vt.init(e,t);const r=new RegExp(`.*${us(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),j3=W("$ZodCheckOverwrite",(e,t)=>{Vt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class D3{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
9
+ `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
10
+ `))}}const U3={major:4,minor:0,patch:0},Ke=W("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=U3;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=ds(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const h=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new is;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==h&&(l||(l=ds(s,h)))});else{if(s.issues.length===h)continue;l||(l=ds(s,h))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new is;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=tc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return rc(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),nc=W("$ZodString",(e,t)=>{Ke.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??w3(e._zod.bag),e._zod.parse=(r,n)=>{if(t.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:e}),r}}),ot=W("$ZodStringFormat",(e,t)=>{yi.init(e,t),nc.init(e,t)}),z3=W("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=a3),ot.init(e,t)}),Z3=W("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=sh(n))}else t.pattern??(t.pattern=sh());ot.init(e,t)}),F3=W("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=i3),ot.init(e,t)}),V3=W("$ZodURL",(e,t)=>{ot.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:m3.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),H3=W("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=c3()),ot.init(e,t)}),B3=W("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=o3),ot.init(e,t)}),J3=W("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Xb),ot.init(e,t)}),W3=W("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=e3),ot.init(e,t)}),G3=W("$ZodULID",(e,t)=>{t.pattern??(t.pattern=t3),ot.init(e,t)}),K3=W("$ZodXID",(e,t)=>{t.pattern??(t.pattern=r3),ot.init(e,t)}),Y3=W("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=n3),ot.init(e,t)}),Q3=W("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=_3(t)),ot.init(e,t)}),X3=W("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=y3),ot.init(e,t)}),e9=W("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=v3(t)),ot.init(e,t)}),t9=W("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=s3),ot.init(e,t)}),r9=W("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=u3),ot.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),n9=W("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=d3),ot.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),o9=W("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=p3),ot.init(e,t)}),s9=W("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=f3),ot.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function ph(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const a9=W("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=h3),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{ph(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function i9(e){if(!ah.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return ph(r)}const l9=W("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ah),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{i9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),c9=W("$ZodE164",(e,t)=>{t.pattern??(t.pattern=g3),ot.init(e,t)});function u9(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const d9=W("$ZodJWT",(e,t)=>{ot.init(e,t),e._zod.check=r=>{u9(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),fh=W("$ZodNumber",(e,t)=>{Ke.init(e,t),e._zod.pattern=e._zod.bag.pattern??k3,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),p9=W("$ZodNumber",(e,t)=>{x3.init(e,t),fh.init(e,t)}),f9=W("$ZodBoolean",(e,t)=>{Ke.init(e,t),e._zod.pattern=T3,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),h9=W("$ZodNull",(e,t)=>{Ke.init(e,t),e._zod.pattern=C3,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),m9=W("$ZodAny",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),g9=W("$ZodUnknown",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),y9=W("$ZodNever",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function hh(e,t,r){e.issues.length&&t.issues.push(...Un(r,e.issues)),t.value[r]=e.value}const v9=W("$ZodArray",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>hh(c,r,a))):hh(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function vi(e,t,r){e.issues.length&&t.issues.push(...Un(r,e.issues)),t.value[r]=e.value}function mh(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Un(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const gh=W("$ZodObject",(e,t)=>{Ke.init(e,t);const r=Yl(()=>{const h=Object.keys(t.shape);for(const f of h)if(!(t.shape[f]instanceof Ke))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=zb(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(p)}});Ve(e._zod,"propValues",()=>{const h=t.shape,p={};for(const f in h){const g=h[f]._zod;if(g.values){p[f]??(p[f]=new Set);for(const _ of g.values)p[f].add(_)}}return p});const n=h=>{const p=new D3(["shape","payload","ctx"]),f=r.value,g=v=>{const m=cs(v);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const _=Object.create(null);let y=0;for(const v of f.keys)_[v]=`key_${y++}`;p.write("const newResult = {}");for(const v of f.keys)if(f.optionalKeys.has(v)){const m=_[v];p.write(`const ${m} = ${g(v)};`);const S=cs(v);p.write(`
11
+ if (${m}.issues.length) {
12
+ if (input[${S}] === undefined) {
13
+ if (${S} in input) {
14
+ newResult[${S}] = undefined;
15
15
  }
16
16
  } else {
17
17
  payload.issues = payload.issues.concat(
18
- ${_}.issues.map((iss) => ({
18
+ ${m}.issues.map((iss) => ({
19
19
  ...iss,
20
- path: iss.path ? [${b}, ...iss.path] : [${b}],
20
+ path: iss.path ? [${S}, ...iss.path] : [${S}],
21
21
  }))
22
22
  );
23
23
  }
24
- } else if (${_}.value === undefined) {
25
- if (${b} in input) newResult[${b}] = undefined;
24
+ } else if (${m}.value === undefined) {
25
+ if (${S} in input) newResult[${S}] = undefined;
26
26
  } else {
27
- newResult[${b}] = ${_}.value;
27
+ newResult[${S}] = ${m}.value;
28
28
  }
29
- `)}else{const _=v[y];h.write(`const ${_} = ${f(y)};`),h.write(`
30
- if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
29
+ `)}else{const m=_[v];p.write(`const ${m} = ${g(v)};`),p.write(`
30
+ if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
31
31
  ...iss,
32
- path: iss.path ? [${As(y)}, ...iss.path] : [${As(y)}]
33
- })));`),h.write(`newResult[${As(y)}] = ${_}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const w=h.compile();return(y,_)=>w(p,y,_)};let s;const o=Ea,a=!af.jitless,c=a&&kw.value,l=e.catchall;let u;t._zod.parse=(p,h)=>{u??(u=r.value);const d=p.value;if(!o(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;const f=[];if(a&&c&&h?.async===!1&&h.jitless!==!0)s||(s=n(e.shape)),p=s(p,h);else{p.value={};const _=u.shape;for(const b of u.keys){const k=_[b],S=k._zod.run({value:d[b],issues:[]},h),T=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?f.push(S.then(x=>T?$f(x,p,b,d):Oa(x,p,b))):T?$f(S,p,b,d):Oa(S,p,b)}}if(!l)return f.length?Promise.all(f).then(()=>p):p;const v=[],g=u.keySet,w=l._zod,y=w.def.type;for(const _ of Object.keys(d)){if(g.has(_))continue;if(y==="never"){v.push(_);continue}const b=w.run({value:d[_],issues:[]},h);b instanceof Promise?f.push(b.then(k=>Oa(k,p,_))):Oa(b,p,_)}return v.length&&p.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:t}),f.length?Promise.all(f).then(()=>p):p}});function xf(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(o=>Zr(o,n,Dr())))}),e}const If=J("$ZodUnion",(t,e)=>{Ze.init(t,e),Me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>lc(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const o=[];for(const a of e.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)o.push(i),s=!0;else{if(i.issues.length===0)return i;o.push(i)}}return s?Promise.all(o).then(a=>xf(a,r,t,n)):xf(o,r,t,n)}}),r3=J("$ZodDiscriminatedUnion",(t,e)=>{If.init(t,e);const r=t._zod.parse;Me(t._zod,"propValues",()=>{const s={};for(const o of e.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[i,c]of Object.entries(a)){s[i]||(s[i]=new Set);for(const l of c)s[i].add(l)}}return s});const n=ic(()=>{const s=e.options,o=new Map;for(const a of s){const i=a._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const c of i){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,a)}}return o});t._zod.parse=(s,o)=>{const a=s.value;if(!Ea(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const i=n.value.get(a?.[e.discriminator]);return i?i._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),n3=J("$ZodIntersection",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,o=e.left._zod.run({value:s,issues:[]},n),a=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([c,l])=>Rf(r,c,l)):Rf(r,o,a)}});function hc(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(xa(t)&&xa(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(const o of n){const a=hc(t[o],e[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};s[o]=a.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],o=e[n],a=hc(s,o);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Rf(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Ns(t))return t;const n=hc(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 s3=J("$ZodRecord",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!xa(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const o=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;r.value={};for(const c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const l=e.valueType._zod.run({value:s[c],issues:[]},n);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&r.issues.push(...pn(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...pn(c,l.issues)),r.value[c]=l.value)}let i;for(const c in s)a.has(c)||(i=i??[],i.push(c));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const i=e.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(l=>Zr(l,n,Dr())),input:a,path:[a],inst:t}),r.value[i.value]=i.value;continue}const c=e.valueType._zod.run({value:s[a],issues:[]},n);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&r.issues.push(...pn(a,l.issues)),r.value[i.value]=l.value})):(c.issues.length&&r.issues.push(...pn(a,c.issues)),r.value[i.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),o3=J("$ZodEnum",(t,e)=>{Ze.init(t,e);const r=cf(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Sw.has(typeof n)).map(n=>typeof n=="string"?Ms(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),a3=J("$ZodLiteral",(t,e)=>{Ze.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ms(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}}),i3=J("$ZodTransform",(t,e)=>{Ze.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(a=>(r.value=a,r));if(s instanceof Promise)throw new Ps;return r.value=s,r}}),c3=J("$ZodOptional",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Me(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${lc(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)}),l3=J("$ZodNullable",(t,e)=>{Ze.init(t,e),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${lc(r.source)}|null)$`):void 0}),Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),u3=J("$ZodDefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Pf(o,e)):Pf(s,e)}});function Pf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const d3=J("$ZodPrefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),p3=J("$ZodNonOptional",(t,e)=>{Ze.init(t,e),Me(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(o=>Of(o,t)):Of(s,t)}});function Of(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 f3=J("$ZodCatch",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(a=>Zr(a,n,Dr()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Zr(o,n,Dr()))},input:r.value}),r.issues=[]),r)}}),h3=J("$ZodPipe",(t,e)=>{Ze.init(t,e),Me(t._zod,"values",()=>e.in._zod.values),Me(t._zod,"optin",()=>e.in._zod.optin),Me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Af(o,e,n)):Af(s,e,n)}});function Af(t,e,r){return Ns(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const m3=J("$ZodReadonly",(t,e)=>{Ze.init(t,e),Me(t._zod,"propValues",()=>e.innerType._zod.propValues),Me(t._zod,"values",()=>e.innerType._zod.values),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Mf):Mf(s)}});function Mf(t){return t.value=Object.freeze(t.value),t}const g3=J("$ZodLazy",(t,e)=>{Ze.init(t,e),Me(t._zod,"innerType",()=>e.getter()),Me(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Me(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Me(t._zod,"optin",()=>t._zod.innerType._zod.optin),Me(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),y3=J("$ZodCustom",(t,e)=>{kt.init(t,e),Ze.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(o=>Nf(o,r,n,t));Nf(s,r,n,t)}});function Nf(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(Ls(s))}}class Lf{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 _3(){return new Lf}const js=_3();function v3(t,e){return new t({type:"string",...ae(e)})}function w3(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function jf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function b3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function k3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function S3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function T3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function qf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function C3(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function $3(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function E3(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function x3(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function I3(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function R3(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function P3(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function O3(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function A3(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function M3(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function N3(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function zf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function L3(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function j3(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function q3(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function z3(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function D3(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function U3(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function Z3(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function F3(t,e){return new t({type:"number",checks:[],...ae(e)})}function V3(t,e){return new t({type:"number",coerce:!0,checks:[],...ae(e)})}function H3(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function B3(t,e){return new t({type:"boolean",...ae(e)})}function J3(t,e){return new t({type:"null",...ae(e)})}function G3(t){return new t({type:"any"})}function W3(t){return new t({type:"unknown"})}function K3(t,e){return new t({type:"never",...ae(e)})}function Df(t,e){return new bf({check:"less_than",...ae(e),value:t,inclusive:!1})}function mc(t,e){return new bf({check:"less_than",...ae(e),value:t,inclusive:!0})}function Uf(t,e){return new kf({check:"greater_than",...ae(e),value:t,inclusive:!1})}function gc(t,e){return new kf({check:"greater_than",...ae(e),value:t,inclusive:!0})}function Zf(t,e){return new ub({check:"multiple_of",...ae(e),value:t})}function Ff(t,e){return new pb({check:"max_length",...ae(e),maximum:t})}function Aa(t,e){return new fb({check:"min_length",...ae(e),minimum:t})}function Vf(t,e){return new hb({check:"length_equals",...ae(e),length:t})}function Y3(t,e){return new mb({check:"string_format",format:"regex",...ae(e),pattern:t})}function Q3(t){return new gb({check:"string_format",format:"lowercase",...ae(t)})}function X3(t){return new yb({check:"string_format",format:"uppercase",...ae(t)})}function e9(t,e){return new _b({check:"string_format",format:"includes",...ae(e),includes:t})}function t9(t,e){return new vb({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function r9(t,e){return new wb({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function qs(t){return new bb({check:"overwrite",tx:t})}function n9(t){return qs(e=>e.normalize(t))}function s9(){return qs(t=>t.trim())}function o9(){return qs(t=>t.toLowerCase())}function a9(){return qs(t=>t.toUpperCase())}function i9(t,e,r){return new t({type:"array",element:e,...ae(r)})}function c9(t,e,r){const n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function l9(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}class Hf{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??js,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,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)i.ref=h,this.process(h,p),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(s.type){case"string":{const f=d;f.type="string";const{minimum:v,maximum:g,format:w,patterns:y,contentEncoding:_}=e._zod.bag;if(typeof v=="number"&&(f.minLength=v),typeof g=="number"&&(f.maxLength=g),w&&(f.format=o[w]??w,f.format===""&&delete f.format),_&&(f.contentEncoding=_),y&&y.size>0){const b=[...y];b.length===1?f.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const f=d,{minimum:v,maximum:g,format:w,multipleOf:y,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof w=="string"&&w.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof v=="number"&&(f.minimum=v,typeof b=="number"&&(b>=v?delete f.minimum:delete f.exclusiveMinimum)),typeof _=="number"&&(f.exclusiveMaximum=_),typeof g=="number"&&(f.maximum=g,typeof _=="number"&&(_<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof y=="number"&&(f.multipleOf=y);break}case"boolean":{const f=d;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.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":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=d,{minimum:v,maximum:g}=e._zod.bag;typeof v=="number"&&(f.minItems=v),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const f=d;f.type="object",f.properties={};const v=s.shape;for(const y in v)f.properties[y]=this.process(v[y],{...p,path:[...p.path,"properties",y]});const g=new Set(Object.keys(v)),w=new Set([...g].filter(y=>{const _=s.shape[y]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));w.size>0&&(f.required=Array.from(w)),s.catchall?._zod.def.type==="never"?f.additionalProperties=!1:s.catchall?s.catchall&&(f.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=d;f.anyOf=s.options.map((v,g)=>this.process(v,{...p,path:[...p.path,"anyOf",g]}));break}case"intersection":{const f=d,v=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),g=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),w=_=>"allOf"in _&&Object.keys(_).length===1,y=[...w(v)?v.allOf:[v],...w(g)?g.allOf:[g]];f.allOf=y;break}case"tuple":{const f=d;f.type="array";const v=s.items.map((y,_)=>this.process(y,{...p,path:[...p.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?f.prefixItems=v:f.items=v,s.rest){const y=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?f.items=y:f.additionalItems=y}s.rest&&(f.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:g,maximum:w}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof w=="number"&&(f.maxItems=w);break}case"record":{const f=d;f.type="object",f.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),f.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 f=d,v=cf(s.entries);v.every(g=>typeof g=="number")&&(f.type="number"),v.every(g=>typeof g=="string")&&(f.type="string"),f.enum=v;break}case"literal":{const f=d,v=[];for(const g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(g))}else v.push(g);if(v.length!==0)if(v.length===1){const g=v[0];f.type=g===null?"null":typeof g,f.const=g}else v.every(g=>typeof g=="number")&&(f.type="number"),v.every(g=>typeof g=="string")&&(f.type="string"),v.every(g=>typeof g=="boolean")&&(f.type="string"),v.every(g=>g===null)&&(f.type="null"),f.enum=v;break}case"file":{const f=d,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:w,mime:y}=e._zod.bag;g!==void 0&&(v.minLength=g),w!==void 0&&(v.maxLength=w),y?y.length===1?(v.contentMediaType=y[0],Object.assign(f,v)):f.anyOf=y.map(_=>({...v,contentMediaType:_})):Object.assign(f,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(s.innerType,p);d.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"success":{const f=d;f.type="boolean";break}case"default":{this.process(s.innerType,p),i.ref=s.innerType,d.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),i.ref=s.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),i.ref=s.innerType;let f;try{f=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=d,v=e._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=v.source;break}case"pipe":{const f=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(f,p),i.ref=f;break}case"readonly":{this.process(s.innerType,p),i.ref=s.innerType,d.readOnly=!0;break}case"promise":{this.process(s.innerType,p),i.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"lazy":{const f=e._zod.innerType;this.process(f,p),i.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const l=this.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),this.io==="input"&&Qe(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.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 o=u=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,g=n.external.uri??(y=>y);if(v)return{ref:g(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${g("__shared")}#/${p}/${w}`}}if(u[1]===s)return{ref:"#"};const d=`#/${p}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:d+f}},a=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:h,defId:d}=o(u);p.def={...p.schema},d&&(p.defId=d);const f=p.schema;for(const v in f)delete f[v];f.$ref=h};if(n.cycles==="throw")for(const u of this.seen.entries()){const p=u[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 u of this.seen.entries()){const p=u[1];if(e===u[0]){a(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(p.cycle){a(u);continue}if(p.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,p)=>{const h=this.seen.get(u),d=h.def??h.schema,f={...d};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){i(v,p);const g=this.seen.get(v).schema;g.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(g)):(Object.assign(d,g),Object.assign(d,f))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[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 u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,s.def);const l=n.external?.defs??{};for(const u of this.seen.entries()){const p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function yc(t,e){if(t instanceof Lf){const n=new Hf(e),s={};for(const i of t._idmap.entries()){const[c,l]=i;n.process(l)}const o={},a={registry:t,uri:e?.uri,defs:s};for(const i of t._idmap.entries()){const[c,l]=i;o[c]=n.emit(l,{...e,external:a})}if(Object.keys(s).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:s}}return{schemas:o}}const r=new Hf(e);return r.process(t),r.emit(t,e)}function Qe(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 Qe(s.element,r);case"object":{for(const o in s.shape)if(Qe(s.shape[o],r))return!0;return!1}case"union":{for(const o of s.options)if(Qe(o,r))return!0;return!1}case"intersection":return Qe(s.left,r)||Qe(s.right,r);case"tuple":{for(const o of s.items)if(Qe(o,r))return!0;return!!(s.rest&&Qe(s.rest,r))}case"record":return Qe(s.keyType,r)||Qe(s.valueType,r);case"map":return Qe(s.keyType,r)||Qe(s.valueType,r);case"set":return Qe(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Qe(s.innerType,r);case"lazy":return Qe(s.getter(),r);case"default":return Qe(s.innerType,r);case"prefault":return Qe(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Qe(s.in,r)||Qe(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const u9=J("ZodISODateTime",(t,e)=>{Nb.init(t,e),We.init(t,e)});function Bf(t){return z3(u9,t)}const d9=J("ZodISODate",(t,e)=>{Lb.init(t,e),We.init(t,e)});function p9(t){return D3(d9,t)}const f9=J("ZodISOTime",(t,e)=>{jb.init(t,e),We.init(t,e)});function h9(t){return U3(f9,t)}const m9=J("ZodISODuration",(t,e)=>{qb.init(t,e),We.init(t,e)});function g9(t){return Z3(m9,t)}const Ma=J("ZodError",(t,e)=>{df.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Aw(t,r)},flatten:{value:r=>Ow(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}),y9=pf(Ma),_9=ff(Ma),v9=hf(Ma),_c=mf(Ma),He=J("ZodType",(t,e)=>(Ze.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)=>Ur(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>y9(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>v9(t,r,n),t.parseAsync=async(r,n)=>_9(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_c(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(l4(r,n)),t.superRefine=r=>t.check(u4(r)),t.overwrite=r=>t.check(qs(r)),t.optional=()=>le(t),t.nullable=()=>nh(t),t.nullish=()=>le(nh(t)),t.nonoptional=r=>t4(t,r),t.array=()=>M(t),t.or=r=>ie([t,r]),t.and=r=>bc(t,r),t.transform=r=>Sc(t,th(r)),t.default=r=>Q9(t,r),t.prefault=r=>e4(t,r),t.catch=r=>n4(t,r),t.pipe=r=>Sc(t,r),t.readonly=()=>a4(t),t.describe=r=>{const n=t.clone();return js.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return js.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return js.get(t);const n=t.clone();return js.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Jf=J("_ZodString",(t,e)=>{fc.init(t,e),He.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(Y3(...n)),t.includes=(...n)=>t.check(e9(...n)),t.startsWith=(...n)=>t.check(t9(...n)),t.endsWith=(...n)=>t.check(r9(...n)),t.min=(...n)=>t.check(Aa(...n)),t.max=(...n)=>t.check(Ff(...n)),t.length=(...n)=>t.check(Vf(...n)),t.nonempty=(...n)=>t.check(Aa(1,...n)),t.lowercase=n=>t.check(Q3(n)),t.uppercase=n=>t.check(X3(n)),t.trim=()=>t.check(s9()),t.normalize=(...n)=>t.check(n9(...n)),t.toLowerCase=()=>t.check(o9()),t.toUpperCase=()=>t.check(a9())}),w9=J("ZodString",(t,e)=>{fc.init(t,e),Jf.init(t,e),t.email=r=>t.check(w3(b9,r)),t.url=r=>t.check(qf(Wf,r)),t.jwt=r=>t.check(q3(L9,r)),t.emoji=r=>t.check(C3(S9,r)),t.guid=r=>t.check(jf(Gf,r)),t.uuid=r=>t.check(b3(Na,r)),t.uuidv4=r=>t.check(k3(Na,r)),t.uuidv6=r=>t.check(S3(Na,r)),t.uuidv7=r=>t.check(T3(Na,r)),t.nanoid=r=>t.check($3(T9,r)),t.guid=r=>t.check(jf(Gf,r)),t.cuid=r=>t.check(E3(C9,r)),t.cuid2=r=>t.check(x3($9,r)),t.ulid=r=>t.check(I3(E9,r)),t.base64=r=>t.check(zf(Kf,r)),t.base64url=r=>t.check(L3(M9,r)),t.xid=r=>t.check(R3(x9,r)),t.ksuid=r=>t.check(P3(I9,r)),t.ipv4=r=>t.check(O3(R9,r)),t.ipv6=r=>t.check(A3(P9,r)),t.cidrv4=r=>t.check(M3(O9,r)),t.cidrv6=r=>t.check(N3(A9,r)),t.e164=r=>t.check(j3(N9,r)),t.datetime=r=>t.check(Bf(r)),t.date=r=>t.check(p9(r)),t.time=r=>t.check(h9(r)),t.duration=r=>t.check(g9(r))});function m(t){return v3(w9,t)}const We=J("ZodStringFormat",(t,e)=>{Je.init(t,e),Jf.init(t,e)}),b9=J("ZodEmail",(t,e)=>{$b.init(t,e),We.init(t,e)}),Gf=J("ZodGUID",(t,e)=>{Tb.init(t,e),We.init(t,e)}),Na=J("ZodUUID",(t,e)=>{Cb.init(t,e),We.init(t,e)}),Wf=J("ZodURL",(t,e)=>{Eb.init(t,e),We.init(t,e)});function k9(t){return qf(Wf,t)}const S9=J("ZodEmoji",(t,e)=>{xb.init(t,e),We.init(t,e)}),T9=J("ZodNanoID",(t,e)=>{Ib.init(t,e),We.init(t,e)}),C9=J("ZodCUID",(t,e)=>{Rb.init(t,e),We.init(t,e)}),$9=J("ZodCUID2",(t,e)=>{Pb.init(t,e),We.init(t,e)}),E9=J("ZodULID",(t,e)=>{Ob.init(t,e),We.init(t,e)}),x9=J("ZodXID",(t,e)=>{Ab.init(t,e),We.init(t,e)}),I9=J("ZodKSUID",(t,e)=>{Mb.init(t,e),We.init(t,e)}),R9=J("ZodIPv4",(t,e)=>{zb.init(t,e),We.init(t,e)}),P9=J("ZodIPv6",(t,e)=>{Db.init(t,e),We.init(t,e)}),O9=J("ZodCIDRv4",(t,e)=>{Ub.init(t,e),We.init(t,e)}),A9=J("ZodCIDRv6",(t,e)=>{Zb.init(t,e),We.init(t,e)}),Kf=J("ZodBase64",(t,e)=>{Fb.init(t,e),We.init(t,e)});function Yf(t){return zf(Kf,t)}const M9=J("ZodBase64URL",(t,e)=>{Hb.init(t,e),We.init(t,e)}),N9=J("ZodE164",(t,e)=>{Bb.init(t,e),We.init(t,e)}),L9=J("ZodJWT",(t,e)=>{Gb.init(t,e),We.init(t,e)}),vc=J("ZodNumber",(t,e)=>{Tf.init(t,e),He.init(t,e),t.gt=(n,s)=>t.check(Uf(n,s)),t.gte=(n,s)=>t.check(gc(n,s)),t.min=(n,s)=>t.check(gc(n,s)),t.lt=(n,s)=>t.check(Df(n,s)),t.lte=(n,s)=>t.check(mc(n,s)),t.max=(n,s)=>t.check(mc(n,s)),t.int=n=>t.check(Qf(n)),t.safe=n=>t.check(Qf(n)),t.positive=n=>t.check(Uf(0,n)),t.nonnegative=n=>t.check(gc(0,n)),t.negative=n=>t.check(Df(0,n)),t.nonpositive=n=>t.check(mc(0,n)),t.multipleOf=(n,s)=>t.check(Zf(n,s)),t.step=(n,s)=>t.check(Zf(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 N(t){return F3(vc,t)}const j9=J("ZodNumberFormat",(t,e)=>{Wb.init(t,e),vc.init(t,e)});function Qf(t){return H3(j9,t)}const q9=J("ZodBoolean",(t,e)=>{Kb.init(t,e),He.init(t,e)});function me(t){return B3(q9,t)}const z9=J("ZodNull",(t,e)=>{Yb.init(t,e),He.init(t,e)});function wc(t){return J3(z9,t)}const D9=J("ZodAny",(t,e)=>{Qb.init(t,e),He.init(t,e)});function ht(){return G3(D9)}const U9=J("ZodUnknown",(t,e)=>{Xb.init(t,e),He.init(t,e)});function Pe(){return W3(U9)}const Z9=J("ZodNever",(t,e)=>{e3.init(t,e),He.init(t,e)});function F9(t){return K3(Z9,t)}const V9=J("ZodArray",(t,e)=>{t3.init(t,e),He.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Aa(r,n)),t.nonempty=r=>t.check(Aa(1,r)),t.max=(r,n)=>t.check(Ff(r,n)),t.length=(r,n)=>t.check(Vf(r,n)),t.unwrap=()=>t.element});function M(t,e){return i9(V9,t,e)}const Xf=J("ZodObject",(t,e)=>{Ef.init(t,e),He.init(t,e),Me(t,"shape",()=>e.shape),t.keyof=()=>xe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:F9()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>xw(t,r),t.merge=r=>Iw(t,r),t.pick=r=>$w(t,r),t.omit=r=>Ew(t,r),t.partial=(...r)=>Rw(rh,t,r[0]),t.required=(...r)=>Pw(sh,t,r[0])});function C(t,e){const r={type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},...ae(e)};return new Xf(r)}function Ke(t,e){return new Xf({type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},catchall:Pe(),...ae(e)})}const eh=J("ZodUnion",(t,e)=>{If.init(t,e),He.init(t,e),t.options=e.options});function ie(t,e){return new eh({type:"union",options:t,...ae(e)})}const H9=J("ZodDiscriminatedUnion",(t,e)=>{eh.init(t,e),r3.init(t,e)});function Xe(t,e,r){return new H9({type:"union",options:e,discriminator:t,...ae(r)})}const B9=J("ZodIntersection",(t,e)=>{n3.init(t,e),He.init(t,e)});function bc(t,e){return new B9({type:"intersection",left:t,right:e})}const J9=J("ZodRecord",(t,e)=>{s3.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new J9({type:"record",keyType:t,valueType:e,...ae(r)})}const kc=J("ZodEnum",(t,e)=>{o3.init(t,e),He.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 o={};for(const a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new kc({...e,checks:[],...ae(s),entries:o})},t.exclude=(n,s)=>{const o={...e.entries};for(const a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new kc({...e,checks:[],...ae(s),entries:o})}});function xe(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new kc({type:"enum",entries:r,...ae(e)})}const G9=J("ZodLiteral",(t,e)=>{a3.init(t,e),He.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 L(t,e){return new G9({type:"literal",values:Array.isArray(t)?t:[t],...ae(e)})}const W9=J("ZodTransform",(t,e)=>{i3.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ls(o,r.value,e));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Ls(a))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function th(t){return new W9({type:"transform",transform:t})}const rh=J("ZodOptional",(t,e)=>{c3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function le(t){return new rh({type:"optional",innerType:t})}const K9=J("ZodNullable",(t,e)=>{l3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function nh(t){return new K9({type:"nullable",innerType:t})}const Y9=J("ZodDefault",(t,e)=>{u3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Q9(t,e){return new Y9({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const X9=J("ZodPrefault",(t,e)=>{d3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function e4(t,e){return new X9({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const sh=J("ZodNonOptional",(t,e)=>{p3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function t4(t,e){return new sh({type:"nonoptional",innerType:t,...ae(e)})}const r4=J("ZodCatch",(t,e)=>{f3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function n4(t,e){return new r4({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const s4=J("ZodPipe",(t,e)=>{h3.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});function Sc(t,e){return new s4({type:"pipe",in:t,out:e})}const o4=J("ZodReadonly",(t,e)=>{m3.init(t,e),He.init(t,e)});function a4(t){return new o4({type:"readonly",innerType:t})}const i4=J("ZodLazy",(t,e)=>{g3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.getter()});function oh(t){return new i4({type:"lazy",getter:t})}const Tc=J("ZodCustom",(t,e)=>{y3.init(t,e),He.init(t,e)});function c4(t){const e=new kt({check:"custom"});return e._zod.check=t,e}function ah(t,e){return c9(Tc,t??(()=>!0),e)}function l4(t,e={}){return l9(Tc,t,e)}function u4(t){const e=c4(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ls(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(Ls(s))}},t(r.value,r)));return e}function La(t,e={error:`Input not instance of ${t.name}`}){const r=new Tc({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ae(e)});return r._zod.bag.Class=t,r}function ih(t,e){return Sc(th(t),e)}const ch={custom:"custom"};function lh(t){return V3(vc,t)}const zs="2025-11-25",uh=[zs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fn="io.modelcontextprotocol/related-task",ja="2.0",st=ah(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dh=ie([m(),N().int()]),ph=m();Ke({ttl:ie([N(),wc()]).optional(),pollInterval:N().optional()});const d4=C({ttl:N().optional()}),p4=C({taskId:m()}),Cc=Ke({progressToken:dh.optional(),[fn]:p4.optional()}),Rt=C({_meta:Cc.optional()}),Ds=Rt.extend({task:d4.optional()}),f4=t=>Ds.safeParse(t).success,ot=C({method:m(),params:Rt.loose().optional()}),jt=C({_meta:Cc.optional()}),qt=C({method:m(),params:jt.loose().optional()}),at=Ke({_meta:Cc.optional()}),qa=ie([m(),N().int()]),fh=C({jsonrpc:L(ja),id:qa,...ot.shape}).strict(),$c=t=>fh.safeParse(t).success,hh=C({jsonrpc:L(ja),...qt.shape}).strict(),h4=t=>hh.safeParse(t).success,Ec=C({jsonrpc:L(ja),id:qa,result:at}).strict(),Us=t=>Ec.safeParse(t).success;var oe;(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"})(oe||(oe={}));const xc=C({jsonrpc:L(ja),id:qa.optional(),error:C({code:N().int(),message:m(),data:Pe().optional()})}).strict(),m4=t=>xc.safeParse(t).success,Tr=ie([fh,hh,Ec,xc]);ie([Ec,xc]);const Fr=at.strict(),g4=jt.extend({requestId:qa.optional(),reason:m().optional()}),Ic=qt.extend({method:L("notifications/cancelled"),params:g4}),y4=C({src:m(),mimeType:m().optional(),sizes:M(m()).optional(),theme:xe(["light","dark"]).optional()}),Zs=C({icons:M(y4).optional()}),Nn=C({name:m(),title:m().optional()}),mh=Nn.extend({...Nn.shape,...Zs.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),_4=bc(C({applyDefaults:me().optional()}),be(m(),Pe())),v4=ih(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,bc(C({form:_4.optional(),url:st.optional()}),be(m(),Pe()).optional())),w4=Ke({list:st.optional(),cancel:st.optional(),requests:Ke({sampling:Ke({createMessage:st.optional()}).optional(),elicitation:Ke({create:st.optional()}).optional()}).optional()}),b4=Ke({list:st.optional(),cancel:st.optional(),requests:Ke({tools:Ke({call:st.optional()}).optional()}).optional()}),k4=C({experimental:be(m(),st).optional(),sampling:C({context:st.optional(),tools:st.optional()}).optional(),elicitation:v4.optional(),roots:C({listChanged:me().optional()}).optional(),tasks:w4.optional()}),S4=Rt.extend({protocolVersion:m(),capabilities:k4,clientInfo:mh}),gh=ot.extend({method:L("initialize"),params:S4}),T4=C({experimental:be(m(),st).optional(),logging:st.optional(),completions:st.optional(),prompts:C({listChanged:me().optional()}).optional(),resources:C({subscribe:me().optional(),listChanged:me().optional()}).optional(),tools:C({listChanged:me().optional()}).optional(),tasks:b4.optional()}),yh=at.extend({protocolVersion:m(),capabilities:T4,serverInfo:mh,instructions:m().optional()}),Rc=qt.extend({method:L("notifications/initialized"),params:jt.optional()}),C4=t=>Rc.safeParse(t).success,Pc=ot.extend({method:L("ping"),params:Rt.optional()}),$4=C({progress:N(),total:le(N()),message:le(m())}),E4=C({...jt.shape,...$4.shape,progressToken:dh}),Oc=qt.extend({method:L("notifications/progress"),params:E4}),x4=Rt.extend({cursor:ph.optional()}),Fs=ot.extend({params:x4.optional()}),Vs=at.extend({nextCursor:ph.optional()}),I4=xe(["working","input_required","completed","failed","cancelled"]),Hs=C({taskId:m(),status:I4,ttl:ie([N(),wc()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:le(N()),statusMessage:le(m())}),Ln=at.extend({task:Hs}),R4=jt.merge(Hs),za=qt.extend({method:L("notifications/tasks/status"),params:R4}),Ac=ot.extend({method:L("tasks/get"),params:Rt.extend({taskId:m()})}),Mc=at.merge(Hs),Nc=ot.extend({method:L("tasks/result"),params:Rt.extend({taskId:m()})});at.loose();const Lc=Fs.extend({method:L("tasks/list")}),jc=Vs.extend({tasks:M(Hs)}),qc=ot.extend({method:L("tasks/cancel"),params:Rt.extend({taskId:m()})}),P4=at.merge(Hs),_h=C({uri:m(),mimeType:le(m()),_meta:be(m(),Pe()).optional()}),vh=_h.extend({text:m()}),zc=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wh=_h.extend({blob:zc}),Bs=xe(["user","assistant"]),jn=C({audience:M(Bs).optional(),priority:N().min(0).max(1).optional(),lastModified:Bf({offset:!0}).optional()}),bh=C({...Nn.shape,...Zs.shape,uri:m(),description:le(m()),mimeType:le(m()),annotations:jn.optional(),_meta:le(Ke({}))}),O4=C({...Nn.shape,...Zs.shape,uriTemplate:m(),description:le(m()),mimeType:le(m()),annotations:jn.optional(),_meta:le(Ke({}))}),Da=Fs.extend({method:L("resources/list")}),kh=Vs.extend({resources:M(bh)}),Dc=Fs.extend({method:L("resources/templates/list")}),Sh=Vs.extend({resourceTemplates:M(O4)}),Uc=Rt.extend({uri:m()}),A4=Uc,Zc=ot.extend({method:L("resources/read"),params:A4}),Th=at.extend({contents:M(ie([vh,wh]))}),Fc=qt.extend({method:L("notifications/resources/list_changed"),params:jt.optional()}),M4=Uc,Ch=ot.extend({method:L("resources/subscribe"),params:M4}),N4=Uc,$h=ot.extend({method:L("resources/unsubscribe"),params:N4}),L4=jt.extend({uri:m()}),Eh=qt.extend({method:L("notifications/resources/updated"),params:L4}),j4=C({name:m(),description:le(m()),required:le(me())}),q4=C({...Nn.shape,...Zs.shape,description:le(m()),arguments:le(M(j4)),_meta:le(Ke({}))}),Vc=Fs.extend({method:L("prompts/list")}),xh=Vs.extend({prompts:M(q4)}),z4=Rt.extend({name:m(),arguments:be(m(),m()).optional()}),Hc=ot.extend({method:L("prompts/get"),params:z4}),Bc=C({type:L("text"),text:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),Jc=C({type:L("image"),data:zc,mimeType:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),Gc=C({type:L("audio"),data:zc,mimeType:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),D4=C({type:L("tool_use"),name:m(),id:m(),input:be(m(),Pe()),_meta:be(m(),Pe()).optional()}),U4=C({type:L("resource"),resource:ie([vh,wh]),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),Z4=bh.extend({type:L("resource_link")}),Wc=ie([Bc,Jc,Gc,Z4,U4]),F4=C({role:Bs,content:Wc}),Ih=at.extend({description:m().optional(),messages:M(F4)}),Kc=qt.extend({method:L("notifications/prompts/list_changed"),params:jt.optional()}),V4=C({title:m().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),H4=C({taskSupport:xe(["required","optional","forbidden"]).optional()}),Rh=C({...Nn.shape,...Zs.shape,description:m().optional(),inputSchema:C({type:L("object"),properties:be(m(),st).optional(),required:M(m()).optional()}).catchall(Pe()),outputSchema:C({type:L("object"),properties:be(m(),st).optional(),required:M(m()).optional()}).catchall(Pe()).optional(),annotations:V4.optional(),execution:H4.optional(),_meta:be(m(),Pe()).optional()}),Yc=Fs.extend({method:L("tools/list")}),Ph=Vs.extend({tools:M(Rh)}),qn=at.extend({content:M(Wc).default([]),structuredContent:be(m(),Pe()).optional(),isError:me().optional()});qn.or(at.extend({toolResult:Pe()}));const B4=Ds.extend({name:m(),arguments:be(m(),Pe()).optional()}),Ua=ot.extend({method:L("tools/call"),params:B4}),Qc=qt.extend({method:L("notifications/tools/list_changed"),params:jt.optional()}),J4=C({autoRefresh:me().default(!0),debounceMs:N().int().nonnegative().default(300)}),Za=xe(["debug","info","notice","warning","error","critical","alert","emergency"]),G4=Rt.extend({level:Za}),Fa=ot.extend({method:L("logging/setLevel"),params:G4}),W4=jt.extend({level:Za,logger:m().optional(),data:Pe()}),Oh=qt.extend({method:L("notifications/message"),params:W4}),K4=C({name:m().optional()}),Y4=C({hints:M(K4).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),Q4=C({mode:xe(["auto","required","none"]).optional()}),X4=C({type:L("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:M(Wc).default([]),structuredContent:C({}).loose().optional(),isError:me().optional(),_meta:be(m(),Pe()).optional()}),ek=Xe("type",[Bc,Jc,Gc]),Va=Xe("type",[Bc,Jc,Gc,D4,X4]),tk=C({role:Bs,content:ie([Va,M(Va)]),_meta:be(m(),Pe()).optional()}),rk=Ds.extend({messages:M(tk),modelPreferences:Y4.optional(),systemPrompt:m().optional(),includeContext:xe(["none","thisServer","allServers"]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:M(m()).optional(),metadata:st.optional(),tools:M(Rh).optional(),toolChoice:Q4.optional()}),Xc=ot.extend({method:L("sampling/createMessage"),params:rk}),Ha=at.extend({model:m(),stopReason:le(xe(["endTurn","stopSequence","maxTokens"]).or(m())),role:Bs,content:ek}),el=at.extend({model:m(),stopReason:le(xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:Bs,content:ie([Va,M(Va)])}),nk=C({type:L("boolean"),title:m().optional(),description:m().optional(),default:me().optional()}),sk=C({type:L("string"),title:m().optional(),description:m().optional(),minLength:N().optional(),maxLength:N().optional(),format:xe(["email","uri","date","date-time"]).optional(),default:m().optional()}),ok=C({type:xe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),ak=C({type:L("string"),title:m().optional(),description:m().optional(),enum:M(m()),default:m().optional()}),ik=C({type:L("string"),title:m().optional(),description:m().optional(),oneOf:M(C({const:m(),title:m()})),default:m().optional()}),ck=C({type:L("string"),title:m().optional(),description:m().optional(),enum:M(m()),enumNames:M(m()).optional(),default:m().optional()}),lk=ie([ak,ik]),uk=C({type:L("array"),title:m().optional(),description:m().optional(),minItems:N().optional(),maxItems:N().optional(),items:C({type:L("string"),enum:M(m())}),default:M(m()).optional()}),dk=C({type:L("array"),title:m().optional(),description:m().optional(),minItems:N().optional(),maxItems:N().optional(),items:C({anyOf:M(C({const:m(),title:m()}))}),default:M(m()).optional()}),pk=ie([uk,dk]),fk=ie([ck,lk,pk]),hk=ie([fk,nk,sk,ok]),mk=Ds.extend({mode:L("form").optional(),message:m(),requestedSchema:C({type:L("object"),properties:be(m(),hk),required:M(m()).optional()})}),gk=Ds.extend({mode:L("url"),message:m(),elicitationId:m(),url:m().url()}),yk=ie([mk,gk]),tl=ot.extend({method:L("elicitation/create"),params:yk}),_k=jt.extend({elicitationId:m()}),vk=qt.extend({method:L("notifications/elicitation/complete"),params:_k}),Js=at.extend({action:xe(["accept","decline","cancel"]),content:ih(t=>t===null?void 0:t,be(m(),ie([m(),N(),me(),M(m())])).optional())}),wk=C({type:L("ref/resource"),uri:m()}),bk=C({type:L("ref/prompt"),name:m()}),kk=Rt.extend({ref:ie([bk,wk]),argument:C({name:m(),value:m()}),context:C({arguments:be(m(),m()).optional()}).optional()}),rl=ot.extend({method:L("completion/complete"),params:kk});function Sk(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Tk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const Ah=at.extend({completion:Ke({values:M(m()).max(100),total:le(N().int()),hasMore:le(me())})}),Ck=C({uri:m().startsWith("file://"),name:m().optional(),_meta:be(m(),Pe()).optional()}),Mh=ot.extend({method:L("roots/list"),params:Rt.optional()}),nl=at.extend({roots:M(Ck)}),Nh=qt.extend({method:L("notifications/roots/list_changed"),params:jt.optional()});ie([Pc,gh,rl,Fa,Hc,Vc,Da,Dc,Zc,Ch,$h,Ua,Yc,Ac,Nc,Lc,qc]),ie([Ic,Oc,Rc,Nh,za]),ie([Fr,Ha,el,Js,nl,Mc,jc,Ln]),ie([Pc,Xc,tl,Mh,Ac,Nc,Lc,qc]),ie([Ic,Oc,Oh,Eh,Fc,Qc,Kc,za,vk]),ie([Fr,yh,Ah,Ih,xh,kh,Sh,Th,qn,Ph,Mc,jc,Ln]);class re 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===oe.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new $k(s.elicitations,r)}return new re(e,r,n)}}class $k extends re{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}const Ek=J("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ze.init(t,e),t.def=e,t.parse=(r,n)=>Mw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>dc(t,r,n),t.parseAsync=async(r,n)=>Nw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>pc(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)=>Ur(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),xk=J("ZodMiniObject",(t,e)=>{Ef.init(t,e),Ek.init(t,e),Me(t,"shape",()=>e.shape)});function Lh(t,e){const r={type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},...ae(e)};return new xk(r)}function Jt(t){return!!t._zod}function zn(t){const e=Object.values(t);if(e.length===0)return Lh({});const r=e.every(Jt),n=e.every(s=>!Jt(s));if(r)return Lh(t);if(n)return nf(t);throw new Error("Mixed Zod versions detected in object shape.")}function Gt(t,e){return Jt(t)?dc(t,e):t.safeParse(e)}async function sl(t,e){return Jt(t)?await pc(t,e):await t.safeParseAsync(e)}function Dn(t){if(!t)return;let e;if(Jt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Gs(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 zn(t)}}if(Jt(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 ol(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 Ik(t){return t.description}function Rk(t){if(Jt(t))return t._zod?.def?.type==="optional";const e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function jh(t){if(Jt(t)){const o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 hn(t){return t==="completed"||t==="failed"||t==="cancelled"}const Pk=Symbol("Let zodToJsonSchema decide on which parser to use"),qh={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"},Ok=t=>typeof t=="string"?{...qh,name:t}:{...qh,...t},Ak=t=>{const e=Ok(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 zh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,s){t[e]=r,zh(t,e,n,s)}const Dh=(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 St(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Dh(e,t.currentPath):e.join("/")}}function Mk(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(r.items=Ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Nk(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?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function Lk(){return{type:"boolean"}}function Uh(t,e){return Ne(t.type._def,e)}const jk=(t,e)=>Ne(t.innerType._def,e);function Zh(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Zh(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 qk(t,e)}}const qk=(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":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function zk(t,e){return{...Ne(t.innerType._def,e),default:t.defaultValue()}}function Dk(t,e){return e.effectStrategy==="input"?Ne(t.schema._def,e):St(e)}function Uk(t){return{type:"string",enum:Array.from(t.values)}}const Zk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Fk(t,e){const r=[Ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ne(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(o=>{if(Zk(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...c}=o;a=c}else n=void 0;s.push(a)}}),s.length?{allOf:s,...n}:void 0}function Vk(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 al;const Wt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(al===void 0&&(al=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),al),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 Fh(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(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":Kt(r,"email",n.message,e);break;case"format:idn-email":Kt(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,Wt.email,n.message,e);break}break;case"url":Kt(r,"uri",n.message,e);break;case"uuid":Kt(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,Wt.cuid,n.message,e);break;case"cuid2":mt(r,Wt.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${il(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${il(n.value,e)}$`),n.message,e);break;case"datetime":Kt(r,"date-time",n.message,e);break;case"date":Kt(r,"date",n.message,e);break;case"time":Kt(r,"time",n.message,e);break;case"duration":Kt(r,"duration",n.message,e);break;case"length":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(il(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Kt(r,"ipv4",n.message,e),n.version!=="v4"&&Kt(r,"ipv6",n.message,e);break}case"base64url":mt(r,Wt.base64url,n.message,e);break;case"jwt":mt(r,Wt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,Wt.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,Wt.ipv6Cidr,n.message,e);break}case"emoji":mt(r,Wt.emoji(),n.message,e);break;case"ulid":{mt(r,Wt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Kt(r,"binary",n.message,e);break}case"contentEncoding:base64":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,Wt.base64,n.message,e);break}}break}case"nanoid":mt(r,Wt.nanoid,n.message,e)}return r}function il(t,e){return e.patternStrategy==="escape"?Bk(t):t}const Hk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Bk(t){let e="";for(let r=0;r<t.length;r++)Hk.has(t[r])||(e+="\\"),e+=t[r];return e}function Kt(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}}})):qe(t,"format",e,r,n)}function mt(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:Vh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",Vh(e,n),r,n)}function Vh(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="",o=!1,a=!1,i=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){i?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),i=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],i=!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+=a?`${n[c]}\r
38
- `:`[${n[c]}\r
39
- ]`;continue}s+=n[c],n[c]==="\\"?o=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!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 Hh(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===z.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??St(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===z.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=Fh(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===z.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=Uh(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function Jk(t,e){if(e.mapStrategy==="record")return Hh(t,e);const r=Ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||St(e),n=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||St(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Gk(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Wk(t){return t.target==="openAi"?void 0:{not:St({...t,currentPath:[...t.currentPath,"not"]})}}function Kk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ba={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yk(t,e){if(e.target==="openApi3")return Bh(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ba&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ba[o._def.typeName];return a&&!s.includes(a)?[...s,a]: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,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Bh(t,e)}const Bh=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ne(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 Qk(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:Ba[t.innerType._def.typeName],nullable:!0}:{type:[Ba[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Xk(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",zh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function e6(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(const i in o){let c=o[i];if(c===void 0||c._def===void 0)continue;let l=r6(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Ne(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,l||s.push(i))}s.length&&(n.required=s);const a=t6(t,e);return a!==void 0&&(n.additionalProperties=a),n}function t6(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ne(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 r6(t){try{return t.isOptional()}catch{return!0}}const n6=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Ne(t.innerType._def,e);const r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:St(e)},r]}:St(e)},s6=(t,e)=>{if(e.pipeStrategy==="input")return Ne(t.in._def,e);if(e.pipeStrategy==="output")return Ne(t.out._def,e);const r=Ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function o6(t,e){return Ne(t.type._def,e)}function a6(t,e){const n={type:"array",uniqueItems:!0,items:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&qe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&qe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function i6(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function c6(t){return{not:St(t)}}function l6(t){return St(t)}const u6=(t,e)=>Ne(t.innerType._def,e),d6=(t,e,r)=>{switch(e){case z.ZodString:return Fh(t,r);case z.ZodNumber:return Xk(t,r);case z.ZodObject:return e6(t,r);case z.ZodBigInt:return Nk(t,r);case z.ZodBoolean:return Lk();case z.ZodDate:return Zh(t,r);case z.ZodUndefined:return c6(r);case z.ZodNull:return Kk(r);case z.ZodArray:return Mk(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return Yk(t,r);case z.ZodIntersection:return Fk(t,r);case z.ZodTuple:return i6(t,r);case z.ZodRecord:return Hh(t,r);case z.ZodLiteral:return Vk(t,r);case z.ZodEnum:return Uk(t);case z.ZodNativeEnum:return Gk(t);case z.ZodNullable:return Qk(t,r);case z.ZodOptional:return n6(t,r);case z.ZodMap:return Jk(t,r);case z.ZodSet:return a6(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return o6(t,r);case z.ZodNaN:case z.ZodNever:return Wk(r);case z.ZodEffects:return Dk(t,r);case z.ZodAny:return St(r);case z.ZodUnknown:return l6(r);case z.ZodDefault:return zk(t,r);case z.ZodBranded:return Uh(t,r);case z.ZodReadonly:return u6(t,r);case z.ZodCatch:return jk(t,r);case z.ZodPipeline:return s6(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ne(t,e,r=!1){const n=e.seen.get(t);if(e.override){const i=e.override?.(t,e,n,r);if(i!==Pk)return i}if(n&&!r){const i=p6(n,e);if(i!==void 0)return i}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=d6(t,t.typeName,e),a=typeof o=="function"?Ne(o(),e):o;if(a&&f6(t,e,a),e.postProcess){const i=e.postProcess(a,t,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}const p6=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Dh(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`),St(e)):e.$refStrategy==="seen"?St(e):void 0}},f6=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),h6=(t,e)=>{const r=Ak(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Ne(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??St(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Ne(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??St(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),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 i=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function m6(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Jh(t,e){return Jt(t)?yc(t,{target:m6(e?.target),io:e?.pipeStrategy??"input"}):h6(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gh(t){const r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=jh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wh(t,e){const r=Gt(t,e);if(!r.success)throw r.error;return r.data}const g6=6e4;class Kh{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(Ic,r=>{this._oncancel(r)}),this.setNotificationHandler(Oc,r=>{this._onprogress(r)}),this.setRequestHandler(Pc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ac,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new re(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Nc,async(r,n)=>{const s=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(i.type==="response"||i.type==="error"){const c=i.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),i.type==="response")u(c);else{const p=c,h=new re(p.error.code,p.error.message,p.error.data);u(h)}else{const p=i.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new re(oe.InvalidParams,`Task not found: ${o}`);if(!hn(a.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(hn(a.status)){const i=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[fn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Lc,async(r,n)=>{try{const{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new re(oe.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(qc,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new re(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(hn(s.status))throw new re(oe.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 o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new re(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof re?s:new re(oe.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,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,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),re.fromError(oe.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=o=>{n?.(o),this._onerror(o)};const s=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{s?.(o,a),Us(o)||m4(o)?this._onresponse(o):$c(o)?this._onrequest(o,a):h4(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=re.fromError(oe.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,o=e.params?._meta?.[fn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:e.id,error:{code:oe.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):s?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const i=f4(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,l={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{const p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(u,p)},sendRequest:async(u,p,h)=>{const d={...h,relatedRequestId:e.id};o&&!d.relatedTask&&(d.relatedTask={taskId:o});const f=d.relatedTask?.taskId??o;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(a.signal.aborted)return;const p={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)},async u=>{if(a.signal.aborted)return;const p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:oe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(c);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Us(e))n(e);else{const a=new re(e.error.code,e.error.message,e.error.data);n(a)}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 o=!1;if(Us(e)&&e.result&&typeof e.result=="object"){const a=e.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,r))}}if(o||this._progressHandlers.delete(r),Us(e))s(e);else{const a=re.fromError(e.error.code,e.error.message,e.error.data);s(a)}}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(a){yield{type:"error",error:a instanceof re?a:new re(oe.InternalError,String(a))}}return}let o;try{const a=await this.request(e,Ln,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new re(oe.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:i},hn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:i.status==="failed"?yield{type:"error",error:new re(oe.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new re(oe.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}const c=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof re?a:new re(oe.InternalError,String(a))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:i,relatedTask:c}=n??{};return new Promise((l,u)=>{const p=y=>{u(y)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(y){p(y);return}n?.signal?.throwIfAborted();const h=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),i&&(d.params={...d.params,task:i}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[fn]:c}});const f=y=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(y)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));const _=y instanceof re?y:new re(oe.RequestTimeout,String(y));u(_)};this._responseHandlers.set(h,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return u(y);try{const _=Gt(r,y.result);_.success?l(_.data):u(_.error)}catch(_){u(_)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});const v=n?.timeout??g6,g=()=>f(re.fromError(oe.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(h,v,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);const w=c?.taskId;if(w){const y=_=>{const b=this._responseHandlers.get(h);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,y),this._enqueueTaskMessage(w,{type:"request",message:d,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(h),u(_)})}else this._transport.send(d,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(h),u(y)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Mc,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},jc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},P4,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 i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[fn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,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 i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[fn]:r.relatedTask}}}),this._transport?.send(i,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[fn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){const n=Gh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=Wh(e,s);return Promise.resolve(r(a,o))})}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=Gh(e);this._notificationHandlers.set(n,s=>{const o=Wh(e,s);return Promise.resolve(r(o))})}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"&&$c(s.message)){const o=s.message.id,a=this._requestResolvers.get(o);a?(a(new re(oe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} 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,o)=>{if(r.aborted){o(new re(oe.InvalidRequest,"Request cancelled"));return}const a=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new re(oe.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 o=await n.getTask(s,r);if(!o)throw new re(oe.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,r);const i=await n.getTask(s,r);if(i){const c=za.parse({method:"notifications/tasks/status",params:i});await this.notification(c),hn(i.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,a)=>{const i=await n.getTask(s,r);if(!i)throw new re(oe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(hn(i.status))throw new re(oe.InvalidParams,`Cannot update task "${s}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,r);const c=await n.getTask(s,r);if(c){const l=za.parse({method:"notifications/tasks/status",params:c});await this.notification(l),hn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function Yh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qh(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];Yh(a)&&Yh(o)?r[s]={...a,...o}:r[s]=o}return r}var Ja={exports:{}},cl={},Xh;function y6(){return Xh||(Xh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(O,D){return{validate:O,compare:D}}t.fullFormats={date:e(o,a),time:e(c(!0),l),"date-time":e(h(!0),d),"iso-time":e(c(),u),"iso-date-time":e(h(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"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:j,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:_,int32:{type:"number",validate:S},int64:{type:"number",validate:T},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"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,d),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"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,f),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(O){return O%4===0&&(O%100!==0||O%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 o(O){const D=n.exec(O);if(!D)return!1;const U=+D[1],V=+D[2],ne=+D[3];return V>=1&&V<=12&&ne>=1&&ne<=(V===2&&r(U)?29:s[V])}function a(O,D){if(O&&D)return O>D?1:O<D?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(O){return function(U){const V=i.exec(U);if(!V)return!1;const ne=+V[1],fe=+V[2],de=+V[3],te=V[4],ye=V[5]==="-"?-1:1,H=+(V[6]||0),P=+(V[7]||0);if(H>23||P>59||O&&!te)return!1;if(ne<=23&&fe<=59&&de<60)return!0;const F=fe-P*ye,q=ne-H*ye-(F<0?1:0);return(q===23||q===-1)&&(F===59||F===-1)&&de<61}}function l(O,D){if(!(O&&D))return;const U=new Date("2020-01-01T"+O).valueOf(),V=new Date("2020-01-01T"+D).valueOf();if(U&&V)return U-V}function u(O,D){if(!(O&&D))return;const U=i.exec(O),V=i.exec(D);if(U&&V)return O=U[1]+U[2]+U[3],D=V[1]+V[2]+V[3],O>D?1:O<D?-1:0}const p=/t|\s/i;function h(O){const D=c(O);return function(V){const ne=V.split(p);return ne.length===2&&o(ne[0])&&D(ne[1])}}function d(O,D){if(!(O&&D))return;const U=new Date(O).valueOf(),V=new Date(D).valueOf();if(U&&V)return U-V}function f(O,D){if(!(O&&D))return;const[U,V]=O.split(p),[ne,fe]=D.split(p),de=a(U,ne);if(de!==void 0)return de||l(V,fe)}const v=/\/|:/,g=/^(?:[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 w(O){return v.test(O)&&g.test(O)}const y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function _(O){return y.lastIndex=0,y.test(O)}const b=-2147483648,k=2**31-1;function S(O){return Number.isInteger(O)&&O<=k&&O>=b}function T(O){return Number.isInteger(O)}function x(){return!0}const R=/[^\\]\\Z/;function j(O){if(R.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(cl)),cl}var ll={},e0;function _6(){return e0||(e0=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=Zp(),r=Ce(),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}},o={message:({keyword:i,schemaCode:c})=>(0,r.str)`should be ${s[i].okStr} ${c}`,params:({keyword:i,schemaCode:c})=>(0,r._)`{comparison: ${s[i].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(i){const{gen:c,data:l,schemaCode:u,keyword:p,it:h}=i,{opts:d,self:f}=h;if(!d.validateFormats)return;const v=new e.KeywordCxt(h,f.RULES.all.format.definition,"format");v.$data?g():w();function g(){const _=c.scopeValue("formats",{ref:f.formats,code:d.code.formats}),b=c.const("fmt",(0,r._)`${_}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,y(b)))}function w(){const _=v.schema,b=f.formats[_];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${p}": format "${_}" does not define "compare" function`);const k=c.scopeValue("formats",{key:_,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(_)}`:void 0});i.fail$data(y(k))}function y(_){return(0,r._)`${_}.compare(${l}, ${u}) ${s[p].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(t.formatLimitDefinition),i);t.default=a})(ll)),ll}var t0;function v6(){return t0||(t0=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=y6(),n=_6(),s=Ce(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(l,u={keywords:!0})=>{if(Array.isArray(u))return c(l,u,r.fullFormats,o),l;const[p,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,o],d=u.formats||r.formatNames;return c(l,d,p,h),u.keywords&&(0,n.default)(l),l};i.get=(l,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[l];if(!h)throw new Error(`Unknown format "${l}"`);return h};function c(l,u,p,h){var d,f;(d=(f=l.opts.code).formats)!==null&&d!==void 0||(f.formats=(0,s._)`require("ajv-formats/dist/formats").${h}`);for(const v of u)l.addFormat(v,p[v])}t.exports=e=i,Object.defineProperty(e,"__esModule",{value:!0}),e.default=i})(Ja,Ja.exports)),Ja.exports}var w6=v6();const b6=rn(w6);function k6(){const t=new Fp({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return b6(t),t}class r0{constructor(e){this._ajv=e??k6()}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 S6{constructor(e){this._client=e}async*callToolStream(e,r=qn,n){const s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},a=s.requestStream({method:"tools/call",params:e},r,o),i=s.getToolOutputValidator(e.name);for await(const c of a){if(c.type==="result"&&i){const l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new re(oe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const u=i(l.structuredContent);if(!u.valid){yield{type:"error",error:new re(oe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof re){yield{type:"error",error:u};return}yield{type:"error",error:new re(oe.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};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 n0(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 s0(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 Ga(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 o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Ga(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)typeof r!="boolean"&&Ga(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)typeof r!="boolean"&&Ga(r,e)}}function T6(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 Ws extends Kh{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 r0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Qc,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Kc,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Fc,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new S6(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qh(this._capabilities,e)}setRequestHandler(e,r){const s=Dn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Jt(s)){const i=s;o=i._zod?.def?.value??i.value}else{const i=s;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const a=o;if(a==="elicitation/create"){const i=async(c,l)=>{const u=Gt(tl,c);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid elicitation request: ${y}`)}const{params:p}=u.data;p.mode=p.mode??"form";const{supportsFormMode:h,supportsUrlMode:d}=T6(this._capabilities.elicitation);if(p.mode==="form"&&!h)throw new re(oe.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!d)throw new re(oe.InvalidParams,"Client does not support URL-mode elicitation requests");const f=await Promise.resolve(r(c,l));if(p.task){const y=Gt(Ln,f);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const v=Gt(Js,f);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new re(oe.InvalidParams,`Invalid elicitation result: ${y}`)}const g=v.data,w=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&g.action==="accept"&&g.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ga(w,g.content)}catch{}return g};return super.setRequestHandler(e,i)}if(a==="sampling/createMessage"){const i=async(c,l)=>{const u=Gt(Xc,c);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid sampling request: ${g}`)}const{params:p}=u.data,h=await Promise.resolve(r(c,l));if(p.task){const g=Gt(Ln,h);if(!g.success){const w=g.error instanceof Error?g.error.message:String(g.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${w}`)}return g.data}const f=p.tools||p.toolChoice?el:Ha,v=Gt(f,h);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new re(oe.InvalidParams,`Invalid sampling result: ${g}`)}return v.data};return super.setRequestHandler(e,i)}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:zs,capabilities:this._capabilities,clientInfo:this._clientInfo}},yh,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!uh.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){n0(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&s0(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Fr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ah,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Fr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Ih,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},xh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},kh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Sh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Th,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Fr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Fr,r)}async callTool(e,r=qn,n){if(this.isToolTaskRequired(e.name))throw new re(oe.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),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new re(oe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new re(oe.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof re?a:new re(oe.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}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},Ph,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){const o=J4.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=o.data,{onChanged:c}=n,l=async()=>{if(!a){c(null,null);return}try{const p=await s();c(null,p)}catch(p){const h=p instanceof Error?p:new Error(String(p));c(h,null)}},u=()=>{if(i){const p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);const h=setTimeout(l,i);this._listChangedDebounceTimers.set(e,h)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class o0 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 ul(t){}function a0(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=ul,onError:r=ul,onRetry:n=ul,onComment:s}=t;let o="",a=!0,i,c="",l="";function u(v){const g=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,y]=C6(`${o}${g}`);for(const _ of w)p(_);o=y,a=!1}function p(v){if(v===""){d();return}if(v.startsWith(":")){s&&s(v.slice(v.startsWith(": ")?2:1));return}const g=v.indexOf(":");if(g!==-1){const w=v.slice(0,g),y=v[g+1]===" "?2:1,_=v.slice(g+y);h(w,_,v);return}h(v,"",v)}function h(v,g,w){switch(v){case"event":l=g;break;case"data":c=`${c}${g}
40
- `;break;case"id":i=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new o0(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:w}));break;default:r(new o0(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:g,line:w}));break}}function d(){c.length>0&&e({id:i,event:l||void 0,data:c.endsWith(`
41
- `)?c.slice(0,-1):c}),i=void 0,c="",l=""}function f(v={}){o&&v.consume&&p(o),a=!0,i=void 0,c="",l="",o=""}return{feed:u,reset:f}}function C6(t){const e=[];let r="",n=0;for(;n<t.length;){const s=t.indexOf("\r",n),o=t.indexOf(`
42
- `,n);let a=-1;if(s!==-1&&o!==-1?a=Math.min(s,o):s!==-1?s===t.length-1?a=-1:a=s:o!==-1&&(a=o),a===-1){r=t.slice(n);break}else{const i=t.slice(n,a);e.push(i),n=a+1,t[n-1]==="\r"&&t[n]===`
43
- `&&n++}}return[e,r]}class i0 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(c0(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(c0(this),r)}}function $6(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function dl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(dl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${dl(t.cause)}`:t.message:`${t}`}function c0(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var l0=t=>{throw TypeError(t)},pl=(t,e,r)=>e.has(t)||l0("Cannot "+r),Ie=(t,e,r)=>(pl(t,e,"read from private field"),r?r.call(t):e.get(t)),et=(t,e,r)=>e.has(t)?l0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ge=(t,e,r,n)=>(pl(t,e,"write to private field"),e.set(t,r),r),Cr=(t,e,r)=>(pl(t,e,"access private method"),r),Tt,mn,Un,Wa,Ka,Ks,Zn,Ys,Vr,Fn,Vn,Hn,Qs,Yt,fl,hl,ml,u0,gl,yl,Xs,_l,vl;class Ya extends EventTarget{constructor(e,r){var n,s;super(),et(this,Yt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,et(this,Tt),et(this,mn),et(this,Un),et(this,Wa),et(this,Ka),et(this,Ks),et(this,Zn),et(this,Ys,null),et(this,Vr),et(this,Fn),et(this,Vn,null),et(this,Hn,null),et(this,Qs,null),et(this,hl,async o=>{var a;Ie(this,Fn).reset();const{body:i,redirected:c,status:l,headers:u}=o;if(l===204){Cr(this,Yt,Xs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Ge(this,Un,new URL(o.url)):Ge(this,Un,void 0),l!==200){Cr(this,Yt,Xs).call(this,`Non-200 status code (${l})`,l);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Cr(this,Yt,Xs).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(Ie(this,Tt)===this.CLOSED)return;Ge(this,Tt,this.OPEN);const p=new Event("open");if((a=Ie(this,Qs))==null||a.call(this,p),this.dispatchEvent(p),typeof i!="object"||!i||!("getReader"in i)){Cr(this,Yt,Xs).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const h=new TextDecoder,d=i.getReader();let f=!0;do{const{done:v,value:g}=await d.read();g&&Ie(this,Fn).feed(h.decode(g,{stream:!v})),v&&(f=!1,Ie(this,Fn).reset(),Cr(this,Yt,_l).call(this))}while(f)}),et(this,ml,o=>{Ge(this,Vr,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Cr(this,Yt,_l).call(this,dl(o))}),et(this,gl,o=>{typeof o.id=="string"&&Ge(this,Ys,o.id);const a=new MessageEvent(o.event||"message",{data:o.data,origin:Ie(this,Un)?Ie(this,Un).origin:Ie(this,mn).origin,lastEventId:o.id||""});Ie(this,Hn)&&(!o.event||o.event==="message")&&Ie(this,Hn).call(this,a),this.dispatchEvent(a)}),et(this,yl,o=>{Ge(this,Ks,o)}),et(this,vl,()=>{Ge(this,Zn,void 0),Ie(this,Tt)===this.CONNECTING&&Cr(this,Yt,fl).call(this)});try{if(e instanceof URL)Ge(this,mn,e);else if(typeof e=="string")Ge(this,mn,new URL(e,E6()));else throw new Error("Invalid URL")}catch{throw $6("An invalid or illegal string was specified")}Ge(this,Fn,a0({onEvent:Ie(this,gl),onRetry:Ie(this,yl)})),Ge(this,Tt,this.CONNECTING),Ge(this,Ks,3e3),Ge(this,Ka,(n=r?.fetch)!=null?n:globalThis.fetch),Ge(this,Wa,(s=r?.withCredentials)!=null?s:!1),Cr(this,Yt,fl).call(this)}get readyState(){return Ie(this,Tt)}get url(){return Ie(this,mn).href}get withCredentials(){return Ie(this,Wa)}get onerror(){return Ie(this,Vn)}set onerror(e){Ge(this,Vn,e)}get onmessage(){return Ie(this,Hn)}set onmessage(e){Ge(this,Hn,e)}get onopen(){return Ie(this,Qs)}set onopen(e){Ge(this,Qs,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(){Ie(this,Zn)&&clearTimeout(Ie(this,Zn)),Ie(this,Tt)!==this.CLOSED&&(Ie(this,Vr)&&Ie(this,Vr).abort(),Ge(this,Tt,this.CLOSED),Ge(this,Vr,void 0))}}Tt=new WeakMap,mn=new WeakMap,Un=new WeakMap,Wa=new WeakMap,Ka=new WeakMap,Ks=new WeakMap,Zn=new WeakMap,Ys=new WeakMap,Vr=new WeakMap,Fn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Qs=new WeakMap,Yt=new WeakSet,fl=function(){Ge(this,Tt,this.CONNECTING),Ge(this,Vr,new AbortController),Ie(this,Ka)(Ie(this,mn),Cr(this,Yt,u0).call(this)).then(Ie(this,hl)).catch(Ie(this,ml))},hl=new WeakMap,ml=new WeakMap,u0=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ie(this,Ys)?{"Last-Event-ID":Ie(this,Ys)}:void 0},cache:"no-store",signal:(t=Ie(this,Vr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},gl=new WeakMap,yl=new WeakMap,Xs=function(t,e){var r;Ie(this,Tt)!==this.CLOSED&&Ge(this,Tt,this.CLOSED);const n=new i0("error",{code:e,message:t});(r=Ie(this,Vn))==null||r.call(this,n),this.dispatchEvent(n)},_l=function(t,e){var r;if(Ie(this,Tt)===this.CLOSED)return;Ge(this,Tt,this.CONNECTING);const n=new i0("error",{code:e,message:t});(r=Ie(this,Vn))==null||r.call(this,n),this.dispatchEvent(n),Ge(this,Zn,setTimeout(Ie(this,vl),Ie(this,Ks)))},vl=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function E6(){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 Qa(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function d0(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Qa(e.headers),...Qa(n.headers)}:e.headers};return t(r,s)}:t}let wl;wl=globalThis.crypto;async function x6(t){return(await wl).getRandomValues(new Uint8Array(t))}async function I6(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await x6(t-n.length);for(const o of s)o<r&&(n+=e[o%e.length])}return n}async function R6(t){return await I6(t)}async function P6(t){const e=await(await wl).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function p0(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await R6(t),r=await P6(e);return{code_verifier:e,code_challenge:r}}const it=k9().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:ch.custom,message:"URL must be parseable",fatal:!0}),of}).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"}),O6=Ke({resource:m().url(),authorization_servers:M(it).optional(),jwks_uri:m().url().optional(),scopes_supported:M(m()).optional(),bearer_methods_supported:M(m()).optional(),resource_signing_alg_values_supported:M(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:M(m()).optional(),dpop_signing_alg_values_supported:M(m()).optional(),dpop_bound_access_tokens_required:me().optional()}),f0=Ke({issuer:m(),authorization_endpoint:it,token_endpoint:it,registration_endpoint:it.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),response_modes_supported:M(m()).optional(),grant_types_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional(),service_documentation:it.optional(),revocation_endpoint:it.optional(),revocation_endpoint_auth_methods_supported:M(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:M(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:M(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:M(m()).optional(),code_challenge_methods_supported:M(m()).optional(),client_id_metadata_document_supported:me().optional()}),A6=Ke({issuer:m(),authorization_endpoint:it,token_endpoint:it,userinfo_endpoint:it.optional(),jwks_uri:it,registration_endpoint:it.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),response_modes_supported:M(m()).optional(),grant_types_supported:M(m()).optional(),acr_values_supported:M(m()).optional(),subject_types_supported:M(m()),id_token_signing_alg_values_supported:M(m()),id_token_encryption_alg_values_supported:M(m()).optional(),id_token_encryption_enc_values_supported:M(m()).optional(),userinfo_signing_alg_values_supported:M(m()).optional(),userinfo_encryption_alg_values_supported:M(m()).optional(),userinfo_encryption_enc_values_supported:M(m()).optional(),request_object_signing_alg_values_supported:M(m()).optional(),request_object_encryption_alg_values_supported:M(m()).optional(),request_object_encryption_enc_values_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional(),display_values_supported:M(m()).optional(),claim_types_supported:M(m()).optional(),claims_supported:M(m()).optional(),service_documentation:m().optional(),claims_locales_supported:M(m()).optional(),ui_locales_supported:M(m()).optional(),claims_parameter_supported:me().optional(),request_parameter_supported:me().optional(),request_uri_parameter_supported:me().optional(),require_request_uri_registration:me().optional(),op_policy_uri:it.optional(),op_tos_uri:it.optional(),client_id_metadata_document_supported:me().optional()}),M6=C({...A6.shape,...f0.pick({code_challenge_methods_supported:!0}).shape}),N6=C({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:lh().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),L6=C({error:m(),error_description:m().optional(),error_uri:m().optional()}),h0=it.optional().or(L("").transform(()=>{})),j6=C({redirect_uris:M(it),token_endpoint_auth_method:m().optional(),grant_types:M(m()).optional(),response_types:M(m()).optional(),client_name:m().optional(),client_uri:it.optional(),logo_uri:h0,scope:m().optional(),contacts:M(m()).optional(),tos_uri:h0,policy_uri:m().optional(),jwks_uri:it.optional(),jwks:ht().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),q6=C({client_id:m(),client_secret:m().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),z6=j6.merge(q6);C({error:m(),error_description:m().optional()}).strip(),C({token:m(),token_type_hint:m().optional()}).strip();function D6(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function U6({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+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}class tt 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 bl extends tt{}bl.errorCode="invalid_request";let Xa=class extends tt{};Xa.errorCode="invalid_client";let ei=class extends tt{};ei.errorCode="invalid_grant";let ti=class extends tt{};ti.errorCode="unauthorized_client";class kl extends tt{}kl.errorCode="unsupported_grant_type";class Sl extends tt{}Sl.errorCode="invalid_scope";class Tl extends tt{}Tl.errorCode="access_denied";let Bn=class extends tt{};Bn.errorCode="server_error";class Cl extends tt{}Cl.errorCode="temporarily_unavailable";class $l extends tt{}$l.errorCode="unsupported_response_type";class El extends tt{}El.errorCode="unsupported_token_type";class xl extends tt{}xl.errorCode="invalid_token";class Il extends tt{}Il.errorCode="method_not_allowed";class Rl extends tt{}Rl.errorCode="too_many_requests";class ri extends tt{}ri.errorCode="invalid_client_metadata";class Pl extends tt{}Pl.errorCode="insufficient_scope";class Ol extends tt{}Ol.errorCode="invalid_target";const Z6={[bl.errorCode]:bl,[Xa.errorCode]:Xa,[ei.errorCode]:ei,[ti.errorCode]:ti,[kl.errorCode]:kl,[Sl.errorCode]:Sl,[Tl.errorCode]:Tl,[Bn.errorCode]:Bn,[Cl.errorCode]:Cl,[$l.errorCode]:$l,[El.errorCode]:El,[xl.errorCode]:xl,[Il.errorCode]:Il,[Rl.errorCode]:Rl,[ri.errorCode]:ri,[Pl.errorCode]:Pl,[Ol.errorCode]:Ol};let zt=class extends Error{constructor(e){super(e??"Unauthorized")}};function F6(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const Al="code",Ml="S256";function V6(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&&F6(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 H6(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":B6(s,o,r);return;case"client_secret_post":J6(s,o,n);return;case"none":G6(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function B6(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 J6(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function G6(t,e){e.set("client_id",t)}async function m0(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=L6.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=Z6[s]||Bn;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Bn(s)}}async function gn(t,e){try{return await Nl(t,e)}catch(r){if(r instanceof Xa||r instanceof ti)return await t.invalidateCredentials?.("all"),await Nl(t,e);if(r instanceof ei)return await t.invalidateCredentials?.("tokens"),await Nl(t,e);throw r}}async function Nl(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await Y6(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",e));const c=await K6(e,t,a),l=await rS(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const g=l?.client_id_metadata_document_supported===!0,w=t.clientMetadataUrl;if(w&&!W6(w))throw new ri(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(g&&w)u={client_id:w},await t.saveClientInformation?.(u);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const _=await iS(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(_),u=_}}const p=!t.redirectUrl;if(r!==void 0||p){const g=await aS(t,i,{metadata:l,resource:c,authorizationCode:r,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}const h=await t.tokens();if(h?.refresh_token)try{const g=await oS(i,{metadata:l,clientInformation:u,refreshToken:h.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof tt)||g instanceof Bn))throw g}const d=t.state?await t.state():void 0,{authorizationUrl:f,codeVerifier:v}=await nS(i,{metadata:l,clientInformation:u,state:d,redirectUrl:t.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(v),await t.redirectToAuthorization(f),"REDIRECT"}function W6(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function K6(t,e,r){const n=D6(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!U6({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 ni(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=Ll(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=Ll(t,"scope")||void 0,i=Ll(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function Ll(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}async function Y6(t,e,r=fetch){const n=await eS(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 O6.parse(await n.json())}async function jl(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?jl(t,void 0,r):void 0;throw n}}function Q6(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function g0(t,e,r=fetch){return await jl(t,{"MCP-Protocol-Version":e},r)}function X6(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function eS(t,e,r,n){const s=new URL(t),o=n?.protocolVersion??zs;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const c=Q6(e,s.pathname);a=new URL(c,n?.metadataServerUrl??s),a.search=s.search}let i=await g0(a,o,r);if(!n?.metadataUrl&&X6(i,s.pathname)){const c=new URL(`/.well-known/${e}`,s);i=await g0(c,o,r)}return i}function tS(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 rS(t,{fetchFn:e=fetch,protocolVersion:r=zs}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=tS(t);for(const{url:o,type:a}of s){const i=await jl(o,n,e);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?f0.parse(await i.json()):M6.parse(await i.json())}}}async function nS(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Al))throw new Error(`Incompatible auth server: does not support response type ${Al}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ml))throw new Error(`Incompatible auth server: does not support code challenge method ${Ml}`)}else i=new URL("/authorize",t);const c=await p0(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",Al),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Ml),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}function sS(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function y0(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:a}){const i=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(o&&r.set("resource",o.href),s)await s(c,r,i,e);else if(n){const u=e?.token_endpoint_auth_methods_supported??[],p=V6(n,u);H6(p,n,c,r)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!l.ok)throw await m0(l);return N6.parse(await l.json())}async function oS(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await y0(t,{metadata:e,tokenRequestParams:i,clientInformation:r,addClientAuthentication:o,resource:s,fetchFn:a});return{refresh_token:n,...c}}async function aS(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:o}={}){const a=t.clientMetadata.scope;let i;if(t.prepareTokenRequest&&(i=await t.prepareTokenRequest(a)),!i){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 l=await t.codeVerifier();i=sS(s,l,t.redirectUrl)}const c=await t.clientInformation();return y0(e,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function iS(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 o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await m0(o);return z6.parse(await o.json())}class cS extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class eo{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=d0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let e;try{e=await gn(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 zt;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=Qa(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 Ya(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await e(s,{...o,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:c,scope:l}=ni(i);this._resourceMetadataUrl=c,this._scope=l}return i}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{if(s.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const o=new cS(s.code,s.message,s);n(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{const o=s;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=s=>{const o=s;let a;try{a=Tr.parse(JSON.parse(o.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}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 zt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("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 o=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=ni(s);if(this._resourceMetadataUrl=a,this._scope=i,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}}class Jn extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(o){s=a0({onEvent:a=>{o.enqueue(a)},onError(a){e==="terminate"?o.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}const lS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Gn extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class to{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=d0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??lS}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let e;try{e=await gn(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 zt;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=Qa(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 Gn(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(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1,c=!1;(async()=>{try{const u=e.pipeThrough(new TextDecoderStream).pipeThrough(new Jn({onRetry:d=>{this._serverRetryMs=d}})).getReader();for(;;){const{value:d,done:f}=await u.read();if(f)break;if(d.id&&(a=d.id,i=!0,s?.(d.id)),!!d.data&&(!d.event||d.event==="message"))try{const v=Tr.parse(JSON.parse(d.data));Us(v)&&(c=!0,o!==void 0&&(v.id=o)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(d){this.onerror?.(new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}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 zt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("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:$c(e)?e.id:void 0}).catch(h=>this.onerror?.(h));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const h=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Gn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:d,scope:f}=ni(i);if(this._resourceMetadataUrl=d,this._scope=f,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:d,scope:f,error:v}=ni(i);if(v==="insufficient_scope"){const g=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Gn(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),d&&(this._resourceMetadataUrl=d),this._lastUpscopingHeader=g??void 0,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(e)}}throw new Gn(i.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),C4(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}const u=(Array.isArray(e)?e:[e]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,p=i.headers.get("content-type");if(u)if(p?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:s},!1);else if(p?.includes("application/json")){const h=await i.json(),d=Array.isArray(h)?h.map(f=>Tr.parse(f)):[Tr.parse(h)];for(const f of d)this.onmessage?.(f)}else throw await i.body?.cancel(),new Gn(-1,`Unexpected content type: ${p}`);else await i.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 Gn(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})}}const uS="mcp";class _0{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,uS),this._socket.onerror=n=>{const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),this.onerror?.(s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let s;try{s=Tr.parse(JSON.parse(n.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(s)}})}async close(){this._socket?.close()}send(e){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),r()})}}const Hr=Pt;(function(t,e){const r=Pt,n=Pt,s=t();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(si,-118057+3521*-35+-2099*-233);const v0=()=>{const t=Pt,e=Pt,r={};r[t(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[e(394)]=e(414),r.ktWqD=function(a,i){return a!==i},r[t(424)]=t(391);const n=r,s=n[e(420)].split("|");let o=859*2+-3*-1039+-4835*1;for(;;){switch(s[o++]){case"0":if(n[e(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[e(405)](typeof global,"undefined"))return global;continue;case"3":if(n[e(405)](typeof globalThis,n[t(394)]))return globalThis;continue;case"4":return Function(n[t(424)])()}break}},dS=(t,e,r)=>{const n=Pt,s=Pt,o={};o.eOzBp=function(i,c){return i!==c},o.ooaJk="undefined",o[n(402)]=function(i,c){return i===c},o[n(421)]="function";const a=o;a[s(389)](typeof window,a.ooaJk)?t[s(423)](e,"*",r):n(423)in t&&a.pTvSc(typeof t[s(423)],a[n(421)])&&t.postMessage(e,r)},pS=(t,e)=>{const r=Pt,n=Pt,s={};s.nTCfA=function(a,i){return a in i},s[r(390)]="addEventListener",s[r(385)]=function(a,i){return a===i},s[r(409)]="function",s.VaHpd=n(392),s[n(384)]=r(417),s.FPOYW=function(a,i){return a!==i};const o=s;o.nTCfA(o.ogKey,t)&&o[n(385)](typeof t.addEventListener,o[n(409)])?t[n(386)](o.VaHpd,e):o[n(384)]in t&&o[r(398)](typeof t[n(417)],r(414))&&(t.onmessage=e)};class ro{constructor(e){this._port=e}async[Hr(401)](){const e=Hr,r=Hr;this[e(422)]&&(this[r(422)].onmessage=n=>{var s,o;const a=e;try{const i=Tr.parse(n.data.message);(s=this.onmessage)==null||s.call(this,i,n[a(412)][a(428)])}catch(i){const c=new Error("MessageChannel failed to parse message: "+i);(o=this[a(383)])==null||o.call(this,c)}},this._port.onmessageerror=n=>{var s;const o=r,a=new Error("MessageChannel transport error: "+JSON[o(415)](n));(s=this.onerror)==null||s.call(this,a)},this[r(422)].start())}async send(e,r){const n={EoBZE:function(s){return s()},leEiG:function(s,o){return s instanceof o},cDUwk:function(s,o){return s(o)}};return new Promise((s,o)=>{var a;const i=Pt,c=Pt;try{const l={};l[i(404)]=r?.[i(404)];const u={};u[i(392)]=e,u.extra=l,this._port&&this._port[c(423)](u),n[i(399)](s)}catch(l){const u=n.leEiG(l,Error)?l:new Error(n.cDUwk(String,l));(a=this.onerror)==null||a.call(this,u),o(u)}})}async close(){var e,r;const n=Hr,s=Hr;(e=this._port)==null||e[n(393)](),this[n(422)]=void 0,(r=this[s(408)])==null||r.call(this)}}class ql extends ro{constructor(e,r=v0()){const n=Hr,s={lSpBh:function(a,i,c,l){return a(i,c,l)}};super(),this._endpoint=e,this._globalObject=r;const o=new MessageChannel;this._port=o[n(410)],s[n(418)](dS,this._globalObject,{endpoint:this[n(397)]},[o[n(429)]])}}class zl extends ro{constructor(e,r=v0()){const n=Hr,s=Hr,o={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,c){return a(i,c)}};super(),this[n(397)]=e,this[s(388)]=r,this[s(416)]=new Promise(a=>{const i=n,c={XlglK:function(l,u){return o.HITdC(l,u)},pXlad:function(l){return o.QdDxM(l)}};o[i(427)](pS,this._globalObject,l=>{const u=i,p=i;l[u(412)]&&c.XlglK(l.data[p(396)],this._endpoint)&&(this[u(422)]=l[p(430)][-3036+-1518*-2],c.pXlad(a))})})}async listen(){return this._listen}}function si(){const t=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return si=function(){return t},si()}function Pt(t,e){const r=si();return Pt=function(n,s){return n=n-(17227+1*-16844),r[n]},Pt(t,e)}const fS=()=>{const t=new MessageChannel;return[new ro(t.port1),new ro(t.port2)]};(function(t,e){const r=Fe,n=Fe,s=t();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(oi,-411935*1+228107+208149*2);const hS=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[s(475)]=s(411),a.SoCaE="resources/templates/list",a[o(484)]="resources/read",a[s(461)]="prompts/get",a.srIIC=o(477),a[o(436)]=o(478),a[o(442)]=s(437),a.dEmVs=s(465);const i=a,{id:c,method:l,params:u}=r;let p={};switch(l){case i.VRyiJ:p=await e.listTools(u);break;case i.VkPYu:p=await e.callTool(u);break;case i.fgMSD:p=await e.listResources(u);break;case i[o(466)]:p=await e.listResourceTemplates(u);break;case i.sthgI:p=await e[s(455)](u);break;case o(486):p=await e.subscribeResource(u);break;case s(410):p=await e.unsubscribeResource(u);break;case i[o(461)]:p=await e[o(414)](u);break;case i[s(412)]:p=await e[s(491)](u);break;case i[s(436)]:p=await e[s(478)]();break;case i.kkNqg:p=await e.complete(u);break;case s(464):p=await e.setLoggingLevel(u?.[o(443)]);break}const h={};h.result=p,h.jsonrpc=i[o(472)],h.id=c,await((n=t?.[o(488)])==null?void 0:n[s(460)](h))},mS=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a[s(487)]=o(462),a.ypHTC="ping",a.fPExS=s(465);const i=a,{id:c,method:l,params:u}=r;let p={};switch(l){case"roots/list":const d={};d.method=l,d[o(446)]=u,p=await e[s(469)](d,nl);break;case"sampling/createMessage":const f={};f[s(481)]=l,f[s(446)]=u,p=await e.request(f,Ha);break;case i[s(487)]:const v={};v.method=l,v[o(446)]=u,p=await e.request(v,Js);break;case i.ypHTC:const g={};g.method=l,p=await e.request(g,Fr);break}const h={};return h.result=p,h.jsonrpc=i.fPExS,h.id=c,await((n=t?.transport)==null?void 0:n.send(h)),p};function Fe(t,e){const r=oi();return Fe=function(n,s){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Fe(t,e)}const gS=(t,e)=>{const r=Fe,n=Fe,s={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,c,l){return a(i,c,l)},yfZbw:"2.0"},o=t._onrequest;t[n(463)]=async(a,i)=>{var c,l,u,p,h;const d=n,f=r,{id:v,method:g}=a;try{s[d(451)](g,s.DhPFX)?await o.call(t,a,i):await s[f(474)](hS,t,e,a)}catch(w){const{code:y,message:_,data:b}=w;try{if(y){const k={};k[f(485)]=y,k[d(422)]=_,k.data=b;const S={};S[f(448)]=k,S.jsonrpc=s[d(417)],S.id=v,await((c=t?.transport)==null?void 0:c[f(460)](S))}else(u=(l=t?.transport)==null?void 0:l.onerror)==null||u.call(l,w)}catch(k){(h=(p=t?.transport)==null?void 0:p.onerror)==null||h.call(p,k)}}}},yS=(t,e)=>{const r=Fe,n=Fe,s={};s[r(476)]=r(439),s[r(431)]=function(a,i){return a!==i},s.UPdQt="notifications/cancelled";const o=s;t[r(421)]=async a=>{var i,c;const l=r,u=n,{method:p,params:h}=a;if(p!==o[l(476)]&&(o.QWYMz(p,o.UPdQt)||h?.[u(490)]))try{await e[l(445)](a)}catch(d){(c=(i=t?.[l(488)])==null?void 0:i[l(480)])==null||c.call(i,d)}}},_S=(t,e)=>async r=>{var n,s,o,a,i;const c=Fe,l=Fe,u={TJhyV:function(p,h,d,f){return p(h,d,f)},MMNTY:c(465)};try{return await u.TJhyV(mS,t,e,r)}catch(p){const{code:h,message:d,data:f}=p;try{if(h){const v={};v.code=h,v[c(422)]=d,v[l(419)]=f;const g={};g[c(448)]=v,g[c(424)]=u.MMNTY,g.id=r.id,await((n=t?.transport)==null?void 0:n[l(460)](g))}else(o=(s=t?.transport)==null?void 0:s[c(480)])==null||o.call(s,p)}catch(v){(i=(a=t?.[c(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},vS=(t,e)=>async r=>{var n,s,o;const a=Fe,i=Fe,c={};c.xmcLM=function(h,d){return h!==d},c.xSWLt="notifications/initialized",c[a(420)]=i(453);const l=c,{method:u,params:p}=r;if(l.xmcLM(u,l.xSWLt)&&(l.xmcLM(u,l[i(420)])||p?.[i(490)]))try{const h={...r};h.jsonrpc=a(465),await((n=e?.[a(488)])==null?void 0:n.send(h))}catch(h){(o=(s=t?.transport)==null?void 0:s.onerror)==null||o.call(s,h)}};function oi(){const t=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return oi=function(){return t},oi()}const wS=(t,e)=>async r=>{var n,s,o,a,i,c;const l=Fe,u=Fe,p={};p.kSvAZ=l(465);const h=p;try{await((n=e?.[u(488)])==null?void 0:n[u(460)](r))}catch(d){const{code:f,message:v,data:g}=d;try{if(f){const w={};w.code=f,w.message=v,w.data=g;const y={};y.error=w,y[u(424)]=h.kSvAZ,y.id=r.id,await((s=t?.transport)==null?void 0:s.send(y))}else(a=(o=t?.transport)==null?void 0:o[l(480)])==null||a.call(o,d)}catch(w){(c=(i=t?.[l(488)])==null?void 0:i[u(480)])==null||c.call(i,w)}}},Dl=()=>{const t=Fe,e={rgPZO:function(c,l){return c!==l},VWsxO:function(c,l){return c(l)},FjTAY:"function"},r=[],n=(c,l)=>{const u=Fe;if(l){const p=[];for(const h of r)try{p.push(h(c,l))}catch{}for(const h of p)if(e.rgPZO(h,null))return h}else for(const p of r)try{e[u(427)](p,c)}catch{}},s=c=>{const l=Fe,u=Fe;typeof c===e[l(456)]&&!r.includes(c)&&r[u(471)](c)},o=c=>{const l=Fe,u=r[l(415)](c);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const c=Fe;r[c(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[t(447)]=s,i.removeListener=o,i.clearListener=a,i},bS=t=>{const e=Fe,r=Fe,n={UlqiY:function(s){return s()},jsmFN:function(s){return s()}};{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(423)](Dl);t._onresponse=s,t[r(438)]=o,t.removeResponseListener=a,t.clearResponseListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(489)](Dl);t[e(432)]=s,t[r(473)]=o,t.removeRequestListener=a,t.clearRequestListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n.jsmFN(Dl);t.fallbackNotificationHandler=s,t[e(444)]=o,t.removeNotificationListener=a,t[r(426)]=i}},kS=(t,{beforeInit:e,afterInit:r}={})=>{const n=Fe,s=Fe,o={HucXo:function(i,c){return i===c},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,c){return i(c)},UynHf:function(i,c){return i===c},yCyFn:function(i){return i()}},a=new Map(t._notificationHandlers);t[n(454)].clear(),t._notificationHandlers.clear(),o.HucXo(typeof e,o.HicFO)&&o[n(435)](e),o[n(467)](t[n(449)][s(428)],n(449))&&(t[s(413)]=t[s(449)]),o.DclXr(bS,t),t[s(438)](i=>{const c=n;t.originalOnResponse[c(440)](t,i)}),o[n(429)](typeof r,o.HicFO)&&o[s(425)](r),t[s(444)](i=>{const c=s,{method:l}=i,u=a[c(483)](l);o[c(467)](typeof u,"function")&&u(i)})},SS=$r;(function(t,e){const r=$r,n=$r,s=t();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ai,995159+-6*-266138+-1619768);const TS=()=>{const t=$r,e=$r,r={};r.svuxn=function(s,o){return s&o},r.ZUPdr=function(s,o){return s===o},r[t(227)]=function(s,o){return s===o},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[e(227)](typeof crypto,"object")&&crypto[t(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,s=>{const o=t,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[o(225)](s,"x")?a:n[o(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},CS=t=>{const e=$r,r=$r,n=new Uint8Array(t);return crypto[e(221)](n),Array[r(218)](n,s=>s[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[e(213)]("")},Br={};Br[SS(211)]=TS,Br.randomBytes=CS;function $r(t,e){const r=ai();return $r=function(n,s){return n=n-(-7373+7187*1+395),r[n]},$r(t,e)}function ai(){const t=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return ai=function(){return t},ai()}function Er(t,e){const r=ii();return Er=function(n,s){return n=n-(-1483*3+-5564+20*513),r[n]},Er(t,e)}const Qt=Er,no=Er;(function(t,e){const r=Er,n=Er,s=t();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ii,-4*308317+753182*2+658196);const $S=(t,e)=>{const r=Er,n=Er,s={olCWX:function(c,l,u){return c(l,u)},sfXDX:function(c,l,u){return c(l,u)},ksWFu:function(c,l,u){return c(l,u)}};s[r(283)](gS,t,e),yS(t,e);const o=s[n(283)](_S,e,t),a=s[n(294)](wS,e,t),i=s[r(277)](vS,e,t);e.addRequestListener(o),e.addResponseListener(a),e[n(287)](i),t.onclose=()=>{const c=r,l=n;e[c(247)](o),e.removeResponseListener(a),e[l(252)](i)}},Ul=(t,e,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,c){return a(i,c)}},s=()=>{var a;n.QhPqi(r,eo)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Er(295)])==null||i.close()})),n.Qalmc($S,t,e)},o={};o.afterInit=s,n.Qalmc(kS,e,o)},w0=(t,e=Br[Qt(299)]())=>{const r=Qt,n=Qt,s={RVabx:function(u,p,h){return u(p,h)},crCTs:"include"},o={};o["sse-session-id"]=e;const a=o,i={};i["sse-session-id"]=e;const c={};c.headers=i,c.credentials=s[r(304)];const l={requestInit:c,eventSourceInit:{async fetch(u,p){const h=r,d=r,f=new Headers(p?.[h(268)]||{});Object.entries(a).forEach(([g,w])=>{f.set(g,w)});const v={...p};return v.headers=f,s[d(279)](fetch,u,v)},withCredentials:!0}};return t&&(l[r(280)].headers.Authorization="Bearer "+t,a.Authorization=n(256)+t),l},b0=(t,e=Br[Qt(299)]())=>{const r=no,n=Qt,s={};s[r(271)]="include";const o=s,a={};a["stream-session-id"]=e;const i={};i[n(268)]=a,i.credentials=o[r(271)];const c={};c.requestInit=i;const l=c;return t&&(l[n(280)][r(268)][n(301)]=r(256)+t),l},Zl=async(t,e,r)=>{const n=Qt,s=Qt,o={rRtFD:function(i){return i()},ToRAF:function(i,c){return i instanceof c}},a=o[n(276)](r);try{return await t[s(260)](a),a}catch(i){if(o[n(275)](i,zt)){const c=await e();return await a[n(257)](c),await Zl(t,e,r)}else throw i}},k0=(t,e)=>{const r=no,n=no,s={};s[r(267)]=function(a,i){return a in i},s.timcZ="waitForOAuthCode",s[r(253)]=function(a,i){return a===i},s.ufiEQ=r(285),s[n(250)]=r(293);const o=s;if(o.oGmBG(o[r(258)],t))return t[n(278)];if(o[n(253)](typeof e,o.ufiEQ))return e;throw new Error(o.daYBw)};function ii(){const t=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return ii=function(){return t},ii()}const ES=async t=>{const e=no,r=Qt,n={GKDjq:function(R,j,O){return R(j,O)},JzpWy:e(281),mcbiU:"1.0.0",CfBXU:function(R){return R()},kdowC:function(R,j,O,D){return R(j,O,D)},KkViY:"sessionId"},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,eventSourceInit:u,waitForOAuthCode:p}=t,h={};h[r(305)]=c,h.requestInit=l,h.eventSourceInit=u;const d=h,f=i||Br[r(299)](),v=n[e(289)](w0,a,f);if(l){const R={...v.requestInit,...l};R[r(268)]={...v[r(280)][e(268)],...l.headers},d.requestInit=R}else d.requestInit=v[e(280)];if(u){const R={...v[e(270)],...u};d.eventSourceInit=R}else d.eventSourceInit=v[e(270)];const g={};g[e(254)]=!0;const w={};w.roots=g,w[e(298)]={},w[r(303)]={};const y=w,_={};_.name=n[r(261)],_[e(288)]=n.mcbiU;const b={};b[e(251)]=y;const k=new Ws(_,b),S=()=>new eo(new URL(o),d);let T=n[e(282)](S);if(c){const R=k0(c,p);T=await n[e(263)](Zl,k,R,S)}else await k.connect(T);Ul(k,s,T),T.sessionId=T[r(274)].searchParams[e(297)](n.KkViY);const x={};return x.transport=T,x.sessionId=T[r(286)],x},xS=async t=>{const e=no,r=Qt,n={wfHUn:function(R,j,O){return R(j,O)},tUMle:"mcp-stream-proxy-client",omKPe:e(248),rSiEq:function(R){return R()},PdsSn:function(R,j,O,D){return R(j,O,D)}},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,reconnectionOptions:u,waitForOAuthCode:p}=t,h={};h.authProvider=c,h.requestInit=l,h.reconnectionOptions=u;const d=h,f=i||Br.randomUUID(),v=n[r(272)](b0,a,f);if(l){const R={...v[e(280)],...l};R.headers={...v.requestInit[e(268)],...l.headers},d.requestInit=R}else d[r(280)]=v[r(280)];const g={};g[r(254)]=!0;const w={};w.roots=g,w[e(298)]={},w[e(303)]={};const y=w,_={};_.name=n[e(262)],_.version=n.omKPe;const b={};b.capabilities=y;const k=new Ws(_,b),S=()=>new to(new URL(o),d);let T=n.rSiEq(S);if(c){const R=n[e(272)](k0,c,p);T=await n[e(296)](Zl,k,R,S)}else await k[e(260)](T);n.PdsSn(Ul,k,s,T);const x={};return x.transport=T,x[r(286)]=T[r(286)],x},IS=async t=>{const e=Qt,r=Qt,n={eZwNI:function(w,y,_,b){return w(y,_,b)}},{client:s,url:o,token:a,sessionId:i}=t,c={};c[e(254)]=!0;const l={};l[r(290)]=c,l.sampling={},l.elicitation={};const u=l,p={};p.name="mcp-socket-proxy-client",p.version=r(248);const h={};h[r(251)]=u;const d=new Ws(p,h),f=i||Br[r(299)](),v=new _0(new URL(o+"?sessionId="+f+r(265)+a));await d.connect(v),n[e(259)](Ul,d,s,v);const g={};return g.transport=v,g[r(286)]=f,g},Jr=Xt,so=Xt;(function(t,e){const r=Xt,n=Xt,s=t();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ci,1297719+-42747*-22+-1289197);function Xt(t,e){const r=ci();return Xt=function(n,s){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Xt(t,e)}const RS=()=>Br.randomBytes(-8746+-382*-23);class PS{constructor(e){const r=Xt,n=Xt,s={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:o,state:a,redirectCallback:i,getAuthCodeByState:c,waitForOAuthCode:l}=e;this._clientMetadata=o,this[r(206)]=o.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||s.HbwOh(RS),this._redirectCallback=i||this[n(202)],this[n(195)]=c||this[r(191)],this.waitForOAuthCode=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,n,s,o,a,i;const c=Xt,l=Xt,u={};u[c(198)]="GET";const p=await fetch(e,u);!p.ok&&((n=(r=this[l(207)])[l(196)])==null||n.call(r,c(208)+p[l(205)]));const h=await this[l(195)](this._redirectUrl,this[c(197)]);if(!h.ok){(o=(s=this[c(207)]).reject)==null||o.call(s,"Failed to fetch auth code: "+h[l(205)]);return}const d=await h.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,d.code)}async[Jr(191)](e,r){const n=Jr,s={};s.xAOmI="POST";const o=s,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(e,{method:o.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const e=this._callBackPromise;return()=>new Promise((r,n)=>{const s=Xt;e.resolve=r,e[s(196)]=n})}get redirectUrl(){return this[Jr(206)]}get[so(190)](){return this._clientMetadata}[Jr(213)](){return this[Jr(197)]}[so(218)](){return this[so(200)]}[Jr(194)](e){this._clientInformation=e}tokens(){return this[so(210)]}saveTokens(e){const r=so;this[r(210)]=e}redirectToAuthorization(e){this._redirectCallback(e)}saveCodeVerifier(e){this._codeVerifier=e}[Jr(212)](){const e=Jr,r={};r[e(215)]=e(214);const n=r;if(!this[e(209)])throw new Error(n.mMdVl);return this[e(209)]}}function ci(){const t=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return ci=function(){return t},ci()}(function(t,e){for(var r=ui,n=ui,s=t();;)try{var o=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(o===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(li,262*-2438+1346066*-1+2*1373311);function li(){var t=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return li=function(){return t},li()}function ui(t,e){var r=li();return ui=function(n,s){n=n-287;var o=r[n];return o},ui(t,e)}class OS{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 AS extends Kh{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Za.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{const o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new r0,this.setRequestHandler(gh,n=>this._oninitialize(n)),this.setNotificationHandler(Rc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fa,async(n,s)=>{const o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=Za.safeParse(a);return i.success&&this._loggingLevels.set(o,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new OS(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qh(this._capabilities,e)}setRequestHandler(e,r){const s=Dn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Jt(s)){const i=s;o=i._zod?.def?.value??i.value}else{const i=s;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){const i=async(c,l)=>{const u=Gt(Ua,c);if(!u.success){const f=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid tools/call request: ${f}`)}const{params:p}=u.data,h=await Promise.resolve(r(c,l));if(p.task){const f=Gt(Ln,h);if(!f.success){const v=f.error instanceof Error?f.error.message:String(f.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${v}`)}return f.data}const d=Gt(qn,h);if(!d.success){const f=d.error instanceof Error?d.error.message:String(d.error);throw new re(oe.InvalidParams,`Invalid tools/call result: ${f}`)}return d.data};return super.setRequestHandler(e,i)}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){s0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&n0(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:uh.includes(r)?r:zs,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"},Fr)}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],o=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=a?Array.isArray(a.content)?a.content:[a.content]:[],c=i.some(l=>l.type==="tool_use");if(o){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){const l=new Set(i.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.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},el,r):this.request({method:"sampling/createMessage",params:e},Ha,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},Js,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"},o=await this.request({method:"elicitation/create",params:s},Js,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!i.valid)throw new re(oe.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof re?a:new re(oe.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}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},nl,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 Fl=Symbol.for("mcp.completable");function MS(t,e){return Object.defineProperty(t,Fl,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function S0(t){return!!t&&typeof t=="object"&&Fl in t}function NS(t){return t[Fl]?.complete}var T0;(function(t){t.Completable="McpCompletable"})(T0||(T0={}));const C0=1e6,Vl=1e6,$0=1e4,LS=1e6;class xr{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){xr.validateLength(e,C0,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const a=e.indexOf("}",s);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>$0)throw new Error(`Template contains too many expressions (max ${$0})`);const i=e.slice(s+1,a),c=this.getOperator(i),l=i.includes("*"),u=this.getNames(i),p=u[0];for(const h of u)xr.validateLength(h,Vl,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),s=a+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 xr.validateLength(e,Vl,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const a=e.names.map(c=>{const l=r[c];if(l===void 0)return"";const u=Array.isArray(l)?l.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){const a=e.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[e.name];if(n===void 0)return"";const o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const o of e.names)xr.validateLength(o,Vl,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){const a=e.names[o],i=o===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}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){xr.validateLength(e,C0,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const c=this.partToRegExp(i);for(const{pattern:l,name:u}of c)r+=l,n.push({name:u,exploded:i.exploded})}r+="$",xr.validateLength(r,LS,"Generated regex pattern");const s=new RegExp(r),o=e.match(s);if(!o)return null;const a={};for(let i=0;i<n.length;i++){const{name:c,exploded:l}=n[i],u=o[i+1],p=c.replace("*","");l&&u.includes(",")?a[p]=u.split(","):a[p]=u}return a}}const jS=/^[A-Za-z0-9._-]{1,128}$/;function qS(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"),!jS.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.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 zS(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 E0(t){const e=qS(t);return zS(t,e.warnings),e.isValid}class DS{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 x0{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 AS(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new DS(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Gr(Yc)),this.server.assertCanSetRequestHandler(Gr(Ua)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Yc,()=>({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=Gs(r.inputSchema);return s?Jh(s,{strictUnions:!0,pipeStrategy:"input"}):ZS})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const s=Gs(r.outputSchema);s&&(n.outputSchema=Jh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ua,async(e,r)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new re(oe.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Tool ${e.params.name} disabled`);const s=!!e.params.task,o=n.execution?.taskSupport,a="createTask"in n.handler;if((o==="required"||o==="optional")&&!a)throw new re(oe.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new re(oe.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&a)return await this.handleAutomaticTaskPolling(n,e,r);const i=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,i,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof re&&n.code===oe.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 o=Gs(e.inputSchema)??e.inputSchema,a=await sl(o,r);if(!a.success){const i="error"in a?a.error:"Unknown error",c=ol(i);throw new re(oe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new re(oe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=Gs(e.outputSchema),o=await sl(s,r.structuredContent);if(!o.success){const a="error"in o?o.error:"Unknown error",i=ol(a);throw new re(oe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(e,r,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(e.inputSchema){const i=s;return await Promise.resolve(i.createTask(r,a))}else{const i=s;return await Promise.resolve(i.createTask(a))}}if(e.inputSchema){const a=s;return await Promise.resolve(a(r,n))}else{const a=s;return await Promise.resolve(a(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),o=e.handler,a={...n,taskStore:n.taskStore},i=s?await Promise.resolve(o.createTask(s,a)):await Promise.resolve(o.createTask(a)),c=i.task.taskId;let l=i.task;const u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(h=>setTimeout(h,u));const p=await n.taskStore.getTask(c);if(!p)throw new re(oe.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Gr(rl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(rl,async e=>{switch(e.params.ref.type){case"ref/prompt":return Sk(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Tk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new re(oe.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new re(oe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return oo;const o=Dn(n.argsSchema)?.[e.params.argument.name];if(!S0(o))return oo;const a=NS(o);if(!a)return oo;const i=await a(e.params.argument.value,e.params.context);return P0(i)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return oo;throw new re(oe.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return oo;const o=await s(e.params.argument.value,e.params.context);return P0(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Gr(Da)),this.server.assertCanSetRequestHandler(Gr(Dc)),this.server.assertCanSetRequestHandler(Gr(Zc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Da,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),s=[];for(const o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;const a=await o.resourceTemplate.listCallback(r);for(const i of a.resources)s.push({...o.metadata,...i})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Dc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Zc,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new re(oe.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const o of Object.values(this._registeredResourceTemplates)){const a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new re(oe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Gr(Vc)),this.server.assertCanSetRequestHandler(Gr(Hc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Vc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?VS(r.argsSchema):void 0}))})),this.server.setRequestHandler(Hc,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new re(oe.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=Gs(n.argsSchema),o=await sl(s,e.params.arguments);if(!o.success){const c="error"in o?o.error:"Unknown error",l=ol(c);throw new re(oe.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}const a=o.data,i=n.callback;return await Promise.resolve(i(a,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 o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,void 0,r,s,o);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,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){const a={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,s,o){const a={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=a)),typeof l.title<"u"&&(a.title=l.title),typeof l.template<"u"&&(a.resourceTemplate=l.template),typeof l.metadata<"u"&&(a.metadata=l.metadata),typeof l.callback<"u"&&(a.readCallback=l.callback),typeof l.enabled<"u"&&(a.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,n,s,o){const a={title:r,description:n,argsSchema:s===void 0?void 0:zn(s),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=zn(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,s&&Object.values(s).some(c=>{const l=c instanceof Bt?c._def?.innerType:c;return S0(l)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,n,s,o,a,i,c,l){E0(e);const u={title:r,description:n,inputSchema:R0(s),outputSchema:R0(o),annotations:a,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&E0(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=zn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=zn(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const c=r[0];Hl(c)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Hl(r[0])&&(a=r.shift())):typeof c=="object"&&c!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,n,s,o,a,{taskSupport:"forbidden"},void 0,i)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:o,inputSchema:a,outputSchema:i,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,s,o,a,i,c,{taskSupport:"forbidden"},l,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 o=r[0],a=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:o,argsSchema:a}=r,i=this._createRegisteredPrompt(e,s,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}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 US{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new xr(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}const ZS={type:"object",properties:{}};function I0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function FS(t){return"_def"in t||"_zod"in t||I0(t)}function Hl(t){return typeof t!="object"||t===null||FS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(I0)}function R0(t){if(t)return Hl(t)?zn(t):t}function VS(t){const e=Dn(t);return e?Object.entries(e).map(([r,n])=>{const s=Ik(n),o=Rk(n);return{name:r,description:s,required:!o}}):[]}function Gr(t){const r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=jh(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function P0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const oo={completion:{values:[],hasMore:!1}};function HS(t){return t.title!==void 0&&t.title!==""?t.title:"annotations"in t&&t.annotations?.title?t.annotations.title:t.name}class ao{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new ao,r=new ao;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(;this._messageQueue.length>0;){const e=this._messageQueue.shift();this.onmessage?.(e.message,e.extra)}}async close(){const e=this._otherTransport;this._otherTransport=void 0,await e?.close(),this.onclose?.()}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r?.authInfo}})}}class BS{constructor(e,r){const n={name:"web-mcp-server",version:"1.0.0"},s={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new x0(e||n,r||{capabilities:s}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=o=>{this.onerror?.(o)},this.server.server.setRequestHandler(Fa,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new zl(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,n){return this.server.registerTool(e,r,n)}registerPrompt(e,r,n){return this.server.registerPrompt(e,r,n)}registerResource(e,r,n,s){return typeof r=="string"?this.server.registerResource(e,r,n,s):this.server.registerResource(e,r,n,s)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,n){return this.server.server.request(e,r,n)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(Ch,e)}onUnsubscribe(e){this.server.server.setRequestHandler($h,e)}onSetLogLevel(e){this.server.server.setRequestHandler(Fa,e)}onListResources(e){this.server.server.setRequestHandler(Da,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(Nh,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const JS=(t,e)=>new zl(t,e),GS=()=>fS(),WS=t=>t instanceof zl,KS=t=>t instanceof x0;class O0{constructor(e,r){const n={name:"web-mcp-client",version:"1.0.0"},s={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ws(e||n,r||{capabilities:s}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=o=>{this.onerror?.(o)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:s,type:o,agent:a,onError:i}=e;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:s};let p;return await(async()=>{const{transport:d,sessionId:f}=o==="sse"?await ES(u):o==="socket"?await IS(u):await xS(u);d.onerror=async v=>{i?.(v)},p={transport:d,sessionId:f}})(),p}const c=new URL(r);let l;if(o==="channel"&&(l=new ql(r),await this.client.connect(l)),o==="sse"){const u=w0(n,s);l=new eo(c,u),await this.client.connect(l)}if(o==="socket"&&(l=new _0(new URL(`${r}?sessionId=${s}&token=${n}`)),l.sessionId=s,await this.client.connect(l)),typeof l>"u"){const u=b0(n,s);l=new to(c,u),await this.client.connect(l)}return this.transport=l,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,qn,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,n){return this.client.request(e,r,n)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(tl,e)}onCreateMessage(e){this.client.setRequestHandler(Xc,e)}onListRoots(e){this.client.setRequestHandler(Mh,e)}onToolListChanged(e){this.client.setNotificationHandler(Qc,e)}onPromptListChanged(e){this.client.setNotificationHandler(Kc,e)}onResourceListChanged(e){this.client.setNotificationHandler(Fc,e)}onResourceUpdated(e){this.client.setNotificationHandler(Eh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Oh,e)}async onPagehide(e){e.persisted||(A0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const YS=(t,e)=>new eo(t,e),QS=(t,e)=>new to(t,e),XS=(t,e)=>new ql(t,e),e5=t=>t instanceof eo,A0=t=>t instanceof to,t5=t=>t instanceof ql,r5=t=>t instanceof Ws,Wn=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},M0=(t,e,r)=>{const n=async function(s){s.source===window&&s.data.type===t&&s.data.direction===r&&await e(s.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Bl=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(s=>{chrome.tabs.sendMessage(s.id,{type:t,data:e,direction:r,tabId:s.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},Jl=(t,e,r,n)=>{const s=(o,a,i)=>{if(o.type===t&&o.direction===r&&(!n||n&&o.tabId===n)){const{data:c}=o;e(c,a,i),i(a)}};return chrome.runtime.onMessage.addListener(s),()=>chrome.runtime.onMessage.removeListener(s)};class N0{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=Jl("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Tr.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const s=n.tabIds[n.tabIds.length-1];Bl("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:s,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const L0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class n5{constructor(e=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||L0(),this._messageListener1=M0("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.error("【Page Svr Transport】 notifyRegistration失败:",r)})},"content->page"),this._messageListener2=M0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=Tr.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Wn("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Wn("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&e.result?.content&&Wn("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Wn("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class s5{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||L0(),this.tabId=r,Jl("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Jl("mcp-client-to-server",e=>{if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const r=Tr.parse(e.mcpMessage);this.onmessage?.(r),e.mcpMessage.params?.name&&Wn("update-page-app-message",{status:"run",message:e.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),Bl("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&e.result?.content&&Wn("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,Bl("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Kn={},Gl,j0;function o5(){return j0||(j0=1,Gl=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Gl}var Wl={},Wr={},q0;function yn(){if(q0)return Wr;q0=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Wr.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Wr.getSymbolTotalCodewords=function(n){return e[n]},Wr.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Wr.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Wr.isKanjiModeEnabled=function(){return typeof t<"u"},Wr.toSJIS=function(n){return t(n)},Wr}var Kl={},z0;function Yl(){return z0||(z0=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,s){if(t.isValid(n))return n;try{return e(n)}catch{return s}}})(Kl)),Kl}var Ql,D0;function a5(){if(D0)return Ql;D0=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ql=t,Ql}var Xl,U0;function i5(){if(U0)return Xl;U0=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,s){const o=e*this.size+r;this.data[o]=n,s&&(this.reservedBit[o]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Xl=t,Xl}var eu={},Z0;function c5(){return Z0||(Z0=1,(function(t){const e=yn().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const s=Math.floor(n/7)+2,o=e(n),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,i=[o-7];for(let c=1;c<s-1;c++)i[c]=i[c-1]-a;return i.push(6),i.reverse()},t.getPositions=function(n){const s=[],o=t.getRowColCoords(n),a=o.length;for(let i=0;i<a;i++)for(let c=0;c<a;c++)i===0&&c===0||i===0&&c===a-1||i===a-1&&c===0||s.push([o[i],o[c]]);return s}})(eu)),eu}var tu={},F0;function l5(){if(F0)return tu;F0=1;const t=yn().getSymbolSize,e=7;return tu.getPositions=function(n){const s=t(n);return[[0,0],[s-e,0],[0,s-e]]},tu}var ru={},V0;function u5(){return V0||(V0=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let a=0,i=0,c=0,l=null,u=null;for(let p=0;p<o;p++){i=c=0,l=u=null;for(let h=0;h<o;h++){let d=s.get(p,h);d===l?i++:(i>=5&&(a+=e.N1+(i-5)),l=d,i=1),d=s.get(h,p),d===u?c++:(c>=5&&(a+=e.N1+(c-5)),u=d,c=1)}i>=5&&(a+=e.N1+(i-5)),c>=5&&(a+=e.N1+(c-5))}return a},t.getPenaltyN2=function(s){const o=s.size;let a=0;for(let i=0;i<o-1;i++)for(let c=0;c<o-1;c++){const l=s.get(i,c)+s.get(i,c+1)+s.get(i+1,c)+s.get(i+1,c+1);(l===4||l===0)&&a++}return a*e.N2},t.getPenaltyN3=function(s){const o=s.size;let a=0,i=0,c=0;for(let l=0;l<o;l++){i=c=0;for(let u=0;u<o;u++)i=i<<1&2047|s.get(l,u),u>=10&&(i===1488||i===93)&&a++,c=c<<1&2047|s.get(u,l),u>=10&&(c===1488||c===93)&&a++}return a*e.N3},t.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let c=0;c<a;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function r(n,s,o){switch(n){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(s,o){const a=o.size;for(let i=0;i<a;i++)for(let c=0;c<a;c++)o.isReserved(c,i)||o.xor(c,i,r(s,c,i))},t.getBestMask=function(s,o){const a=Object.keys(t.Patterns).length;let i=0,c=1/0;for(let l=0;l<a;l++){o(l),t.applyMask(l,s);const u=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(l,s),u<c&&(c=u,i=l)}return i}})(ru)),ru}var di={},H0;function B0(){if(H0)return di;H0=1;const t=Yl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return di.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},di.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return r[(s-1)*4+0];case t.M:return r[(s-1)*4+1];case t.Q:return r[(s-1)*4+2];case t.H:return r[(s-1)*4+3];default:return}},di}var nu={},io={},J0;function d5(){if(J0)return io;J0=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let s=0;s<255;s++)t[s]=n,e[n]=s,n<<=1,n&256&&(n^=285);for(let s=255;s<512;s++)t[s]=t[s-255]})(),io.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},io.exp=function(n){return t[n]},io.mul=function(n,s){return n===0||s===0?0:t[e[n]+e[s]]},io}var G0;function p5(){return G0||(G0=1,(function(t){const e=d5();t.mul=function(n,s){const o=new Uint8Array(n.length+s.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<s.length;i++)o[a+i]^=e.mul(n[a],s[i]);return o},t.mod=function(n,s){let o=new Uint8Array(n);for(;o.length-s.length>=0;){const a=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],a);let i=0;for(;i<o.length&&o[i]===0;)i++;o=o.slice(i)}return o},t.generateECPolynomial=function(n){let s=new Uint8Array([1]);for(let o=0;o<n;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})(nu)),nu}var su,W0;function f5(){if(W0)return su;W0=1;const t=p5();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const s=new Uint8Array(n.length+this.degree);s.set(n);const o=t.mod(s,this.genPoly),a=this.degree-o.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(o,a),i}return o},su=e,su}var ou={},au={},iu={},K0;function Y0(){return K0||(K0=1,iu.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),iu}var ur={},Q0;function X0(){if(Q0)return ur;Q0=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
44
- ]))+`;ur.KANJI=new RegExp(r,"g"),ur.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ur.BYTE=new RegExp(n,"g"),ur.NUMERIC=new RegExp(t,"g"),ur.ALPHANUMERIC=new RegExp(e,"g");const s=new RegExp("^"+r+"$"),o=new RegExp("^"+t+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ur.testKanji=function(c){return s.test(c)},ur.testNumeric=function(c){return o.test(c)},ur.testAlphanumeric=function(c){return a.test(c)},ur}var em;function _n(){return em||(em=1,(function(t){const e=Y0(),r=X0();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(o,a){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?o.ccBits[0]:a<27?o.ccBits[1]:o.ccBits[2]},t.getBestModeForData=function(o){return r.testNumeric(o)?t.NUMERIC:r.testAlphanumeric(o)?t.ALPHANUMERIC:r.testKanji(o)?t.KANJI:t.BYTE},t.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},t.isValid=function(o){return o&&o.bit&&o.ccBits};function n(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+s)}}t.from=function(o,a){if(t.isValid(o))return o;try{return n(o)}catch{return a}}})(au)),au}var tm;function h5(){return tm||(tm=1,(function(t){const e=yn(),r=B0(),n=Yl(),s=_n(),o=Y0(),a=7973,i=e.getBCHDigit(a);function c(h,d,f){for(let v=1;v<=40;v++)if(d<=t.getCapacity(v,f,h))return v}function l(h,d){return s.getCharCountIndicator(h,d)+4}function u(h,d){let f=0;return h.forEach(function(v){const g=l(v.mode,d);f+=g+v.getBitsLength()}),f}function p(h,d){for(let f=1;f<=40;f++)if(u(h,f)<=t.getCapacity(f,d,s.MIXED))return f}t.from=function(d,f){return o.isValid(d)?parseInt(d,10):f},t.getCapacity=function(d,f,v){if(!o.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=s.BYTE);const g=e.getSymbolTotalCodewords(d),w=r.getTotalCodewordsCount(d,f),y=(g-w)*8;if(v===s.MIXED)return y;const _=y-l(v,d);switch(v){case s.NUMERIC:return Math.floor(_/10*3);case s.ALPHANUMERIC:return Math.floor(_/11*2);case s.KANJI:return Math.floor(_/13);case s.BYTE:default:return Math.floor(_/8)}},t.getBestVersionForData=function(d,f){let v;const g=n.from(f,n.M);if(Array.isArray(d)){if(d.length>1)return p(d,g);if(d.length===0)return 1;v=d[0]}else v=d;return c(v.mode,v.getLength(),g)},t.getEncodedBits=function(d){if(!o.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;e.getBCHDigit(f)-i>=0;)f^=a<<e.getBCHDigit(f)-i;return d<<12|f}})(ou)),ou}var cu={},rm;function m5(){if(rm)return cu;rm=1;const t=yn(),e=1335,r=21522,n=t.getBCHDigit(e);return cu.getEncodedBits=function(o,a){const i=o.bit<<3|a;let c=i<<10;for(;t.getBCHDigit(c)-n>=0;)c^=e<<t.getBCHDigit(c)-n;return(i<<10|c)^r},cu}var lu={},uu,nm;function g5(){if(nm)return uu;nm=1;const t=_n();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let s,o,a;for(s=0;s+3<=this.data.length;s+=3)o=this.data.substr(s,3),a=parseInt(o,10),n.put(a,10);const i=this.data.length-s;i>0&&(o=this.data.substr(s),a=parseInt(o,10),n.put(a,i*3+1))},uu=e,uu}var du,sm;function y5(){if(sm)return du;sm=1;const t=_n(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(s){return 11*Math.floor(s/2)+6*(s%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(s){let o;for(o=0;o+2<=this.data.length;o+=2){let a=e.indexOf(this.data[o])*45;a+=e.indexOf(this.data[o+1]),s.put(a,11)}this.data.length%2&&s.put(e.indexOf(this.data[o]),6)},du=r,du}var pu,om;function _5(){if(om)return pu;om=1;const t=_n();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,s=this.data.length;n<s;n++)r.put(this.data[n],8)},pu=e,pu}var fu,am;function v5(){if(am)return fu;am=1;const t=_n(),e=yn();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(s){return s*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let s;for(s=0;s<this.data.length;s++){let o=e.toSJIS(this.data[s]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[s]+`
45
- Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},fu=r,fu}var hu={exports:{}},im;function w5(){return im||(im=1,(function(t){var e={single_source_shortest_paths:function(r,n,s){var o={},a={};a[n]=0;var i=e.PriorityQueue.make();i.push(n,0);for(var c,l,u,p,h,d,f,v,g;!i.empty();){c=i.pop(),l=c.value,p=c.cost,h=r[l]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],f=p+d,v=a[u],g=typeof a[u]>"u",(g||v>f)&&(a[u]=f,i.push(u,f),o[u]=l))}if(typeof s<"u"&&typeof a[s]>"u"){var w=["Could not find a path from ",n," to ",s,"."].join("");throw new Error(w)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var s=[],o=n;o;)s.push(o),r[o],o=r[o];return s.reverse(),s},find_path:function(r,n,s){var o=e.single_source_shortest_paths(r,n,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,s={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(s[o]=n[o]);return s.queue=[],s.sorter=r.sorter||n.default_sorter,s},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var s={value:r,cost:n};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(hu)),hu.exports}var cm;function b5(){return cm||(cm=1,(function(t){const e=_n(),r=g5(),n=y5(),s=_5(),o=v5(),a=X0(),i=yn(),c=w5();function l(w){return unescape(encodeURIComponent(w)).length}function u(w,y,_){const b=[];let k;for(;(k=w.exec(_))!==null;)b.push({data:k[0],index:k.index,mode:y,length:k[0].length});return b}function p(w){const y=u(a.NUMERIC,e.NUMERIC,w),_=u(a.ALPHANUMERIC,e.ALPHANUMERIC,w);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,e.BYTE,w),k=u(a.KANJI,e.KANJI,w)):(b=u(a.BYTE_KANJI,e.BYTE,w),k=[]),y.concat(_,b,k).sort(function(T,x){return T.index-x.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function h(w,y){switch(y){case e.NUMERIC:return r.getBitsLength(w);case e.ALPHANUMERIC:return n.getBitsLength(w);case e.KANJI:return o.getBitsLength(w);case e.BYTE:return s.getBitsLength(w)}}function d(w){return w.reduce(function(y,_){const b=y.length-1>=0?y[y.length-1]:null;return b&&b.mode===_.mode?(y[y.length-1].data+=_.data,y):(y.push(_),y)},[])}function f(w){const y=[];for(let _=0;_<w.length;_++){const b=w[_];switch(b.mode){case e.NUMERIC:y.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:y.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:y.push([b,{data:b.data,mode:e.BYTE,length:l(b.data)}]);break;case e.BYTE:y.push([{data:b.data,mode:e.BYTE,length:l(b.data)}])}}return y}function v(w,y){const _={},b={start:{}};let k=["start"];for(let S=0;S<w.length;S++){const T=w[S],x=[];for(let R=0;R<T.length;R++){const j=T[R],O=""+S+R;x.push(O),_[O]={node:j,lastCount:0},b[O]={};for(let D=0;D<k.length;D++){const U=k[D];_[U]&&_[U].node.mode===j.mode?(b[U][O]=h(_[U].lastCount+j.length,j.mode)-h(_[U].lastCount,j.mode),_[U].lastCount+=j.length):(_[U]&&(_[U].lastCount=j.length),b[U][O]=h(j.length,j.mode)+4+e.getCharCountIndicator(j.mode,y))}}k=x}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:_}}function g(w,y){let _;const b=e.getBestModeForData(w);if(_=e.from(y,b),_!==e.BYTE&&_.bit<b.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(_)+`.
46
- Suggested mode is: `+e.toString(b));switch(_===e.KANJI&&!i.isKanjiModeEnabled()&&(_=e.BYTE),_){case e.NUMERIC:return new r(w);case e.ALPHANUMERIC:return new n(w);case e.KANJI:return new o(w);case e.BYTE:return new s(w)}}t.fromArray=function(y){return y.reduce(function(_,b){return typeof b=="string"?_.push(g(b,null)):b.data&&_.push(g(b.data,b.mode)),_},[])},t.fromString=function(y,_){const b=p(y,i.isKanjiModeEnabled()),k=f(b),S=v(k,_),T=c.find_path(S.map,"start","end"),x=[];for(let R=1;R<T.length-1;R++)x.push(S.table[T[R]].node);return t.fromArray(d(x))},t.rawSplit=function(y){return t.fromArray(p(y,i.isKanjiModeEnabled()))}})(lu)),lu}var lm;function k5(){if(lm)return Wl;lm=1;const t=yn(),e=Yl(),r=a5(),n=i5(),s=c5(),o=l5(),a=u5(),i=B0(),c=f5(),l=h5(),u=m5(),p=_n(),h=b5();function d(S,T){const x=S.size,R=o.getPositions(T);for(let j=0;j<R.length;j++){const O=R[j][0],D=R[j][1];for(let U=-1;U<=7;U++)if(!(O+U<=-1||x<=O+U))for(let V=-1;V<=7;V++)D+V<=-1||x<=D+V||(U>=0&&U<=6&&(V===0||V===6)||V>=0&&V<=6&&(U===0||U===6)||U>=2&&U<=4&&V>=2&&V<=4?S.set(O+U,D+V,!0,!0):S.set(O+U,D+V,!1,!0))}}function f(S){const T=S.size;for(let x=8;x<T-8;x++){const R=x%2===0;S.set(x,6,R,!0),S.set(6,x,R,!0)}}function v(S,T){const x=s.getPositions(T);for(let R=0;R<x.length;R++){const j=x[R][0],O=x[R][1];for(let D=-2;D<=2;D++)for(let U=-2;U<=2;U++)D===-2||D===2||U===-2||U===2||D===0&&U===0?S.set(j+D,O+U,!0,!0):S.set(j+D,O+U,!1,!0)}}function g(S,T){const x=S.size,R=l.getEncodedBits(T);let j,O,D;for(let U=0;U<18;U++)j=Math.floor(U/3),O=U%3+x-8-3,D=(R>>U&1)===1,S.set(j,O,D,!0),S.set(O,j,D,!0)}function w(S,T,x){const R=S.size,j=u.getEncodedBits(T,x);let O,D;for(O=0;O<15;O++)D=(j>>O&1)===1,O<6?S.set(O,8,D,!0):O<8?S.set(O+1,8,D,!0):S.set(R-15+O,8,D,!0),O<8?S.set(8,R-O-1,D,!0):O<9?S.set(8,15-O-1+1,D,!0):S.set(8,15-O-1,D,!0);S.set(R-8,8,1,!0)}function y(S,T){const x=S.size;let R=-1,j=x-1,O=7,D=0;for(let U=x-1;U>0;U-=2)for(U===6&&U--;;){for(let V=0;V<2;V++)if(!S.isReserved(j,U-V)){let ne=!1;D<T.length&&(ne=(T[D]>>>O&1)===1),S.set(j,U-V,ne),O--,O===-1&&(D++,O=7)}if(j+=R,j<0||x<=j){j-=R,R=-R;break}}}function _(S,T,x){const R=new r;x.forEach(function(V){R.put(V.mode.bit,4),R.put(V.getLength(),p.getCharCountIndicator(V.mode,S)),V.write(R)});const j=t.getSymbolTotalCodewords(S),O=i.getTotalCodewordsCount(S,T),D=(j-O)*8;for(R.getLengthInBits()+4<=D&&R.put(0,4);R.getLengthInBits()%8!==0;)R.putBit(0);const U=(D-R.getLengthInBits())/8;for(let V=0;V<U;V++)R.put(V%2?17:236,8);return b(R,S,T)}function b(S,T,x){const R=t.getSymbolTotalCodewords(T),j=i.getTotalCodewordsCount(T,x),O=R-j,D=i.getBlocksCount(T,x),U=R%D,V=D-U,ne=Math.floor(R/D),fe=Math.floor(O/D),de=fe+1,te=ne-fe,ye=new c(te);let H=0;const P=new Array(D),F=new Array(D);let q=0;const E=new Uint8Array(S.buffer);for(let _e=0;_e<D;_e++){const pe=_e<V?fe:de;P[_e]=E.slice(H,H+pe),F[_e]=ye.encode(P[_e]),H+=pe,q=Math.max(q,pe)}const I=new Uint8Array(R);let $=0,B,W;for(B=0;B<q;B++)for(W=0;W<D;W++)B<P[W].length&&(I[$++]=P[W][B]);for(B=0;B<te;B++)for(W=0;W<D;W++)I[$++]=F[W][B];return I}function k(S,T,x,R){let j;if(Array.isArray(S))j=h.fromArray(S);else if(typeof S=="string"){let ne=T;if(!ne){const fe=h.rawSplit(S);ne=l.getBestVersionForData(fe,x)}j=h.fromString(S,ne||40)}else throw new Error("Invalid data");const O=l.getBestVersionForData(j,x);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=O;else if(T<O)throw new Error(`
32
+ path: iss.path ? [${cs(v)}, ...iss.path] : [${cs(v)}]
33
+ })));`),p.write(`newResult[${cs(v)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(v,m)=>w(h,v,m)};let o;const s=fi,a=!Kf.jitless,l=a&&Db.value,c=t.catchall;let u;e._zod.parse=(h,p)=>{u??(u=r.value);const f=h.value;if(!s(f))return h.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),h;const g=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),h=o(h,p);else{h.value={};const m=u.shape;for(const S of u.keys){const k=m[S],T=k._zod.run({value:f[S],issues:[]},p),b=k._zod.optin==="optional"&&k._zod.optout==="optional";T instanceof Promise?g.push(T.then(x=>b?mh(x,h,S,f):vi(x,h,S))):b?mh(T,h,S,f):vi(T,h,S)}}if(!c)return g.length?Promise.all(g).then(()=>h):h;const _=[],y=u.keySet,w=c._zod,v=w.def.type;for(const m of Object.keys(f)){if(y.has(m))continue;if(v==="never"){_.push(m);continue}const S=w.run({value:f[m],issues:[]},p);S instanceof Promise?g.push(S.then(k=>vi(k,h,m))):vi(S,h,m)}return _.length&&h.issues.push({code:"unrecognized_keys",keys:_,input:f,inst:e}),g.length?Promise.all(g).then(()=>h):h}});function yh(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>yn(s,n,mn())))}),t}const vh=W("$ZodUnion",(e,t)=>{Ke.init(e,t),Ve(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ve(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ve(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ve(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Xl(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>yh(a,r,e,n)):yh(s,r,e,n)}}),_9=W("$ZodDiscriminatedUnion",(e,t)=>{vh.init(e,t);const r=e._zod.parse;Ve(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=Yl(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!fi(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),w9=W("$ZodIntersection",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>_h(r,l,c)):_h(r,s,a)}});function oc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(hi(e)&&hi(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=oc(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=oc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function _h(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),ds(e))return e;const n=oc(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const b9=W("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!hi(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Un(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Un(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>yn(c,n,mn())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...Un(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Un(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),k9=W("$ZodEnum",(e,t)=>{Ke.init(e,t);const r=Yf(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Ub.has(typeof n)).map(n=>typeof n=="string"?us(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),T9=W("$ZodLiteral",(e,t)=>{Ke.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?us(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),C9=W("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new is;return r.value=o,r}}),S9=W("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ve(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Xl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),I9=W("$ZodNullable",(e,t)=>{Ke.init(e,t),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Xl(r.source)}|null)$`):void 0}),Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),E9=W("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>wh(s,t)):wh(o,t)}});function wh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const x9=W("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),$9=W("$ZodNonOptional",(e,t)=>{Ke.init(e,t),Ve(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>bh(s,e)):bh(o,e)}});function bh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const R9=W("$ZodCatch",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>yn(a,n,mn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>yn(s,n,mn()))},input:r.value}),r.issues=[]),r)}}),P9=W("$ZodPipe",(e,t)=>{Ke.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>kh(s,t,n)):kh(o,t,n)}});function kh(e,t,r){return ds(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const M9=W("$ZodReadonly",(e,t)=>{Ke.init(e,t),Ve(e._zod,"propValues",()=>t.innerType._zod.propValues),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Th):Th(o)}});function Th(e){return e.value=Object.freeze(e.value),e}const O9=W("$ZodLazy",(e,t)=>{Ke.init(e,t),Ve(e._zod,"innerType",()=>t.getter()),Ve(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ve(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ve(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ve(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),N9=W("$ZodCustom",(e,t)=>{Vt.init(e,t),Ke.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Ch(s,r,n,e));Ch(o,r,n,e)}});function Ch(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(ps(o))}}class Sh{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,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,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function A9(){return new Sh}const fs=A9();function q9(e,t){return new e({type:"string",...fe(t)})}function L9(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function Ih(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function j9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function D9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function U9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function z9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function Eh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function Z9(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function F9(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function V9(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function H9(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function B9(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function J9(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function W9(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function G9(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function K9(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function Y9(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(t)})}function Q9(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function xh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function X9(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function e4(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function t4(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function r4(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function n4(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function o4(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function s4(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function a4(e,t){return new e({type:"number",checks:[],...fe(t)})}function i4(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function l4(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function c4(e,t){return new e({type:"boolean",...fe(t)})}function u4(e,t){return new e({type:"null",...fe(t)})}function d4(e){return new e({type:"any"})}function p4(e){return new e({type:"unknown"})}function f4(e,t){return new e({type:"never",...fe(t)})}function $h(e,t){return new uh({check:"less_than",...fe(t),value:e,inclusive:!1})}function sc(e,t){return new uh({check:"less_than",...fe(t),value:e,inclusive:!0})}function Rh(e,t){return new dh({check:"greater_than",...fe(t),value:e,inclusive:!1})}function ac(e,t){return new dh({check:"greater_than",...fe(t),value:e,inclusive:!0})}function Ph(e,t){return new E3({check:"multiple_of",...fe(t),value:e})}function Mh(e,t){return new $3({check:"max_length",...fe(t),maximum:e})}function _i(e,t){return new R3({check:"min_length",...fe(t),minimum:e})}function Oh(e,t){return new P3({check:"length_equals",...fe(t),length:e})}function h4(e,t){return new M3({check:"string_format",format:"regex",...fe(t),pattern:e})}function m4(e){return new O3({check:"string_format",format:"lowercase",...fe(e)})}function g4(e){return new N3({check:"string_format",format:"uppercase",...fe(e)})}function y4(e,t){return new A3({check:"string_format",format:"includes",...fe(t),includes:e})}function v4(e,t){return new q3({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function _4(e,t){return new L3({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function hs(e){return new j3({check:"overwrite",tx:e})}function w4(e){return hs(t=>t.normalize(e))}function b4(){return hs(e=>e.trim())}function k4(){return hs(e=>e.toLowerCase())}function T4(){return hs(e=>e.toUpperCase())}function C4(e,t,r){return new e({type:"array",element:t,...fe(r)})}function S4(e,t,r){const n=fe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function I4(e,t,r){return new e({type:"custom",check:"custom",fn:t,...fe(r)})}class Nh{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??fs,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const h={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,h),this.seen.get(p).isParent=!0;else{const f=i.schema;switch(o.type){case"string":{const g=f;g.type="string";const{minimum:_,maximum:y,format:w,patterns:v,contentEncoding:m}=t._zod.bag;if(typeof _=="number"&&(g.minLength=_),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),m&&(g.contentEncoding=m),v&&v.size>0){const S=[...v];S.length===1?g.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const g=f,{minimum:_,maximum:y,format:w,multipleOf:v,exclusiveMaximum:m,exclusiveMinimum:S}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof S=="number"&&(g.exclusiveMinimum=S),typeof _=="number"&&(g.minimum=_,typeof S=="number"&&(S>=_?delete g.minimum:delete g.exclusiveMinimum)),typeof m=="number"&&(g.exclusiveMaximum=m),typeof y=="number"&&(g.maximum=y,typeof m=="number"&&(m<=y?delete g.maximum:delete g.exclusiveMaximum)),typeof v=="number"&&(g.multipleOf=v);break}case"boolean":{const g=f;g.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=f,{minimum:_,maximum:y}=t._zod.bag;typeof _=="number"&&(g.minItems=_),typeof y=="number"&&(g.maxItems=y),g.type="array",g.items=this.process(o.element,{...h,path:[...h.path,"items"]});break}case"object":{const g=f;g.type="object",g.properties={};const _=o.shape;for(const v in _)g.properties[v]=this.process(_[v],{...h,path:[...h.path,"properties",v]});const y=new Set(Object.keys(_)),w=new Set([...y].filter(v=>{const m=o.shape[v]._zod;return this.io==="input"?m.optin===void 0:m.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=f;g.anyOf=o.options.map((_,y)=>this.process(_,{...h,path:[...h.path,"anyOf",y]}));break}case"intersection":{const g=f,_=this.process(o.left,{...h,path:[...h.path,"allOf",0]}),y=this.process(o.right,{...h,path:[...h.path,"allOf",1]}),w=m=>"allOf"in m&&Object.keys(m).length===1,v=[...w(_)?_.allOf:[_],...w(y)?y.allOf:[y]];g.allOf=v;break}case"tuple":{const g=f;g.type="array";const _=o.items.map((v,m)=>this.process(v,{...h,path:[...h.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?g.prefixItems=_:g.items=_,o.rest){const v=this.process(o.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?g.items=v:g.additionalItems=v}o.rest&&(g.items=this.process(o.rest,{...h,path:[...h.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(g.minItems=y),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=f;g.type="object",g.propertyNames=this.process(o.keyType,{...h,path:[...h.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...h,path:[...h.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 g=f,_=Yf(o.entries);_.every(y=>typeof y=="number")&&(g.type="number"),_.every(y=>typeof y=="string")&&(g.type="string"),g.enum=_;break}case"literal":{const g=f,_=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(y))}else _.push(y);if(_.length!==0)if(_.length===1){const y=_[0];g.type=y===null?"null":typeof y,g.const=y}else _.every(y=>typeof y=="number")&&(g.type="number"),_.every(y=>typeof y=="string")&&(g.type="string"),_.every(y=>typeof y=="boolean")&&(g.type="string"),_.every(y=>y===null)&&(g.type="null"),g.enum=_;break}case"file":{const g=f,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:v}=t._zod.bag;y!==void 0&&(_.minLength=y),w!==void 0&&(_.maxLength=w),v?v.length===1?(_.contentMediaType=v[0],Object.assign(g,_)):g.anyOf=v.map(m=>({..._,contentMediaType:m})):Object.assign(g,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const g=this.process(o.innerType,h);f.anyOf=[g,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,h),i.ref=o.innerType;break}case"success":{const g=f;g.type="boolean";break}case"default":{this.process(o.innerType,h),i.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,h),i.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,h),i.ref=o.innerType;let g;try{g=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=g;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const g=f,_=t._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");g.type="string",g.pattern=_.source;break}case"pipe":{const g=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(g,h),i.ref=g;break}case"readonly":{this.process(o.innerType,h),i.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,h),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,h),i.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,h),i.ref=g;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&_t(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const h=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const _=n.external.registry.get(u[0])?.id,y=n.external.uri??(v=>v);if(_)return{ref:y(_)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${y("__shared")}#/${h}/${w}`}}if(u[1]===o)return{ref:"#"};const f=`#/${h}/`,g=u[1].schema.id??`__schema${this.counter++}`;return{defId:g,ref:f+g}},a=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:f}=s(u);h.def={...h.schema},f&&(h.defId=f);const g=h.schema;for(const _ in g)delete g[_];g.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${h.cycle?.join("/")}/<root>
34
+
35
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const h=u[1];if(t===u[0]){a(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(h.cycle){a(u);continue}if(h.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,h)=>{const p=this.seen.get(u),f=p.def??p.schema,g={...f};if(p.ref===null)return;const _=p.ref;if(p.ref=null,_){i(_,h);const y=this.seen.get(_).schema;y.$ref&&h.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,g))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const h=u[1];h.def&&h.defId&&(c[h.defId]=h.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function Ah(e,t){if(e instanceof Sh){const n=new Nh(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new Nh(t);return r.process(e),r.emit(e,t)}function _t(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return _t(o.element,r);case"object":{for(const s in o.shape)if(_t(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(_t(s,r))return!0;return!1}case"intersection":return _t(o.left,r)||_t(o.right,r);case"tuple":{for(const s of o.items)if(_t(s,r))return!0;return!!(o.rest&&_t(o.rest,r))}case"record":return _t(o.keyType,r)||_t(o.valueType,r);case"map":return _t(o.keyType,r)||_t(o.valueType,r);case"set":return _t(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return _t(o.innerType,r);case"lazy":return _t(o.getter(),r);case"default":return _t(o.innerType,r);case"prefault":return _t(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return _t(o.in,r)||_t(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const E4=W("ZodISODateTime",(e,t)=>{Q3.init(e,t),lt.init(e,t)});function qh(e){return r4(E4,e)}const x4=W("ZodISODate",(e,t)=>{X3.init(e,t),lt.init(e,t)});function $4(e){return n4(x4,e)}const R4=W("ZodISOTime",(e,t)=>{e9.init(e,t),lt.init(e,t)});function P4(e){return o4(R4,e)}const M4=W("ZodISODuration",(e,t)=>{t9.init(e,t),lt.init(e,t)});function O4(e){return s4(M4,e)}const wi=W("ZodError",(e,t)=>{eh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Kb(e,r)},flatten:{value:r=>Gb(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),N4=th(wi),A4=rh(wi),q4=nh(wi),Lh=oh(wi),et=W("ZodType",(e,t)=>(Ke.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>gn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>N4(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>q4(e,r,n),e.parseAsync=async(r,n)=>A4(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Lh(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Ik(r,n)),e.superRefine=r=>e.check(Ek(r)),e.overwrite=r=>e.check(hs(r)),e.optional=()=>pe(e),e.nullable=()=>Wh(e),e.nullish=()=>pe(Wh(e)),e.nonoptional=r=>vk(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>lc(e,r),e.transform=r=>uc(e,Bh(r)),e.default=r=>mk(e,r),e.prefault=r=>yk(e,r),e.catch=r=>wk(e,r),e.pipe=r=>uc(e,r),e.readonly=()=>Tk(e),e.describe=r=>{const n=e.clone();return fs.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return fs.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return fs.get(e);const n=e.clone();return fs.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),jh=W("_ZodString",(e,t)=>{nc.init(e,t),et.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(h4(...n)),e.includes=(...n)=>e.check(y4(...n)),e.startsWith=(...n)=>e.check(v4(...n)),e.endsWith=(...n)=>e.check(_4(...n)),e.min=(...n)=>e.check(_i(...n)),e.max=(...n)=>e.check(Mh(...n)),e.length=(...n)=>e.check(Oh(...n)),e.nonempty=(...n)=>e.check(_i(1,...n)),e.lowercase=n=>e.check(m4(n)),e.uppercase=n=>e.check(g4(n)),e.trim=()=>e.check(b4()),e.normalize=(...n)=>e.check(w4(...n)),e.toLowerCase=()=>e.check(k4()),e.toUpperCase=()=>e.check(T4())}),L4=W("ZodString",(e,t)=>{nc.init(e,t),jh.init(e,t),e.email=r=>e.check(L9(j4,r)),e.url=r=>e.check(Eh(Uh,r)),e.jwt=r=>e.check(t4(X4,r)),e.emoji=r=>e.check(Z9(U4,r)),e.guid=r=>e.check(Ih(Dh,r)),e.uuid=r=>e.check(j9(bi,r)),e.uuidv4=r=>e.check(D9(bi,r)),e.uuidv6=r=>e.check(U9(bi,r)),e.uuidv7=r=>e.check(z9(bi,r)),e.nanoid=r=>e.check(F9(z4,r)),e.guid=r=>e.check(Ih(Dh,r)),e.cuid=r=>e.check(V9(Z4,r)),e.cuid2=r=>e.check(H9(F4,r)),e.ulid=r=>e.check(B9(V4,r)),e.base64=r=>e.check(xh(zh,r)),e.base64url=r=>e.check(X9(Y4,r)),e.xid=r=>e.check(J9(H4,r)),e.ksuid=r=>e.check(W9(B4,r)),e.ipv4=r=>e.check(G9(J4,r)),e.ipv6=r=>e.check(K9(W4,r)),e.cidrv4=r=>e.check(Y9(G4,r)),e.cidrv6=r=>e.check(Q9(K4,r)),e.e164=r=>e.check(e4(Q4,r)),e.datetime=r=>e.check(qh(r)),e.date=r=>e.check($4(r)),e.time=r=>e.check(P4(r)),e.duration=r=>e.check(O4(r))});function d(e){return q9(L4,e)}const lt=W("ZodStringFormat",(e,t)=>{ot.init(e,t),jh.init(e,t)}),j4=W("ZodEmail",(e,t)=>{F3.init(e,t),lt.init(e,t)}),Dh=W("ZodGUID",(e,t)=>{z3.init(e,t),lt.init(e,t)}),bi=W("ZodUUID",(e,t)=>{Z3.init(e,t),lt.init(e,t)}),Uh=W("ZodURL",(e,t)=>{V3.init(e,t),lt.init(e,t)});function D4(e){return Eh(Uh,e)}const U4=W("ZodEmoji",(e,t)=>{H3.init(e,t),lt.init(e,t)}),z4=W("ZodNanoID",(e,t)=>{B3.init(e,t),lt.init(e,t)}),Z4=W("ZodCUID",(e,t)=>{J3.init(e,t),lt.init(e,t)}),F4=W("ZodCUID2",(e,t)=>{W3.init(e,t),lt.init(e,t)}),V4=W("ZodULID",(e,t)=>{G3.init(e,t),lt.init(e,t)}),H4=W("ZodXID",(e,t)=>{K3.init(e,t),lt.init(e,t)}),B4=W("ZodKSUID",(e,t)=>{Y3.init(e,t),lt.init(e,t)}),J4=W("ZodIPv4",(e,t)=>{r9.init(e,t),lt.init(e,t)}),W4=W("ZodIPv6",(e,t)=>{n9.init(e,t),lt.init(e,t)}),G4=W("ZodCIDRv4",(e,t)=>{o9.init(e,t),lt.init(e,t)}),K4=W("ZodCIDRv6",(e,t)=>{s9.init(e,t),lt.init(e,t)}),zh=W("ZodBase64",(e,t)=>{a9.init(e,t),lt.init(e,t)});function Zh(e){return xh(zh,e)}const Y4=W("ZodBase64URL",(e,t)=>{l9.init(e,t),lt.init(e,t)}),Q4=W("ZodE164",(e,t)=>{c9.init(e,t),lt.init(e,t)}),X4=W("ZodJWT",(e,t)=>{d9.init(e,t),lt.init(e,t)}),ic=W("ZodNumber",(e,t)=>{fh.init(e,t),et.init(e,t),e.gt=(n,o)=>e.check(Rh(n,o)),e.gte=(n,o)=>e.check(ac(n,o)),e.min=(n,o)=>e.check(ac(n,o)),e.lt=(n,o)=>e.check($h(n,o)),e.lte=(n,o)=>e.check(sc(n,o)),e.max=(n,o)=>e.check(sc(n,o)),e.int=n=>e.check(Fh(n)),e.safe=n=>e.check(Fh(n)),e.positive=n=>e.check(Rh(0,n)),e.nonnegative=n=>e.check(ac(0,n)),e.negative=n=>e.check($h(0,n)),e.nonpositive=n=>e.check(sc(0,n)),e.multipleOf=(n,o)=>e.check(Ph(n,o)),e.step=(n,o)=>e.check(Ph(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function j(e){return a4(ic,e)}const ek=W("ZodNumberFormat",(e,t)=>{p9.init(e,t),ic.init(e,t)});function Fh(e){return l4(ek,e)}const tk=W("ZodBoolean",(e,t)=>{f9.init(e,t),et.init(e,t)});function me(e){return c4(tk,e)}const rk=W("ZodNull",(e,t)=>{h9.init(e,t),et.init(e,t)});function ki(e){return u4(rk,e)}const nk=W("ZodAny",(e,t)=>{m9.init(e,t),et.init(e,t)});function bt(){return d4(nk)}const ok=W("ZodUnknown",(e,t)=>{g9.init(e,t),et.init(e,t)});function Me(){return p4(ok)}const sk=W("ZodNever",(e,t)=>{y9.init(e,t),et.init(e,t)});function ak(e){return f4(sk,e)}const ik=W("ZodArray",(e,t)=>{v9.init(e,t),et.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(_i(r,n)),e.nonempty=r=>e.check(_i(1,r)),e.max=(r,n)=>e.check(Mh(r,n)),e.length=(r,n)=>e.check(Oh(r,n)),e.unwrap=()=>e.element});function q(e,t){return C4(ik,e,t)}const Vh=W("ZodObject",(e,t)=>{gh.init(e,t),et.init(e,t),Ve(e,"shape",()=>t.shape),e.keyof=()=>we(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Me()}),e.loose=()=>e.clone({...e._zod.def,catchall:Me()}),e.strict=()=>e.clone({...e._zod.def,catchall:ak()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Hb(e,r),e.merge=r=>Bb(e,r),e.pick=r=>Fb(e,r),e.omit=r=>Vb(e,r),e.partial=(...r)=>Jb(Jh,e,r[0]),e.required=(...r)=>Wb(Gh,e,r[0])});function C(e,t){const r={type:"object",get shape(){return ls(this,"shape",{...e}),this.shape},...fe(t)};return new Vh(r)}function ct(e,t){return new Vh({type:"object",get shape(){return ls(this,"shape",{...e}),this.shape},catchall:Me(),...fe(t)})}const Hh=W("ZodUnion",(e,t)=>{vh.init(e,t),et.init(e,t),e.options=t.options});function oe(e,t){return new Hh({type:"union",options:e,...fe(t)})}const lk=W("ZodDiscriminatedUnion",(e,t)=>{Hh.init(e,t),_9.init(e,t)});function ze(e,t,r){return new lk({type:"union",options:t,discriminator:e,...fe(r)})}const ck=W("ZodIntersection",(e,t)=>{w9.init(e,t),et.init(e,t)});function lc(e,t){return new ck({type:"intersection",left:e,right:t})}const uk=W("ZodRecord",(e,t)=>{b9.init(e,t),et.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ye(e,t,r){return new uk({type:"record",keyType:e,valueType:t,...fe(r)})}const cc=W("ZodEnum",(e,t)=>{k9.init(e,t),et.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new cc({...t,checks:[],...fe(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new cc({...t,checks:[],...fe(o),entries:s})}});function we(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new cc({type:"enum",entries:r,...fe(t)})}const dk=W("ZodLiteral",(e,t)=>{T9.init(e,t),et.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function $(e,t){return new dk({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const pk=W("ZodTransform",(e,t)=>{C9.init(e,t),et.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ps(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(ps(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Bh(e){return new pk({type:"transform",transform:e})}const Jh=W("ZodOptional",(e,t)=>{S9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pe(e){return new Jh({type:"optional",innerType:e})}const fk=W("ZodNullable",(e,t)=>{I9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Wh(e){return new fk({type:"nullable",innerType:e})}const hk=W("ZodDefault",(e,t)=>{E9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function mk(e,t){return new hk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const gk=W("ZodPrefault",(e,t)=>{x9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType});function yk(e,t){return new gk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Gh=W("ZodNonOptional",(e,t)=>{$9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType});function vk(e,t){return new Gh({type:"nonoptional",innerType:e,...fe(t)})}const _k=W("ZodCatch",(e,t)=>{R9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function wk(e,t){return new _k({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const bk=W("ZodPipe",(e,t)=>{P9.init(e,t),et.init(e,t),e.in=t.in,e.out=t.out});function uc(e,t){return new bk({type:"pipe",in:e,out:t})}const kk=W("ZodReadonly",(e,t)=>{M9.init(e,t),et.init(e,t)});function Tk(e){return new kk({type:"readonly",innerType:e})}const Ck=W("ZodLazy",(e,t)=>{O9.init(e,t),et.init(e,t),e.unwrap=()=>e._zod.def.getter()});function dc(e){return new Ck({type:"lazy",getter:e})}const pc=W("ZodCustom",(e,t)=>{N9.init(e,t),et.init(e,t)});function Sk(e){const t=new Vt({check:"custom"});return t._zod.check=e,t}function Kh(e,t){return S4(pc,e??(()=>!0),t)}function Ik(e,t={}){return I4(pc,e,t)}function Ek(e){const t=Sk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ps(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(ps(o))}},e(r.value,r)));return t}function Ti(e,t={error:`Input not instance of ${e.name}`}){const r=new pc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...fe(t)});return r._zod.bag.Class=e,r}function Yh(e,t){return uc(Bh(e),t)}const Qh={custom:"custom"};function Xh(e){return i4(ic,e)}const ms="2025-11-25",em=[ms,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],zn="io.modelcontextprotocol/related-task",Ci="2.0",Et=Kh(e=>e!==null&&(typeof e=="object"||typeof e=="function")),tm=oe([d(),j().int()]),rm=d();ct({ttl:oe([j(),ki()]).optional(),pollInterval:j().optional()});const xk=C({ttl:j().optional()}),$k=C({taskId:d()}),fc=ct({progressToken:tm.optional(),[zn]:$k.optional()}),Xt=C({_meta:fc.optional()}),gs=Xt.extend({task:xk.optional()}),Rk=e=>gs.safeParse(e).success,xt=C({method:d(),params:Xt.loose().optional()}),ar=C({_meta:fc.optional()}),ir=C({method:d(),params:ar.loose().optional()}),$t=ct({_meta:fc.optional()}),Si=oe([d(),j().int()]),nm=C({jsonrpc:$(Ci),id:Si,...xt.shape}).strict(),hc=e=>nm.safeParse(e).success,om=C({jsonrpc:$(Ci),...ir.shape}).strict(),Pk=e=>om.safeParse(e).success,mc=C({jsonrpc:$(Ci),id:Si,result:$t}).strict(),ys=e=>mc.safeParse(e).success;var de;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(de||(de={}));const gc=C({jsonrpc:$(Ci),id:Si.optional(),error:C({code:j().int(),message:d(),data:Me().optional()})}).strict(),Mk=e=>gc.safeParse(e).success,Kr=oe([nm,om,mc,gc]);oe([mc,gc]);const vn=$t.strict(),Ok=ar.extend({requestId:Si.optional(),reason:d().optional()}),yc=ir.extend({method:$("notifications/cancelled"),params:Ok}),Nk=C({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:we(["light","dark"]).optional()}),vs=C({icons:q(Nk).optional()}),ho=C({name:d(),title:d().optional()}),sm=ho.extend({...ho.shape,...vs.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),Ak=lc(C({applyDefaults:me().optional()}),ye(d(),Me())),qk=Yh(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lc(C({form:Ak.optional(),url:Et.optional()}),ye(d(),Me()).optional())),Lk=ct({list:Et.optional(),cancel:Et.optional(),requests:ct({sampling:ct({createMessage:Et.optional()}).optional(),elicitation:ct({create:Et.optional()}).optional()}).optional()}),jk=ct({list:Et.optional(),cancel:Et.optional(),requests:ct({tools:ct({call:Et.optional()}).optional()}).optional()}),Dk=C({experimental:ye(d(),Et).optional(),sampling:C({context:Et.optional(),tools:Et.optional()}).optional(),elicitation:qk.optional(),roots:C({listChanged:me().optional()}).optional(),tasks:Lk.optional()}),Uk=Xt.extend({protocolVersion:d(),capabilities:Dk,clientInfo:sm}),am=xt.extend({method:$("initialize"),params:Uk}),zk=C({experimental:ye(d(),Et).optional(),logging:Et.optional(),completions:Et.optional(),prompts:C({listChanged:me().optional()}).optional(),resources:C({subscribe:me().optional(),listChanged:me().optional()}).optional(),tools:C({listChanged:me().optional()}).optional(),tasks:jk.optional()}),im=$t.extend({protocolVersion:d(),capabilities:zk,serverInfo:sm,instructions:d().optional()}),vc=ir.extend({method:$("notifications/initialized"),params:ar.optional()}),Zk=e=>vc.safeParse(e).success,_c=xt.extend({method:$("ping"),params:Xt.optional()}),Fk=C({progress:j(),total:pe(j()),message:pe(d())}),Vk=C({...ar.shape,...Fk.shape,progressToken:tm}),wc=ir.extend({method:$("notifications/progress"),params:Vk}),Hk=Xt.extend({cursor:rm.optional()}),_s=xt.extend({params:Hk.optional()}),ws=$t.extend({nextCursor:rm.optional()}),Bk=we(["working","input_required","completed","failed","cancelled"]),bs=C({taskId:d(),status:Bk,ttl:oe([j(),ki()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:pe(j()),statusMessage:pe(d())}),mo=$t.extend({task:bs}),Jk=ar.merge(bs),Ii=ir.extend({method:$("notifications/tasks/status"),params:Jk}),bc=xt.extend({method:$("tasks/get"),params:Xt.extend({taskId:d()})}),kc=$t.merge(bs),Tc=xt.extend({method:$("tasks/result"),params:Xt.extend({taskId:d()})});$t.loose();const Cc=_s.extend({method:$("tasks/list")}),Sc=ws.extend({tasks:q(bs)}),Ic=xt.extend({method:$("tasks/cancel"),params:Xt.extend({taskId:d()})}),Wk=$t.merge(bs),lm=C({uri:d(),mimeType:pe(d()),_meta:ye(d(),Me()).optional()}),cm=lm.extend({text:d()}),Ec=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),um=lm.extend({blob:Ec}),ks=we(["user","assistant"]),go=C({audience:q(ks).optional(),priority:j().min(0).max(1).optional(),lastModified:qh({offset:!0}).optional()}),dm=C({...ho.shape,...vs.shape,uri:d(),description:pe(d()),mimeType:pe(d()),annotations:go.optional(),_meta:pe(ct({}))}),Gk=C({...ho.shape,...vs.shape,uriTemplate:d(),description:pe(d()),mimeType:pe(d()),annotations:go.optional(),_meta:pe(ct({}))}),Ei=_s.extend({method:$("resources/list")}),pm=ws.extend({resources:q(dm)}),xc=_s.extend({method:$("resources/templates/list")}),fm=ws.extend({resourceTemplates:q(Gk)}),$c=Xt.extend({uri:d()}),Kk=$c,Rc=xt.extend({method:$("resources/read"),params:Kk}),hm=$t.extend({contents:q(oe([cm,um]))}),Pc=ir.extend({method:$("notifications/resources/list_changed"),params:ar.optional()}),Yk=$c,mm=xt.extend({method:$("resources/subscribe"),params:Yk}),Qk=$c,gm=xt.extend({method:$("resources/unsubscribe"),params:Qk}),Xk=ar.extend({uri:d()}),ym=ir.extend({method:$("notifications/resources/updated"),params:Xk}),eT=C({name:d(),description:pe(d()),required:pe(me())}),tT=C({...ho.shape,...vs.shape,description:pe(d()),arguments:pe(q(eT)),_meta:pe(ct({}))}),Mc=_s.extend({method:$("prompts/list")}),vm=ws.extend({prompts:q(tT)}),rT=Xt.extend({name:d(),arguments:ye(d(),d()).optional()}),Oc=xt.extend({method:$("prompts/get"),params:rT}),Nc=C({type:$("text"),text:d(),annotations:go.optional(),_meta:ye(d(),Me()).optional()}),Ac=C({type:$("image"),data:Ec,mimeType:d(),annotations:go.optional(),_meta:ye(d(),Me()).optional()}),qc=C({type:$("audio"),data:Ec,mimeType:d(),annotations:go.optional(),_meta:ye(d(),Me()).optional()}),nT=C({type:$("tool_use"),name:d(),id:d(),input:ye(d(),Me()),_meta:ye(d(),Me()).optional()}),oT=C({type:$("resource"),resource:oe([cm,um]),annotations:go.optional(),_meta:ye(d(),Me()).optional()}),sT=dm.extend({type:$("resource_link")}),Lc=oe([Nc,Ac,qc,sT,oT]),aT=C({role:ks,content:Lc}),_m=$t.extend({description:d().optional(),messages:q(aT)}),jc=ir.extend({method:$("notifications/prompts/list_changed"),params:ar.optional()}),iT=C({title:d().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),lT=C({taskSupport:we(["required","optional","forbidden"]).optional()}),wm=C({...ho.shape,...vs.shape,description:d().optional(),inputSchema:C({type:$("object"),properties:ye(d(),Et).optional(),required:q(d()).optional()}).catchall(Me()),outputSchema:C({type:$("object"),properties:ye(d(),Et).optional(),required:q(d()).optional()}).catchall(Me()).optional(),annotations:iT.optional(),execution:lT.optional(),_meta:ye(d(),Me()).optional()}),Dc=_s.extend({method:$("tools/list")}),bm=ws.extend({tools:q(wm)}),yo=$t.extend({content:q(Lc).default([]),structuredContent:ye(d(),Me()).optional(),isError:me().optional()});yo.or($t.extend({toolResult:Me()}));const cT=gs.extend({name:d(),arguments:ye(d(),Me()).optional()}),xi=xt.extend({method:$("tools/call"),params:cT}),Uc=ir.extend({method:$("notifications/tools/list_changed"),params:ar.optional()}),uT=C({autoRefresh:me().default(!0),debounceMs:j().int().nonnegative().default(300)}),$i=we(["debug","info","notice","warning","error","critical","alert","emergency"]),dT=Xt.extend({level:$i}),Ri=xt.extend({method:$("logging/setLevel"),params:dT}),pT=ar.extend({level:$i,logger:d().optional(),data:Me()}),km=ir.extend({method:$("notifications/message"),params:pT}),fT=C({name:d().optional()}),hT=C({hints:q(fT).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),mT=C({mode:we(["auto","required","none"]).optional()}),gT=C({type:$("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Lc).default([]),structuredContent:C({}).loose().optional(),isError:me().optional(),_meta:ye(d(),Me()).optional()}),yT=ze("type",[Nc,Ac,qc]),Pi=ze("type",[Nc,Ac,qc,nT,gT]),vT=C({role:ks,content:oe([Pi,q(Pi)]),_meta:ye(d(),Me()).optional()}),_T=gs.extend({messages:q(vT),modelPreferences:hT.optional(),systemPrompt:d().optional(),includeContext:we(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:Et.optional(),tools:q(wm).optional(),toolChoice:mT.optional()}),zc=xt.extend({method:$("sampling/createMessage"),params:_T}),Mi=$t.extend({model:d(),stopReason:pe(we(["endTurn","stopSequence","maxTokens"]).or(d())),role:ks,content:yT}),Zc=$t.extend({model:d(),stopReason:pe(we(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:ks,content:oe([Pi,q(Pi)])}),wT=C({type:$("boolean"),title:d().optional(),description:d().optional(),default:me().optional()}),bT=C({type:$("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:we(["email","uri","date","date-time"]).optional(),default:d().optional()}),kT=C({type:we(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),TT=C({type:$("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),CT=C({type:$("string"),title:d().optional(),description:d().optional(),oneOf:q(C({const:d(),title:d()})),default:d().optional()}),ST=C({type:$("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),IT=oe([TT,CT]),ET=C({type:$("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:C({type:$("string"),enum:q(d())}),default:q(d()).optional()}),xT=C({type:$("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:C({anyOf:q(C({const:d(),title:d()}))}),default:q(d()).optional()}),$T=oe([ET,xT]),RT=oe([ST,IT,$T]),PT=oe([RT,wT,bT,kT]),MT=gs.extend({mode:$("form").optional(),message:d(),requestedSchema:C({type:$("object"),properties:ye(d(),PT),required:q(d()).optional()})}),OT=gs.extend({mode:$("url"),message:d(),elicitationId:d(),url:d().url()}),NT=oe([MT,OT]),Fc=xt.extend({method:$("elicitation/create"),params:NT}),AT=ar.extend({elicitationId:d()}),qT=ir.extend({method:$("notifications/elicitation/complete"),params:AT}),Ts=$t.extend({action:we(["accept","decline","cancel"]),content:Yh(e=>e===null?void 0:e,ye(d(),oe([d(),j(),me(),q(d())])).optional())}),LT=C({type:$("ref/resource"),uri:d()}),jT=C({type:$("ref/prompt"),name:d()}),DT=Xt.extend({ref:oe([jT,LT]),argument:C({name:d(),value:d()}),context:C({arguments:ye(d(),d()).optional()}).optional()}),Vc=xt.extend({method:$("completion/complete"),params:DT});function UT(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function zT(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Tm=$t.extend({completion:ct({values:q(d()).max(100),total:pe(j().int()),hasMore:pe(me())})}),ZT=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ye(d(),Me()).optional()}),Cm=xt.extend({method:$("roots/list"),params:Xt.optional()}),Hc=$t.extend({roots:q(ZT)}),Sm=ir.extend({method:$("notifications/roots/list_changed"),params:ar.optional()});oe([_c,am,Vc,Ri,Oc,Mc,Ei,xc,Rc,mm,gm,xi,Dc,bc,Tc,Cc,Ic]),oe([yc,wc,vc,Sm,Ii]),oe([vn,Mi,Zc,Ts,Hc,kc,Sc,mo]),oe([_c,zc,Fc,Cm,bc,Tc,Cc,Ic]),oe([yc,wc,km,ym,Pc,Uc,jc,Ii,qT]),oe([vn,im,Tm,_m,vm,pm,fm,hm,yo,bm,kc,Sc,mo]);class ie extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===de.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new FT(o.elicitations,r)}return new ie(t,r,n)}}class FT extends ie{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(de.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const VT=W("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ke.init(e,t),e.def=t,e.parse=(r,n)=>Yb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>tc(e,r,n),e.parseAsync=async(r,n)=>Qb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>rc(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>gn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),HT=W("ZodMiniObject",(e,t)=>{gh.init(e,t),VT.init(e,t),Ve(e,"shape",()=>t.shape)});function Im(e,t){const r={type:"object",get shape(){return ls(this,"shape",{...e}),this.shape},...fe(t)};return new HT(r)}function yr(e){return!!e._zod}function vo(e){const t=Object.values(e);if(t.length===0)return Im({});const r=t.every(yr),n=t.every(o=>!yr(o));if(r)return Im(e);if(n)return Ft(e);throw new Error("Mixed Zod versions detected in object shape.")}function vr(e,t){return yr(e)?tc(e,t):e.safeParse(t)}async function Bc(e,t){return yr(e)?await rc(e,t):await e.safeParseAsync(t)}function _o(e){if(!e)return;let t;if(yr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Cs(e){if(e){if(typeof e=="object"){const t=e,r=e;if(!t._def&&!r._zod){const n=Object.values(e);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return vo(e)}}if(yr(e)){const r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Jc(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function BT(e){return e.description}function JT(e){if(yr(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Em(e){if(yr(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._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=e.value;if(n!==void 0)return n}function Zn(e){return e==="completed"||e==="failed"||e==="cancelled"}const WT=Symbol("Let zodToJsonSchema decide on which parser to use"),xm={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"},GT=e=>typeof e=="string"?{...xm,name:e}:{...xm,...e},KT=e=>{const t=GT(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function $m(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Je(e,t,r,n,o){e[t]=r,$m(e,t,n,o)}const Rm=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ht(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Rm(t,e.currentPath):t.join("/")}}function YT(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(r.items=He(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Je(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Je(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Je(r,"minItems",e.exactLength.value,e.exactLength.message,t),Je(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function QT(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Je(r,"minimum",n.value,n.message,t):Je(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Je(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Je(r,"maximum",n.value,n.message,t):Je(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Je(r,"maximum",n.value,n.message,t));break;case"multipleOf":Je(r,"multipleOf",n.value,n.message,t);break}return r}function XT(){return{type:"boolean"}}function Pm(e,t){return He(e.type._def,t)}const eC=(e,t)=>He(e.innerType._def,t);function Mm(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Mm(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tC(e,t)}}const tC=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Je(r,"minimum",n.value,n.message,t);break;case"max":Je(r,"maximum",n.value,n.message,t);break}return r};function rC(e,t){return{...He(e.innerType._def,t),default:e.defaultValue()}}function nC(e,t){return t.effectStrategy==="input"?He(e.schema._def,t):Ht(t)}function oC(e){return{type:"string",enum:Array.from(e.values)}}const sC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function aC(e,t){const r=[He(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),He(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(s=>{if(sC(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function iC(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let Wc;const _r={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:()=>(Wc===void 0&&(Wc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wc),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 Om(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":Je(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Je(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":wr(r,"email",n.message,t);break;case"format:idn-email":wr(r,"idn-email",n.message,t);break;case"pattern:zod":Dt(r,_r.email,n.message,t);break}break;case"url":wr(r,"uri",n.message,t);break;case"uuid":wr(r,"uuid",n.message,t);break;case"regex":Dt(r,n.regex,n.message,t);break;case"cuid":Dt(r,_r.cuid,n.message,t);break;case"cuid2":Dt(r,_r.cuid2,n.message,t);break;case"startsWith":Dt(r,RegExp(`^${Gc(n.value,t)}`),n.message,t);break;case"endsWith":Dt(r,RegExp(`${Gc(n.value,t)}$`),n.message,t);break;case"datetime":wr(r,"date-time",n.message,t);break;case"date":wr(r,"date",n.message,t);break;case"time":wr(r,"time",n.message,t);break;case"duration":wr(r,"duration",n.message,t);break;case"length":Je(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Je(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Dt(r,RegExp(Gc(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&wr(r,"ipv4",n.message,t),n.version!=="v4"&&wr(r,"ipv6",n.message,t);break}case"base64url":Dt(r,_r.base64url,n.message,t);break;case"jwt":Dt(r,_r.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Dt(r,_r.ipv4Cidr,n.message,t),n.version!=="v4"&&Dt(r,_r.ipv6Cidr,n.message,t);break}case"emoji":Dt(r,_r.emoji(),n.message,t);break;case"ulid":{Dt(r,_r.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{wr(r,"binary",n.message,t);break}case"contentEncoding:base64":{Je(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Dt(r,_r.base64,n.message,t);break}}break}case"nanoid":Dt(r,_r.nanoid,n.message,t)}return r}function Gc(e,t){return t.patternStrategy==="escape"?cC(e):e}const lC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function cC(e){let t="";for(let r=0;r<e.length;r++)lC.has(e[r])||(t+="\\"),t+=e[r];return t}function wr(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Je(e,"format",t,r,n)}function Dt(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Nm(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Je(e,"pattern",Nm(t,n),r,n)}function Nm(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(a){if(n[l].match(/[a-z]/)){i?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],i=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
36
+ ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
37
+ ]))`;continue}}if(r.s&&n[l]==="."){o+=a?`${n[l]}\r
38
+ `:`[${n[l]}\r
39
+ ]`;continue}o+=n[l],n[l]==="\\"?s=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Am(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===B.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ht(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===B.ZodString&&e.keyType._def.checks?.length){const{type:n,...o}=Om(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===B.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===B.ZodBranded&&e.keyType._def.type._def.typeName===B.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...o}=Pm(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function uC(e,t){if(t.mapStrategy==="record")return Am(e,t);const r=He(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ht(t),n=He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ht(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function dC(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function pC(e){return e.target==="openAi"?void 0:{not:Ht({...e,currentPath:[...e.currentPath,"not"]})}}function fC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Oi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hC(e,t){if(t.target==="openApi3")return qm(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Oi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Oi[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return qm(e,t)}const qm=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>He(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function mC(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Oi[e.innerType._def.typeName],nullable:!0}:{type:[Oi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=He(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function gC(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",$m(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Je(r,"minimum",n.value,n.message,t):Je(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Je(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Je(r,"maximum",n.value,n.message,t):Je(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Je(r,"maximum",n.value,n.message,t));break;case"multipleOf":Je(r,"multipleOf",n.value,n.message,t);break}return r}function yC(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=_C(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=He(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||o.push(i))}o.length&&(n.required=o);const a=vC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function vC(e,t){if(e.catchall._def.typeName!=="ZodNever")return He(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function _C(e){try{return e.isOptional()}catch{return!0}}const wC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return He(e.innerType._def,t);const r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ht(t)},r]}:Ht(t)},bC=(e,t)=>{if(t.pipeStrategy==="input")return He(e.in._def,t);if(t.pipeStrategy==="output")return He(e.out._def,t);const r=He(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=He(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function kC(e,t){return He(e.type._def,t)}function TC(e,t){const n={type:"array",uniqueItems:!0,items:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Je(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Je(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function CC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:He(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function SC(e){return{not:Ht(e)}}function IC(e){return Ht(e)}const EC=(e,t)=>He(e.innerType._def,t),xC=(e,t,r)=>{switch(t){case B.ZodString:return Om(e,r);case B.ZodNumber:return gC(e,r);case B.ZodObject:return yC(e,r);case B.ZodBigInt:return QT(e,r);case B.ZodBoolean:return XT();case B.ZodDate:return Mm(e,r);case B.ZodUndefined:return SC(r);case B.ZodNull:return fC(r);case B.ZodArray:return YT(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return hC(e,r);case B.ZodIntersection:return aC(e,r);case B.ZodTuple:return CC(e,r);case B.ZodRecord:return Am(e,r);case B.ZodLiteral:return iC(e,r);case B.ZodEnum:return oC(e);case B.ZodNativeEnum:return dC(e);case B.ZodNullable:return mC(e,r);case B.ZodOptional:return wC(e,r);case B.ZodMap:return uC(e,r);case B.ZodSet:return TC(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return kC(e,r);case B.ZodNaN:case B.ZodNever:return pC(r);case B.ZodEffects:return nC(e,r);case B.ZodAny:return Ht(r);case B.ZodUnknown:return IC(r);case B.ZodDefault:return rC(e,r);case B.ZodBranded:return Pm(e,r);case B.ZodReadonly:return EC(e,r);case B.ZodCatch:return eC(e,r);case B.ZodPipeline:return bC(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}};function He(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==WT)return i}if(n&&!r){const i=$C(n,t);if(i!==void 0)return i}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=xC(e,e.typeName,t),a=typeof s=="function"?He(s(),t):s;if(a&&RC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const $C=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rm(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ht(t)):t.$refStrategy==="seen"?Ht(t):void 0}},RC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),PC=(e,t)=>{const r=KT(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:He(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ht(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=He(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ht(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a),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 i=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function MC(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Lm(e,t){return yr(e)?Ah(e,{target:MC(t?.target),io:t?.pipeStrategy??"input"}):PC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function jm(e){const r=_o(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Em(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Dm(e,t){const r=vr(e,t);if(!r.success)throw r.error;return r.data}const OC=6e4;class Um{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(yc,r=>{this._oncancel(r)}),this.setNotificationHandler(wc,r=>{this._onprogress(r)}),this.setRequestHandler(_c,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(bc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ie(de.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Tc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const h=l,p=new ie(h.error.code,h.error.message,h.error.data);u(p)}else{const h=i.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new ie(de.InvalidParams,`Task not found: ${s}`);if(!Zn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Zn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[zn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Cc,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new ie(de.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ic,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ie(de.InvalidParams,`Task not found: ${r.params.taskId}`);if(Zn(o.status))throw new ie(de.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ie(de.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ie?o:new ie(de.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ie.fromError(de.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),ys(s)||Mk(s)?this._onresponse(s):hc(s)?this._onrequest(s,a):Pk(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=ie.fromError(de.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[zn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:de.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=Rk(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const h={relatedRequestId:t.id};s&&(h.relatedTask={taskId:s}),await this.notification(u,h)},sendRequest:async(u,h,p)=>{const f={...p,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});const g=f.relatedTask?.taskId??s;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(u,h,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async u=>{if(a.signal.aborted)return;const h={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:de.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ys(t))n(t);else{const a=new ie(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(ys(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),ys(t))o(t);else{const a=ie.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof ie?a:new ie(de.InternalError,String(a))}}return}let s;try{const a=await this.request(t,mo,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ie(de.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Zn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ie(de.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ie(de.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ie?a:new ie(de.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const h=v=>{u(v)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(v){h(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[zn]:l}});const g=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));const m=v instanceof ie?v:new ie(de.RequestTimeout,String(v));u(m)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const m=vr(r,v.result);m.success?c(m.data):u(m.error)}catch(m){u(m)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});const _=n?.timeout??OC,y=()=>g(ie.fromError(de.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const v=m=>{const S=this._responseHandlers.get(p);S?S(m):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(m=>{this._cleanupTimeout(p),u(m)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(p),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},kc,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Sc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Wk,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[zn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[zn]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[zn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=jm(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Dm(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=jm(t);this._notificationHandlers.set(n,o=>{const s=Dm(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&hc(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ie(de.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ie(de.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ie(de.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ie(de.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Ii.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Zn(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new ie(de.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zn(i.status))throw new ie(de.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Ii.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Zn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function zm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Zm(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];zm(a)&&zm(s)?r[o]={...a,...s}:r[o]=s}return r}var Ni={exports:{}},Kc={},Fm;function NC(){return Fm||(Fm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,A){return{validate:O,compare:A}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),f),"iso-time":t(l(),u),"iso-date-time":t(p(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"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:L,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:T},int64:{type:"number",validate:b},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\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,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\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,g),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},e.formatNames=Object.keys(e.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(O){const A=n.exec(O);if(!A)return!1;const N=+A[1],U=+A[2],G=+A[3];return U>=1&&U<=12&&G>=1&&G<=(U===2&&r(N)?29:o[U])}function a(O,A){if(O&&A)return O>A?1:O<A?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(N){const U=i.exec(N);if(!U)return!1;const G=+U[1],J=+U[2],ue=+U[3],re=U[4],ge=U[5]==="-"?-1:1,V=+(U[6]||0),R=+(U[7]||0);if(V>23||R>59||O&&!re)return!1;if(G<=23&&J<=59&&ue<60)return!0;const H=J-R*ge,Z=G-V*ge-(H<0?1:0);return(Z===23||Z===-1)&&(H===59||H===-1)&&ue<61}}function c(O,A){if(!(O&&A))return;const N=new Date("2020-01-01T"+O).valueOf(),U=new Date("2020-01-01T"+A).valueOf();if(N&&U)return N-U}function u(O,A){if(!(O&&A))return;const N=i.exec(O),U=i.exec(A);if(N&&U)return O=N[1]+N[2]+N[3],A=U[1]+U[2]+U[3],O>A?1:O<A?-1:0}const h=/t|\s/i;function p(O){const A=l(O);return function(U){const G=U.split(h);return G.length===2&&s(G[0])&&A(G[1])}}function f(O,A){if(!(O&&A))return;const N=new Date(O).valueOf(),U=new Date(A).valueOf();if(N&&U)return N-U}function g(O,A){if(!(O&&A))return;const[N,U]=O.split(h),[G,J]=A.split(h),ue=a(N,G);if(ue!==void 0)return ue||c(U,J)}const _=/\/|:/,y=/^(?:[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 w(O){return _.test(O)&&y.test(O)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(O){return v.lastIndex=0,v.test(O)}const S=-2147483648,k=2**31-1;function T(O){return Number.isInteger(O)&&O<=k&&O>=S}function b(O){return Number.isInteger(O)}function x(){return!0}const I=/[^\\]\\Z/;function L(O){if(I.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(Kc)),Kc}var Yc={},Vm;function AC(){return Vm||(Vm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Af(),r=Ae(),n=r.operators,o={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}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:h,it:p}=i,{opts:f,self:g}=p;if(!f.validateFormats)return;const _=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");_.$data?y():w();function y(){const m=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),S=l.const("fmt",(0,r._)`${m}[${_.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,v(S)))}function w(){const m=_.schema,S=g.formats[m];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${h}": format "${m}" does not define "compare" function`);const k=l.scopeValue("formats",{key:m,ref:S,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(m)}`:void 0});i.fail$data(v(k))}function v(m){return(0,r._)`${m}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(Yc)),Yc}var Hm;function qC(){return Hm||(Hm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=NC(),n=AC(),o=Ae(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[h,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],f=u.formats||r.formatNames;return l(c,f,h,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,h,p){var f,g;(f=(g=c.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const _ of u)c.addFormat(_,h[_])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(Ni,Ni.exports)),Ni.exports}var LC=qC();const jC=Pn(LC);function DC(){const e=new qf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return jC(e),e}class Bm{constructor(t){this._ajv=t??DC()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class UC{constructor(t){this._client=t}async*callToolStream(t,r=yo,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ie(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new ie(de.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ie){yield{type:"error",error:u};return}yield{type:"error",error:new ie(de.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function Jm(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function Wm(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function Ai(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Ai(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Ai(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Ai(r,t)}}function zC(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Ss extends Um{constructor(t,r){super(r),this._clientInfo=t,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 Bm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Uc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",jc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Pc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new UC(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zm(this._capabilities,t)}setRequestHandler(t,r){const o=_o(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(yr(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=vr(Fc,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new ie(de.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=zC(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new ie(de.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!f)throw new ie(de.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(h.task){const v=vr(mo,g);if(!v.success){const m=v.error instanceof Error?v.error.message:String(v.error);throw new ie(de.InvalidParams,`Invalid task creation result: ${m}`)}return v.data}const _=vr(Ts,g);if(!_.success){const v=_.error instanceof Error?_.error.message:String(_.error);throw new ie(de.InvalidParams,`Invalid elicitation result: ${v}`)}const y=_.data,w=h.mode==="form"?h.requestedSchema:void 0;if(h.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ai(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=vr(zc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ie(de.InvalidParams,`Invalid sampling request: ${y}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const y=vr(mo,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ie(de.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=h.tools||h.toolChoice?Zc:Mi,_=vr(g,p);if(!_.success){const y=_.error instanceof Error?_.error.message:String(_.error);throw new ie(de.InvalidParams,`Invalid sampling result: ${y}`)}return _.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:ms,capabilities:this._capabilities,clientInfo:this._clientInfo}},im,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!em.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.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(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);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 ${t})`);break}}assertTaskCapability(t){Jm(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Wm(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},vn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Tm,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},vn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},_m,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},vm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},pm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},fm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},hm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},vn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},vn,r)}async callTool(t,r=yo,n){if(this.isToolTaskRequired(t.name))throw new ie(de.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ie(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new ie(de.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ie?a:new ie(de.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},bm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=uT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const h=await o();l(null,h)}catch(h){const p=h instanceof Error?h:new Error(String(h));l(p,null)}},u=()=>{if(i){const h=this._listChangedDebounceTimers.get(t);h&&clearTimeout(h);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Gm extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Qc(e){}function Km(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Qc,onError:r=Qc,onRetry:n=Qc,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(_){const y=a?_.replace(/^\xEF\xBB\xBF/,""):_,[w,v]=ZC(`${s}${y}`);for(const m of w)h(m);s=v,a=!1}function h(_){if(_===""){f();return}if(_.startsWith(":")){o&&o(_.slice(_.startsWith(": ")?2:1));return}const y=_.indexOf(":");if(y!==-1){const w=_.slice(0,y),v=_[y+1]===" "?2:1,m=_.slice(y+v);p(w,m,_);return}p(_,"",_)}function p(_,y,w){switch(_){case"event":c=y;break;case"data":l=`${l}${y}
40
+ `;break;case"id":i=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new Gm(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new Gm(`Unknown field "${_.length>20?`${_.slice(0,20)}…`:_}"`,{type:"unknown-field",field:_,value:y,line:w}));break}}function f(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
41
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function g(_={}){s&&_.consume&&h(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:g}}function ZC(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
42
+ `,n);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
43
+ `&&n++}}return[t,r]}class Ym extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(Qm(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Qm(this),r)}}function FC(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Xc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Xc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Xc(e.cause)}`:e.message:`${e}`}function Qm(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Xm=e=>{throw TypeError(e)},eu=(e,t,r)=>t.has(e)||Xm("Cannot "+r),Le=(e,t,r)=>(eu(e,t,"read from private field"),r?r.call(e):t.get(e)),wt=(e,t,r)=>t.has(e)?Xm("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),st=(e,t,r,n)=>(eu(e,t,"write to private field"),t.set(e,r),r),Yr=(e,t,r)=>(eu(e,t,"access private method"),r),Bt,Fn,wo,qi,Li,Is,bo,Es,_n,ko,To,Co,xs,br,tu,ru,nu,e0,ou,su,$s,au,iu;class ji extends EventTarget{constructor(t,r){var n,o;super(),wt(this,br),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,wt(this,Bt),wt(this,Fn),wt(this,wo),wt(this,qi),wt(this,Li),wt(this,Is),wt(this,bo),wt(this,Es,null),wt(this,_n),wt(this,ko),wt(this,To,null),wt(this,Co,null),wt(this,xs,null),wt(this,ru,async s=>{var a;Le(this,ko).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){Yr(this,br,$s).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?st(this,wo,new URL(s.url)):st(this,wo,void 0),c!==200){Yr(this,br,$s).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Yr(this,br,$s).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Le(this,Bt)===this.CLOSED)return;st(this,Bt,this.OPEN);const h=new Event("open");if((a=Le(this,xs))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){Yr(this,br,$s).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=i.getReader();let g=!0;do{const{done:_,value:y}=await f.read();y&&Le(this,ko).feed(p.decode(y,{stream:!_})),_&&(g=!1,Le(this,ko).reset(),Yr(this,br,au).call(this))}while(g)}),wt(this,nu,s=>{st(this,_n,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Yr(this,br,au).call(this,Xc(s))}),wt(this,ou,s=>{typeof s.id=="string"&&st(this,Es,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:Le(this,wo)?Le(this,wo).origin:Le(this,Fn).origin,lastEventId:s.id||""});Le(this,Co)&&(!s.event||s.event==="message")&&Le(this,Co).call(this,a),this.dispatchEvent(a)}),wt(this,su,s=>{st(this,Is,s)}),wt(this,iu,()=>{st(this,bo,void 0),Le(this,Bt)===this.CONNECTING&&Yr(this,br,tu).call(this)});try{if(t instanceof URL)st(this,Fn,t);else if(typeof t=="string")st(this,Fn,new URL(t,VC()));else throw new Error("Invalid URL")}catch{throw FC("An invalid or illegal string was specified")}st(this,ko,Km({onEvent:Le(this,ou),onRetry:Le(this,su)})),st(this,Bt,this.CONNECTING),st(this,Is,3e3),st(this,Li,(n=r?.fetch)!=null?n:globalThis.fetch),st(this,qi,(o=r?.withCredentials)!=null?o:!1),Yr(this,br,tu).call(this)}get readyState(){return Le(this,Bt)}get url(){return Le(this,Fn).href}get withCredentials(){return Le(this,qi)}get onerror(){return Le(this,To)}set onerror(t){st(this,To,t)}get onmessage(){return Le(this,Co)}set onmessage(t){st(this,Co,t)}get onopen(){return Le(this,xs)}set onopen(t){st(this,xs,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){Le(this,bo)&&clearTimeout(Le(this,bo)),Le(this,Bt)!==this.CLOSED&&(Le(this,_n)&&Le(this,_n).abort(),st(this,Bt,this.CLOSED),st(this,_n,void 0))}}Bt=new WeakMap,Fn=new WeakMap,wo=new WeakMap,qi=new WeakMap,Li=new WeakMap,Is=new WeakMap,bo=new WeakMap,Es=new WeakMap,_n=new WeakMap,ko=new WeakMap,To=new WeakMap,Co=new WeakMap,xs=new WeakMap,br=new WeakSet,tu=function(){st(this,Bt,this.CONNECTING),st(this,_n,new AbortController),Le(this,Li)(Le(this,Fn),Yr(this,br,e0).call(this)).then(Le(this,ru)).catch(Le(this,nu))},ru=new WeakMap,nu=new WeakMap,e0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Le(this,Es)?{"Last-Event-ID":Le(this,Es)}:void 0},cache:"no-store",signal:(e=Le(this,_n))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ou=new WeakMap,su=new WeakMap,$s=function(e,t){var r;Le(this,Bt)!==this.CLOSED&&st(this,Bt,this.CLOSED);const n=new Ym("error",{code:t,message:e});(r=Le(this,To))==null||r.call(this,n),this.dispatchEvent(n)},au=function(e,t){var r;if(Le(this,Bt)===this.CLOSED)return;st(this,Bt,this.CONNECTING);const n=new Ym("error",{code:t,message:e});(r=Le(this,To))==null||r.call(this,n),this.dispatchEvent(n),st(this,bo,setTimeout(Le(this,iu),Le(this,Is)))},iu=new WeakMap,ji.CONNECTING=0,ji.OPEN=1,ji.CLOSED=2;function VC(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function Di(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function t0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Di(t.headers),...Di(n.headers)}:t.headers};return e(r,o)}:e}let lu;lu=globalThis.crypto;async function HC(e){return(await lu).getRandomValues(new Uint8Array(e))}async function BC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await HC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function JC(e){return await BC(e)}async function WC(e){const t=await(await lu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function r0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await JC(e),r=await WC(t);return{code_verifier:t,code_challenge:r}}const Rt=D4().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Qh.custom,message:"URL must be parseable",fatal:!0}),Gf}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),GC=ct({resource:d().url(),authorization_servers:q(Rt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:me().optional()}),n0=ct({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,registration_endpoint:Rt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:Rt.optional(),revocation_endpoint:Rt.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:me().optional()}),KC=ct({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,userinfo_endpoint:Rt.optional(),jwks_uri:Rt,registration_endpoint:Rt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:me().optional(),request_parameter_supported:me().optional(),request_uri_parameter_supported:me().optional(),require_request_uri_registration:me().optional(),op_policy_uri:Rt.optional(),op_tos_uri:Rt.optional(),client_id_metadata_document_supported:me().optional()}),YC=C({...KC.shape,...n0.pick({code_challenge_methods_supported:!0}).shape}),QC=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Xh().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),XC=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),o0=Rt.optional().or($("").transform(()=>{})),eS=C({redirect_uris:q(Rt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Rt.optional(),logo_uri:o0,scope:d().optional(),contacts:q(d()).optional(),tos_uri:o0,policy_uri:d().optional(),jwks_uri:Rt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),tS=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),rS=eS.merge(tS);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function nS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function oS({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class kt extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class cu extends kt{}cu.errorCode="invalid_request";let Ui=class extends kt{};Ui.errorCode="invalid_client";let zi=class extends kt{};zi.errorCode="invalid_grant";let Zi=class extends kt{};Zi.errorCode="unauthorized_client";class uu extends kt{}uu.errorCode="unsupported_grant_type";class du extends kt{}du.errorCode="invalid_scope";class pu extends kt{}pu.errorCode="access_denied";let So=class extends kt{};So.errorCode="server_error";class fu extends kt{}fu.errorCode="temporarily_unavailable";class hu extends kt{}hu.errorCode="unsupported_response_type";class mu extends kt{}mu.errorCode="unsupported_token_type";class gu extends kt{}gu.errorCode="invalid_token";class yu extends kt{}yu.errorCode="method_not_allowed";class vu extends kt{}vu.errorCode="too_many_requests";class Fi extends kt{}Fi.errorCode="invalid_client_metadata";class _u extends kt{}_u.errorCode="insufficient_scope";class wu extends kt{}wu.errorCode="invalid_target";const sS={[cu.errorCode]:cu,[Ui.errorCode]:Ui,[zi.errorCode]:zi,[Zi.errorCode]:Zi,[uu.errorCode]:uu,[du.errorCode]:du,[pu.errorCode]:pu,[So.errorCode]:So,[fu.errorCode]:fu,[hu.errorCode]:hu,[mu.errorCode]:mu,[gu.errorCode]:gu,[yu.errorCode]:yu,[vu.errorCode]:vu,[Fi.errorCode]:Fi,[_u.errorCode]:_u,[wu.errorCode]:wu};let lr=class extends Error{constructor(t){super(t??"Unauthorized")}};function aS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const bu="code",ku="S256";function iS(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&aS(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function lS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":cS(o,s,r);return;case"client_secret_post":uS(o,s,n);return;case"none":dS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function cS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function uS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function dS(e,t){t.set("client_id",e)}async function s0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=XC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=sS[o]||So;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new So(o)}}async function Vn(e,t){try{return await Tu(e,t)}catch(r){if(r instanceof Ui||r instanceof Zi)return await e.invalidateCredentials?.("all"),await Tu(e,t);if(r instanceof zi)return await e.invalidateCredentials?.("tokens"),await Tu(e,t);throw r}}async function Tu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await hS(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await fS(t,e,a),c=await _S(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!pS(w))throw new Fi(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const m=await CS(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(m),u=m}}const h=!e.redirectUrl;if(r!==void 0||h){const y=await TS(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await kS(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof kt)||y instanceof So))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:_}=await wS(i,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(g),"REDIRECT"}function pS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function fS(e,t,r){const n=nS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!oS({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 Vi(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Cu(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=Cu(e,"scope")||void 0,i=Cu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Cu(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function hS(e,t,r=fetch){const n=await yS(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.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 GC.parse(await n.json())}async function Su(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Su(e,void 0,r):void 0;throw n}}function mS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function a0(e,t,r=fetch){return await Su(e,{"MCP-Protocol-Version":t},r)}function gS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function yS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ms;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=mS(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await a0(a,s,r);if(!n?.metadataUrl&&gS(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await a0(l,s,r)}return i}function vS(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function _S(e,{fetchFn:t=fetch,protocolVersion:r=ms}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=vS(e);for(const{url:s,type:a}of o){const i=await Su(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?n0.parse(await i.json()):YC.parse(await i.json())}}}async function wS(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(bu))throw new Error(`Incompatible auth server: does not support response type ${bu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ku))throw new Error(`Incompatible auth server: does not support code challenge method ${ku}`)}else i=new URL("/authorize",e);const l=await r0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",bu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",ku),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function bS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function i0(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],h=iS(n,u);lS(h,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await s0(c);return QC.parse(await c.json())}async function kS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await i0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function TS(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=bS(o,c,e.redirectUrl)}const l=await e.clientInformation();return i0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function CS(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await s0(s);return rS.parse(await s.json())}class SS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Rs{constructor(t,r){this._url=t,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=t0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new lr("No auth provider");let t;try{t=await Vn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new lr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Di(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new ji(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=Vi(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new SS(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=Kr.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}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(t){if(!this._authProvider)throw new lr("No auth provider");if(await Vn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new lr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){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(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=Vi(o);if(this._resourceMetadataUrl=a,this._scope=i,await Vn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new lr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Io extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Km({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}const IS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Eo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Ps{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=t0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??IS}async _authThenStart(){if(!this._authProvider)throw new lr("No auth provider");let t;try{t=await Vn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new lr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Di(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Eo(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Io({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:g}=await u.read();if(g)break;if(f.id&&(a=f.id,i=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const _=Kr.parse(JSON.parse(f.data));ys(_)&&(l=!0,s!==void 0&&(_.id=s)),this.onmessage?.(_)}catch(_){this.onerror?.(_)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}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(t){if(!this._authProvider)throw new lr("No auth provider");if(await Vn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new lr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:hc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Eo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=Vi(i);if(this._resourceMetadataUrl=f,this._scope=g,await Vn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new lr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:_}=Vi(i);if(_==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Eo(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await Vn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new lr;return this.send(t)}}throw new Eo(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),Zk(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,h=i.headers.get("content-type");if(u)if(h?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(h?.includes("application/json")){const p=await i.json(),f=Array.isArray(p)?p.map(g=>Kr.parse(g)):[Kr.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await i.body?.cancel(),new Eo(-1,`Unexpected content type: ${h}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Eo(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}const ES="mcp";class l0{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,ES),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=Kr.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const wn=er;(function(e,t){const r=er,n=er,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Hi,-118057+3521*-35+-2099*-233);const c0=()=>{const e=er,t=er,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},xS=(e,t,r)=>{const n=er,o=er,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)},$S=(e,t)=>{const r=er,n=er,o={};o.nTCfA=function(a,i){return a in i},o[r(390)]="addEventListener",o[r(385)]=function(a,i){return a===i},o[r(409)]="function",o.VaHpd=n(392),o[n(384)]=r(417),o.FPOYW=function(a,i){return a!==i};const s=o;s.nTCfA(s.ogKey,e)&&s[n(385)](typeof e.addEventListener,s[n(409)])?e[n(386)](s.VaHpd,t):s[n(384)]in e&&s[r(398)](typeof e[n(417)],r(414))&&(e.onmessage=t)};class Ms{constructor(t){this._port=t}async[wn(401)](){const t=wn,r=wn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=Kr.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=er,l=er;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=wn,o=wn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class Iu extends Ms{constructor(t,r=c0()){const n=wn,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](xS,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class Eu extends Ms{constructor(t,r=c0()){const n=wn,o=wn,s={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,l){return a(i,l)}};super(),this[n(397)]=t,this[o(388)]=r,this[o(416)]=new Promise(a=>{const i=n,l={XlglK:function(c,u){return s.HITdC(c,u)},pXlad:function(c){return s.QdDxM(c)}};s[i(427)]($S,this._globalObject,c=>{const u=i,h=i;c[u(412)]&&l.XlglK(c.data[h(396)],this._endpoint)&&(this[u(422)]=c[h(430)][-3036+-1518*-2],l.pXlad(a))})})}async listen(){return this._listen}}function Hi(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return Hi=function(){return e},Hi()}function er(e,t){const r=Hi();return er=function(n,o){return n=n-(17227+1*-16844),r[n]},er(e,t)}const RS=()=>{const e=new MessageChannel;return[new Ms(e.port1),new Ms(e.port2)]};(function(e,t){const r=Ye,n=Ye,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Bi,-411935*1+228107+208149*2);const PS=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case i.VRyiJ:h=await t.listTools(u);break;case i.VkPYu:h=await t.callTool(u);break;case i.fgMSD:h=await t.listResources(u);break;case i[s(466)]:h=await t.listResourceTemplates(u);break;case i.sthgI:h=await t[o(455)](u);break;case s(486):h=await t.subscribeResource(u);break;case o(410):h=await t.unsubscribeResource(u);break;case i[s(461)]:h=await t[s(414)](u);break;case i[o(412)]:h=await t[o(491)](u);break;case i[o(436)]:h=await t[o(478)]();break;case i.kkNqg:h=await t.complete(u);break;case o(464):h=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=h,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},MS=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,h=await t[o(469)](f,Hc);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,h=await t.request(g,Mi);break;case i[o(487)]:const _={};_.method=c,_[s(446)]=u,h=await t.request(_,Ts);break;case i.ypHTC:const y={};y.method=c,h=await t.request(y,vn);break}const p={};return p.result=h,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),h};function Ye(e,t){const r=Bi();return Ye=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ye(e,t)}const OS=(e,t)=>{const r=Ye,n=Ye,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,h,p;const f=n,g=r,{id:_,method:y}=a;try{o[f(451)](y,o.DhPFX)?await s.call(e,a,i):await o[g(474)](PS,e,t,a)}catch(w){const{code:v,message:m,data:S}=w;try{if(v){const k={};k[g(485)]=v,k[f(422)]=m,k.data=S;const T={};T[g(448)]=k,T.jsonrpc=o[f(417)],T.id=_,await((l=e?.transport)==null?void 0:l[g(460)](T))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(k){(p=(h=e?.transport)==null?void 0:h.onerror)==null||p.call(h,k)}}}},NS=(e,t)=>{const r=Ye,n=Ye,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:h,params:p}=a;if(h!==s[c(476)]&&(s.QWYMz(h,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},AS=(e,t)=>async r=>{var n,o,s,a,i;const l=Ye,c=Ye,u={TJhyV:function(h,p,f,g){return h(p,f,g)},MMNTY:l(465)};try{return await u.TJhyV(MS,e,t,r)}catch(h){const{code:p,message:f,data:g}=h;try{if(p){const _={};_.code=p,_[l(422)]=f,_[c(419)]=g;const y={};y[l(448)]=_,y[l(424)]=u.MMNTY,y.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](y))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,h)}catch(_){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,_)}}},qS=(e,t)=>async r=>{var n,o,s;const a=Ye,i=Ye,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:h}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||h?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Bi(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return Bi=function(){return e},Bi()}const LS=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Ye,u=Ye,h={};h.kSvAZ=c(465);const p=h;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:g,message:_,data:y}=f;try{if(g){const w={};w.code=g,w.message=_,w.data=y;const v={};v.error=w,v[u(424)]=p.kSvAZ,v.id=r.id,await((o=e?.transport)==null?void 0:o.send(v))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,f)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},xu=()=>{const e=Ye,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ye;if(c){const h=[];for(const p of r)try{h.push(p(l,c))}catch{}for(const p of h)if(t.rgPZO(p,null))return p}else for(const h of r)try{t[u(427)](h,l)}catch{}},o=l=>{const c=Ye,u=Ye;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ye,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Ye;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},jS=e=>{const t=Ye,r=Ye,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](xu);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](xu);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(xu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},DS=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ye,o=Ye,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(jS,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},US=Qr;(function(e,t){const r=Qr,n=Qr,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ji,995159+-6*-266138+-1619768);const zS=()=>{const e=Qr,t=Qr,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},ZS=e=>{const t=Qr,r=Qr,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},bn={};bn[US(211)]=zS,bn.randomBytes=ZS;function Qr(e,t){const r=Ji();return Qr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Qr(e,t)}function Ji(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Ji=function(){return e},Ji()}function Xr(e,t){const r=Wi();return Xr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Xr(e,t)}const kr=Xr,Os=Xr;(function(e,t){const r=Xr,n=Xr,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Wi,-4*308317+753182*2+658196);const FS=(e,t)=>{const r=Xr,n=Xr,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](OS,e,t),NS(e,t);const s=o[n(283)](AS,t,e),a=o[n(294)](LS,t,e),i=o[r(277)](qS,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},$u=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,Rs)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Xr(295)])==null||i.close()})),n.Qalmc(FS,e,t)},s={};s.afterInit=o,n.Qalmc(DS,t,s)},u0=(e,t=bn[kr(299)]())=>{const r=kr,n=kr,o={RVabx:function(u,h,p){return u(h,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,h){const p=r,f=r,g=new Headers(h?.[p(268)]||{});Object.entries(a).forEach(([y,w])=>{g.set(y,w)});const _={...h};return _.headers=g,o[f(279)](fetch,u,_)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},d0=(e,t=bn[kr(299)]())=>{const r=Os,n=kr,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},Ru=async(e,t,r)=>{const n=kr,o=kr,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,lr)){const l=await t();return await a[n(257)](l),await Ru(e,t,r)}else throw i}},p0=(e,t)=>{const r=Os,n=Os,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function Wi(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return Wi=function(){return e},Wi()}const VS=async e=>{const t=Os,r=kr,n={GKDjq:function(I,L,O){return I(L,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(I){return I()},kdowC:function(I,L,O,A){return I(L,O,A)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,g=i||bn[r(299)](),_=n[t(289)](u0,a,g);if(c){const I={..._.requestInit,...c};I[r(268)]={..._[r(280)][t(268)],...c.headers},f.requestInit=I}else f.requestInit=_[t(280)];if(u){const I={..._[t(270)],...u};f.eventSourceInit=I}else f.eventSourceInit=_[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const v=w,m={};m.name=n[r(261)],m[t(288)]=n.mcbiU;const S={};S[t(251)]=v;const k=new Ss(m,S),T=()=>new Rs(new URL(s),f);let b=n[t(282)](T);if(l){const I=p0(l,h);b=await n[t(263)](Ru,k,I,T)}else await k.connect(b);$u(k,o,b),b.sessionId=b[r(274)].searchParams[t(297)](n.KkViY);const x={};return x.transport=b,x.sessionId=b[r(286)],x},HS=async e=>{const t=Os,r=kr,n={wfHUn:function(I,L,O){return I(L,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(I){return I()},PdsSn:function(I,L,O,A){return I(L,O,A)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,g=i||bn.randomUUID(),_=n[r(272)](d0,a,g);if(c){const I={..._[t(280)],...c};I.headers={..._.requestInit[t(268)],...c.headers},f.requestInit=I}else f[r(280)]=_[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const v=w,m={};m.name=n[t(262)],m.version=n.omKPe;const S={};S.capabilities=v;const k=new Ss(m,S),T=()=>new Ps(new URL(s),f);let b=n.rSiEq(T);if(l){const I=n[t(272)](p0,l,h);b=await n[t(296)](Ru,k,I,T)}else await k[t(260)](b);n.PdsSn($u,k,o,b);const x={};return x.transport=b,x[r(286)]=b[r(286)],x},BS=async e=>{const t=kr,r=kr,n={eZwNI:function(w,v,m,S){return w(v,m,S)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,h={};h.name="mcp-socket-proxy-client",h.version=r(248);const p={};p[r(251)]=u;const f=new Ss(h,p),g=i||bn[r(299)](),_=new l0(new URL(s+"?sessionId="+g+r(265)+a));await f.connect(_),n[t(259)]($u,f,o,_);const y={};return y.transport=_,y[r(286)]=g,y},kn=Tr,Ns=Tr;(function(e,t){const r=Tr,n=Tr,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Gi,1297719+-42747*-22+-1289197);function Tr(e,t){const r=Gi();return Tr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Tr(e,t)}const JS=()=>bn.randomBytes(-8746+-382*-23);class WS{constructor(t){const r=Tr,n=Tr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(JS),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=Tr,c=Tr,u={};u[l(198)]="GET";const h=await fetch(t,u);!h.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+h[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const f=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,f.code)}async[kn(191)](t,r){const n=kn,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Tr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[kn(206)]}get[Ns(190)](){return this._clientMetadata}[kn(213)](){return this[kn(197)]}[Ns(218)](){return this[Ns(200)]}[kn(194)](t){this._clientInformation=t}tokens(){return this[Ns(210)]}saveTokens(t){const r=Ns;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[kn(212)](){const t=kn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Gi(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return Gi=function(){return e},Gi()}(function(e,t){for(var r=Yi,n=Yi,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ki,262*-2438+1346066*-1+2*1373311);function Ki(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Ki=function(){return e},Ki()}function Yi(e,t){var r=Ki();return Yi=function(n,o){n=n-287;var s=r[n];return s},Yi(e,t)}class GS{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}class KS extends Um{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($i.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{const s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Bm,this.setRequestHandler(am,n=>this._oninitialize(n)),this.setNotificationHandler(vc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ri,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=$i.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new GS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zm(this._capabilities,t)}setRequestHandler(t,r){const o=_o(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(yr(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){const i=async(l,c)=>{const u=vr(xi,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new ie(de.InvalidParams,`Invalid tools/call request: ${g}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const g=vr(mo,p);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new ie(de.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}const f=vr(yo,p);if(!f.success){const g=f.error instanceof Error?f.error.message:String(f.error);throw new ie(de.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"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 ${t})`);break}}assertTaskCapability(t){Wm(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Jm(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){const r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:em.includes(r)?r:ms,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"},vn)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){const n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,i=a?Array.isArray(a.content)?a.content:[a.content]:[],l=i.some(c=>c.type==="tool_use");if(s){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const c=new Set(i.filter(h=>h.type==="tool_use").map(h=>h.id)),u=new Set(o.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(c.size!==u.size||![...c].every(h=>u.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},Zc,r):this.request({method:"sampling/createMessage",params:t},Mi,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const o=t;return this.request({method:"elicitation/create",params:o},Ts,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Ts,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new ie(de.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof ie?a:new ie(de.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return s}}}createElicitationCompletionNotifier(t,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:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Hc,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Pu=Symbol.for("mcp.completable");function YS(e,t){return Object.defineProperty(e,Pu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function f0(e){return!!e&&typeof e=="object"&&Pu in e}function QS(e){return e[Pu]?.complete}var h0;(function(e){e.Completable="McpCompletable"})(h0||(h0={}));const m0=1e6,Mu=1e6,g0=1e4,XS=1e6;class en{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){en.validateLength(t,m0,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){const r=[];let n="",o=0,s=0;for(;o<t.length;)if(t[o]==="{"){n&&(r.push(n),n="");const a=t.indexOf("}",o);if(a===-1)throw new Error("Unclosed template expression");if(s++,s>g0)throw new Error(`Template contains too many expressions (max ${g0})`);const i=t.slice(o+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),h=u[0];for(const p of u)en.validateLength(p,Mu,"Variable name");r.push({name:h,operator:l,names:u,exploded:c}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(n=>t.startsWith(n))||""}getNames(t){const r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return en.validateLength(t,Mu,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){const a=t.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(h=>this.encodeValue(h,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(t.operator==="?"?"?":"&")+a.join("&")}if(t.names.length>1){const a=t.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[t.name];if(n===void 0)return"";const s=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,t.operator));switch(t.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(t){let r="",n=!1;for(const o of this.parts){if(typeof o=="string"){r+=o;continue}const s=this.expandPart(o,t);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){const r=[];for(const s of t.names)en.validateLength(s,Mu,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const a=t.names[s],i=s===0?"\\"+t.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const o=t.name;switch(t.operator){case"":n=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(t){en.validateLength(t,m0,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)r+=c,n.push({name:u,exploded:i.exploded})}r+="$",en.validateLength(r,XS,"Generated regex pattern");const o=new RegExp(r),s=t.match(o);if(!s)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=s[i+1],h=l.replace("*","");c&&u.includes(",")?a[h]=u.split(","):a[h]=u}return a}}const e6=/^[A-Za-z0-9._-]{1,128}$/;function t6(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!e6.test(e)){const r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function r6(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const r of t)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 y0(e){const t=t6(e);return r6(e,t.warnings),t.isValid}class n6{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){const o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}class v0{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new KS(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new n6(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Tn(Dc)),this.server.assertCanSetRequestHandler(Tn(xi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Dc,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{const n={name:t,title:r.title,description:r.description,inputSchema:(()=>{const o=Cs(r.inputSchema);return o?Lm(o,{strictUnions:!0,pipeStrategy:"input"}):s6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=Cs(r.outputSchema);o&&(n.outputSchema=Lm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(xi,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new ie(de.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ie(de.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if((s==="required"||s==="optional")&&!a)throw new ie(de.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new ie(de.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof ie&&n.code===de.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const s=Cs(t.inputSchema)??t.inputSchema,a=await Bc(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Jc(i);throw new ie(de.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ie(de.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=Cs(t.outputSchema),s=await Bc(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Jc(a);throw new ie(de.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,a))}else{const i=o;return await Promise.resolve(i.createTask(a))}}if(t.inputSchema){const a=o;return await Promise.resolve(a(r,n))}else{const a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,a={...n,taskStore:n.taskStore},i=o?await Promise.resolve(s.createTask(o,a)):await Promise.resolve(s.createTask(a)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const h=await n.taskStore.getTask(l);if(!h)throw new ie(de.InternalError,`Task ${l} not found during polling`);c=h}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Tn(Vc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Vc,async t=>{switch(t.params.ref.type){case"ref/prompt":return UT(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return zT(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ie(de.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new ie(de.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ie(de.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return As;const s=_o(n.argsSchema)?.[t.params.argument.name];if(!f0(s))return As;const a=QS(s);if(!a)return As;const i=await a(t.params.argument.value,t.params.context);return b0(i)}async handleResourceCompletion(t,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return As;throw new ie(de.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return As;const s=await o(t.params.argument.value,t.params.context);return b0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Tn(Ei)),this.server.assertCanSetRequestHandler(Tn(xc)),this.server.assertCanSetRequestHandler(Tn(Rc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ei,async(t,r)=>{const n=Object.entries(this._registeredResources).filter(([s,a])=>a.enabled).map(([s,a])=>({uri:s,name:a.name,...a.metadata})),o=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const a=await s.resourceTemplate.listCallback(r);for(const i of a.resources)o.push({...s.metadata,...i})}return{resources:[...n,...o]}}),this.server.setRequestHandler(xc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rc,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ie(de.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(n.toString());if(a)return s.readCallback(n,a,r)}throw new ie(de.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Tn(Mc)),this.server.assertCanSetRequestHandler(Tn(Oc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Mc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?i6(r.argsSchema):void 0}))})),this.server.setRequestHandler(Oc,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new ie(de.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ie(de.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=Cs(n.argsSchema),s=await Bc(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Jc(l);throw new ie(de.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const a=s.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){const a={name:t,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(t,r,n,o,s){const a={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,n,o,s){const a={title:r,description:n,argsSchema:o===void 0?void 0:vo(o),callback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==t&&(delete this._registeredPrompts[t],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=vo(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,o&&Object.values(o).some(l=>{const c=l instanceof gr?l._def?.innerType:l;return f0(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){y0(t);const u={title:r,description:n,inputSchema:w0(o),outputSchema:w0(s),annotations:a,execution:i,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:h=>{typeof h.name<"u"&&h.name!==t&&(typeof h.name=="string"&&y0(h.name),delete this._registeredTools[t],h.name&&(this._registeredTools[h.name]=u)),typeof h.title<"u"&&(u.title=h.title),typeof h.description<"u"&&(u.description=h.description),typeof h.paramsSchema<"u"&&(u.inputSchema=vo(h.paramsSchema)),typeof h.outputSchema<"u"&&(u.outputSchema=vo(h.outputSchema)),typeof h.callback<"u"&&(u.handler=h.callback),typeof h.annotations<"u"&&(u.annotations=h.annotations),typeof h._meta<"u"&&(u._meta=h._meta),typeof h.enabled<"u"&&(u.enabled=h.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];Ou(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ou(r[0])&&(a=r.shift())):typeof l=="object"&&l!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(t,void 0,n,o,s,a,{taskSupport:"forbidden"},void 0,i)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);const{title:o,description:s,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,s,a,i,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());const s=r[0],a=this._createRegisteredPrompt(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);const{title:o,description:s,argsSchema:a}=r,i=this._createRegisteredPrompt(t,o,s,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class o6{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new en(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const s6={type:"object",properties:{}};function _0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function a6(e){return"_def"in e||"_zod"in e||_0(e)}function Ou(e){return typeof e!="object"||e===null||a6(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(_0)}function w0(e){if(e)return Ou(e)?vo(e):e}function i6(e){const t=_o(e);return t?Object.entries(t).map(([r,n])=>{const o=BT(n),s=JT(n);return{name:r,description:o,required:!s}}):[]}function Tn(e){const r=_o(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Em(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function b0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const As={completion:{values:[],hasMore:!1}};function l6(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class qs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new qs,r=new qs;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}class c6{constructor(t,r){const n={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new v0(t||n,r||{capabilities:o}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=s=>{this.onerror?.(s)},this.server.server.setRequestHandler(Ri,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new Eu(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,r,n){return this.server.registerTool(t,r,n)}registerPrompt(t,r,n){return this.server.registerPrompt(t,r,n)}registerResource(t,r,n,o){return typeof r=="string"?this.server.registerResource(t,r,n,o):this.server.registerResource(t,r,n,o)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(t,r){return await this.server.server.createMessage(t,r)}async elicitInput(t,r){return await this.server.server.elicitInput(t,r)}async listRoots(t,r){return await this.server.server.listRoots(t,r)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,r,n){return this.server.server.request(t,r,n)}async notification(t,r){return await this.server.server.notification(t,r)}setRequestHandler(t,r){this.server.server.setRequestHandler(t,r)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,r){this.server.server.setNotificationHandler(t,r)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(mm,t)}onUnsubscribe(t){this.server.server.setRequestHandler(gm,t)}onSetLogLevel(t){this.server.server.setRequestHandler(Ri,t)}onListResources(t){this.server.server.setRequestHandler(Ei,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(Sm,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const u6=(e,t)=>new Eu(e,t),d6=()=>RS(),p6=e=>e instanceof Eu,f6=e=>e instanceof v0;class k0{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ss(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let h;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await VS(u):s==="socket"?await BS(u):await HS(u);f.onerror=async _=>{i?.(_)},h={transport:f,sessionId:g}})(),h}const l=new URL(r);let c;if(s==="channel"&&(c=new Iu(r),await this.client.connect(c)),s==="sse"){const u=u0(n,o);c=new Rs(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new l0(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=d0(n,o);c=new Ps(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,yo,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(Fc,t)}onCreateMessage(t){this.client.setRequestHandler(zc,t)}onListRoots(t){this.client.setRequestHandler(Cm,t)}onToolListChanged(t){this.client.setNotificationHandler(Uc,t)}onPromptListChanged(t){this.client.setNotificationHandler(jc,t)}onResourceListChanged(t){this.client.setNotificationHandler(Pc,t)}onResourceUpdated(t){this.client.setNotificationHandler(ym,t)}onLoggingMessage(t){this.client.setNotificationHandler(km,t)}async onPagehide(t){t.persisted||(T0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const h6=(e,t)=>new Rs(e,t),m6=(e,t)=>new Ps(e,t),g6=(e,t)=>new Iu(e,t),y6=e=>e instanceof Rs,T0=e=>e instanceof Ps,v6=e=>e instanceof Iu,_6=e=>e instanceof Ss,xo=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},C0=(e,t,r)=>{const n=async function(o){o.source===window&&o.data.type===e&&o.data.direction===r&&await t(o.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Nu=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},Au=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r&&(!n||n&&s.tabId===n)){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class S0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Au("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Kr.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=n.tabIds[n.tabIds.length-1];Nu("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const I0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});class w6{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||I0(),this._messageListener1=C0("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.error("【Page Svr Transport】 notifyRegistration失败:",r)})},"content->page"),this._messageListener2=C0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=Kr.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&xo("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),xo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&xo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{xo("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}class b6{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||I0(),this.tabId=r,Au("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Au("mcp-client-to-server",t=>{if(!(t.sessionId!==this.sessionId||t.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",t.mcpMessage);const r=Kr.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&xo("update-page-app-message",{status:"run",message:t.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",t),Nu("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&t.result?.content&&xo("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(t){this._isStarted&&(this._lastRegistration=t,Nu("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(t))}}}var $o={},qu,E0;function k6(){return E0||(E0=1,qu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),qu}var Lu={},Cn={},x0;function Hn(){if(x0)return Cn;x0=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Cn.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Cn.getSymbolTotalCodewords=function(n){return t[n]},Cn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Cn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Cn.isKanjiModeEnabled=function(){return typeof e<"u"},Cn.toSJIS=function(n){return e(n)},Cn}var ju={},$0;function Du(){return $0||($0=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(ju)),ju}var Uu,R0;function T6(){if(R0)return Uu;R0=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Uu=e,Uu}var zu,P0;function C6(){if(P0)return zu;P0=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},zu=e,zu}var Zu={},M0;function S6(){return M0||(M0=1,(function(e){const t=Hn().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Zu)),Zu}var Fu={},O0;function I6(){if(O0)return Fu;O0=1;const e=Hn().getSymbolSize,t=7;return Fu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Fu}var Vu={},N0;function E6(){return N0||(N0=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let h=0;h<s;h++){i=l=0,c=u=null;for(let p=0;p<s;p++){let f=o.get(h,p);f===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=f,i=1),f=o.get(p,h),f===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=f,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function r(n,o,s){switch(n){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(Vu)),Vu}var Qi={},A0;function q0(){if(A0)return Qi;A0=1;const e=Du(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Qi.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},Qi.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},Qi}var Hu={},Ls={},L0;function x6(){if(L0)return Ls;L0=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),Ls.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Ls.exp=function(n){return e[n]},Ls.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Ls}var j0;function $6(){return j0||(j0=1,(function(e){const t=x6();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Hu)),Hu}var Bu,D0;function R6(){if(D0)return Bu;D0=1;const e=$6();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},Bu=t,Bu}var Ju={},Wu={},Gu={},U0;function z0(){return U0||(U0=1,Gu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Gu}var Ar={},Z0;function F0(){if(Z0)return Ar;Z0=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
44
+ ]))+`;Ar.KANJI=new RegExp(r,"g"),Ar.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ar.BYTE=new RegExp(n,"g"),Ar.NUMERIC=new RegExp(e,"g"),Ar.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ar.testKanji=function(l){return o.test(l)},Ar.testNumeric=function(l){return s.test(l)},Ar.testAlphanumeric=function(l){return a.test(l)},Ar}var V0;function Bn(){return V0||(V0=1,(function(e){const t=z0(),r=F0();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return n(s)}catch{return a}}})(Wu)),Wu}var H0;function P6(){return H0||(H0=1,(function(e){const t=Hn(),r=q0(),n=Du(),o=Bn(),s=z0(),a=7973,i=t.getBCHDigit(a);function l(p,f,g){for(let _=1;_<=40;_++)if(f<=e.getCapacity(_,g,p))return _}function c(p,f){return o.getCharCountIndicator(p,f)+4}function u(p,f){let g=0;return p.forEach(function(_){const y=c(_.mode,f);g+=y+_.getBitsLength()}),g}function h(p,f){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,f,o.MIXED))return g}e.from=function(f,g){return s.isValid(f)?parseInt(f,10):g},e.getCapacity=function(f,g,_){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=o.BYTE);const y=t.getSymbolTotalCodewords(f),w=r.getTotalCodewordsCount(f,g),v=(y-w)*8;if(_===o.MIXED)return v;const m=v-c(_,f);switch(_){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},e.getBestVersionForData=function(f,g){let _;const y=n.from(g,n.M);if(Array.isArray(f)){if(f.length>1)return h(f,y);if(f.length===0)return 1;_=f[0]}else _=f;return l(_.mode,_.getLength(),y)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-i>=0;)g^=a<<t.getBCHDigit(g)-i;return f<<12|g}})(Ju)),Ju}var Ku={},B0;function M6(){if(B0)return Ku;B0=1;const e=Hn(),t=1335,r=21522,n=e.getBCHDigit(t);return Ku.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},Ku}var Yu={},Qu,J0;function O6(){if(J0)return Qu;J0=1;const e=Bn();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},Qu=t,Qu}var Xu,W0;function N6(){if(W0)return Xu;W0=1;const e=Bn(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},Xu=r,Xu}var ed,G0;function A6(){if(G0)return ed;G0=1;const e=Bn();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},ed=t,ed}var td,K0;function q6(){if(K0)return td;K0=1;const e=Bn(),t=Hn();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
45
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},td=r,td}var rd={exports:{}},Y0;function L6(){return Y0||(Y0=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,h,p,f,g,_,y;!i.empty();){l=i.pop(),c=l.value,h=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=h+f,_=a[u],y=typeof a[u]>"u",(y||_>g)&&(a[u]=g,i.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(rd)),rd.exports}var Q0;function j6(){return Q0||(Q0=1,(function(e){const t=Bn(),r=O6(),n=N6(),o=A6(),s=q6(),a=F0(),i=Hn(),l=L6();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,v,m){const S=[];let k;for(;(k=w.exec(m))!==null;)S.push({data:k[0],index:k.index,mode:v,length:k[0].length});return S}function h(w){const v=u(a.NUMERIC,t.NUMERIC,w),m=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let S,k;return i.isKanjiModeEnabled()?(S=u(a.BYTE,t.BYTE,w),k=u(a.KANJI,t.KANJI,w)):(S=u(a.BYTE_KANJI,t.BYTE,w),k=[]),v.concat(m,S,k).sort(function(b,x){return b.index-x.index}).map(function(b){return{data:b.data,mode:b.mode,length:b.length}})}function p(w,v){switch(v){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function f(w){return w.reduce(function(v,m){const S=v.length-1>=0?v[v.length-1]:null;return S&&S.mode===m.mode?(v[v.length-1].data+=m.data,v):(v.push(m),v)},[])}function g(w){const v=[];for(let m=0;m<w.length;m++){const S=w[m];switch(S.mode){case t.NUMERIC:v.push([S,{data:S.data,mode:t.ALPHANUMERIC,length:S.length},{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.ALPHANUMERIC:v.push([S,{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.KANJI:v.push([S,{data:S.data,mode:t.BYTE,length:c(S.data)}]);break;case t.BYTE:v.push([{data:S.data,mode:t.BYTE,length:c(S.data)}])}}return v}function _(w,v){const m={},S={start:{}};let k=["start"];for(let T=0;T<w.length;T++){const b=w[T],x=[];for(let I=0;I<b.length;I++){const L=b[I],O=""+T+I;x.push(O),m[O]={node:L,lastCount:0},S[O]={};for(let A=0;A<k.length;A++){const N=k[A];m[N]&&m[N].node.mode===L.mode?(S[N][O]=p(m[N].lastCount+L.length,L.mode)-p(m[N].lastCount,L.mode),m[N].lastCount+=L.length):(m[N]&&(m[N].lastCount=L.length),S[N][O]=p(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,v))}}k=x}for(let T=0;T<k.length;T++)S[k[T]].end=0;return{map:S,table:m}}function y(w,v){let m;const S=t.getBestModeForData(w);if(m=t.from(v,S),m!==t.BYTE&&m.bit<S.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
46
+ Suggested mode is: `+t.toString(S));switch(m===t.KANJI&&!i.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(v){return v.reduce(function(m,S){return typeof S=="string"?m.push(y(S,null)):S.data&&m.push(y(S.data,S.mode)),m},[])},e.fromString=function(v,m){const S=h(v,i.isKanjiModeEnabled()),k=g(S),T=_(k,m),b=l.find_path(T.map,"start","end"),x=[];for(let I=1;I<b.length-1;I++)x.push(T.table[b[I]].node);return e.fromArray(f(x))},e.rawSplit=function(v){return e.fromArray(h(v,i.isKanjiModeEnabled()))}})(Yu)),Yu}var X0;function D6(){if(X0)return Lu;X0=1;const e=Hn(),t=Du(),r=T6(),n=C6(),o=S6(),s=I6(),a=E6(),i=q0(),l=R6(),c=P6(),u=M6(),h=Bn(),p=j6();function f(T,b){const x=T.size,I=s.getPositions(b);for(let L=0;L<I.length;L++){const O=I[L][0],A=I[L][1];for(let N=-1;N<=7;N++)if(!(O+N<=-1||x<=O+N))for(let U=-1;U<=7;U++)A+U<=-1||x<=A+U||(N>=0&&N<=6&&(U===0||U===6)||U>=0&&U<=6&&(N===0||N===6)||N>=2&&N<=4&&U>=2&&U<=4?T.set(O+N,A+U,!0,!0):T.set(O+N,A+U,!1,!0))}}function g(T){const b=T.size;for(let x=8;x<b-8;x++){const I=x%2===0;T.set(x,6,I,!0),T.set(6,x,I,!0)}}function _(T,b){const x=o.getPositions(b);for(let I=0;I<x.length;I++){const L=x[I][0],O=x[I][1];for(let A=-2;A<=2;A++)for(let N=-2;N<=2;N++)A===-2||A===2||N===-2||N===2||A===0&&N===0?T.set(L+A,O+N,!0,!0):T.set(L+A,O+N,!1,!0)}}function y(T,b){const x=T.size,I=c.getEncodedBits(b);let L,O,A;for(let N=0;N<18;N++)L=Math.floor(N/3),O=N%3+x-8-3,A=(I>>N&1)===1,T.set(L,O,A,!0),T.set(O,L,A,!0)}function w(T,b,x){const I=T.size,L=u.getEncodedBits(b,x);let O,A;for(O=0;O<15;O++)A=(L>>O&1)===1,O<6?T.set(O,8,A,!0):O<8?T.set(O+1,8,A,!0):T.set(I-15+O,8,A,!0),O<8?T.set(8,I-O-1,A,!0):O<9?T.set(8,15-O-1+1,A,!0):T.set(8,15-O-1,A,!0);T.set(I-8,8,1,!0)}function v(T,b){const x=T.size;let I=-1,L=x-1,O=7,A=0;for(let N=x-1;N>0;N-=2)for(N===6&&N--;;){for(let U=0;U<2;U++)if(!T.isReserved(L,N-U)){let G=!1;A<b.length&&(G=(b[A]>>>O&1)===1),T.set(L,N-U,G),O--,O===-1&&(A++,O=7)}if(L+=I,L<0||x<=L){L-=I,I=-I;break}}}function m(T,b,x){const I=new r;x.forEach(function(U){I.put(U.mode.bit,4),I.put(U.getLength(),h.getCharCountIndicator(U.mode,T)),U.write(I)});const L=e.getSymbolTotalCodewords(T),O=i.getTotalCodewordsCount(T,b),A=(L-O)*8;for(I.getLengthInBits()+4<=A&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const N=(A-I.getLengthInBits())/8;for(let U=0;U<N;U++)I.put(U%2?17:236,8);return S(I,T,b)}function S(T,b,x){const I=e.getSymbolTotalCodewords(b),L=i.getTotalCodewordsCount(b,x),O=I-L,A=i.getBlocksCount(b,x),N=I%A,U=A-N,G=Math.floor(I/A),J=Math.floor(O/A),ue=J+1,re=G-J,ge=new l(re);let V=0;const R=new Array(A),H=new Array(A);let Z=0;const E=new Uint8Array(T.buffer);for(let ae=0;ae<A;ae++){const Ie=ae<U?J:ue;R[ae]=E.slice(V,V+Ie),H[ae]=ge.encode(R[ae]),V+=Ie,Z=Math.max(Z,Ie)}const M=new Uint8Array(I);let D=0,K,ne;for(K=0;K<Z;K++)for(ne=0;ne<A;ne++)K<R[ne].length&&(M[D++]=R[ne][K]);for(K=0;K<re;K++)for(ne=0;ne<A;ne++)M[D++]=H[ne][K];return M}function k(T,b,x,I){let L;if(Array.isArray(T))L=p.fromArray(T);else if(typeof T=="string"){let G=b;if(!G){const J=p.rawSplit(T);G=c.getBestVersionForData(J,x)}L=p.fromString(T,G||40)}else throw new Error("Invalid data");const O=c.getBestVersionForData(L,x);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!b)b=O;else if(b<O)throw new Error(`
47
47
  The chosen QR Code version cannot contain this amount of data.
48
48
  Minimum version required to store current data is: `+O+`.
49
- `);const D=_(T,x,j),U=t.getSymbolSize(T),V=new n(U);return d(V,T),f(V),v(V,T),w(V,x,0),T>=7&&g(V,T),y(V,D),isNaN(R)&&(R=a.getBestMask(V,w.bind(null,V,x))),a.applyMask(R,V),w(V,x,R),{modules:V,version:T,errorCorrectionLevel:x,maskPattern:R,segments:j}}return Wl.create=function(T,x){if(typeof T>"u"||T==="")throw new Error("No input text");let R=e.M,j,O;return typeof x<"u"&&(R=e.from(x.errorCorrectionLevel,e.M),j=l.from(x.version),O=a.from(x.maskPattern),x.toSJISFunc&&t.setToSJISFunction(x.toSJISFunc)),k(T,j,R,O)},Wl}var mu={},gu={},um;function dm(){return um||(um=1,(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const s=parseInt(n.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+n.slice(0,6).join("")}}t.getOptions=function(n){n||(n={}),n.color||(n.color={});const s=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:o,scale:o?4:a,margin:s,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},t.getScale=function(n,s){return s.width&&s.width>=n+s.margin*2?s.width/(n+s.margin*2):s.scale},t.getImageWidth=function(n,s){const o=t.getScale(n,s);return Math.floor((n+s.margin*2)*o)},t.qrToImageData=function(n,s,o){const a=s.modules.size,i=s.modules.data,c=t.getScale(a,o),l=Math.floor((a+o.margin*2)*c),u=o.margin*c,p=[o.color.light,o.color.dark];for(let h=0;h<l;h++)for(let d=0;d<l;d++){let f=(h*l+d)*4,v=o.color.light;if(h>=u&&d>=u&&h<l-u&&d<l-u){const g=Math.floor((h-u)/c),w=Math.floor((d-u)/c);v=p[i[g*a+w]?1:0]}n[f++]=v.r,n[f++]=v.g,n[f++]=v.b,n[f]=v.a}}})(gu)),gu}var pm;function S5(){return pm||(pm=1,(function(t){const e=dm();function r(s,o,a){s.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=a,o.width=a,o.style.height=a+"px",o.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(o,a,i){let c=i,l=a;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),a||(l=n()),c=e.getOptions(c);const u=e.getImageWidth(o.modules.size,c),p=l.getContext("2d"),h=p.createImageData(u,u);return e.qrToImageData(h.data,o,c),r(p,l,u),p.putImageData(h,0,0),l},t.renderToDataURL=function(o,a,i){let c=i;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),c||(c={});const l=t.render(o,a,c),u=c.type||"image/png",p=c.rendererOpts||{};return l.toDataURL(u,p.quality)}})(mu)),mu}var yu={},fm;function T5(){if(fm)return yu;fm=1;const t=dm();function e(s,o){const a=s.a/255,i=o+'="'+s.hex+'"';return a<1?i+" "+o+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(s,o,a){let i=s+o;return typeof a<"u"&&(i+=" "+a),i}function n(s,o,a){let i="",c=0,l=!1,u=0;for(let p=0;p<s.length;p++){const h=Math.floor(p%o),d=Math.floor(p/o);!h&&!l&&(l=!0),s[p]?(u++,p>0&&h>0&&s[p-1]||(i+=l?r("M",h+a,.5+d+a):r("m",c,0),c=0,l=!1),h+1<o&&s[p+1]||(i+=r("h",u),u=0)):c++}return i}return yu.render=function(o,a,i){const c=t.getOptions(a),l=o.modules.size,u=o.modules.data,p=l+c.margin*2,h=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+p+"v"+p+'H0z"/>':"",d="<path "+e(c.color.dark,"stroke")+' d="'+n(u,l,c.margin)+'"/>',f='viewBox="0 0 '+p+" "+p+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+f+' shape-rendering="crispEdges">'+h+d+`</svg>
50
- `;return typeof i=="function"&&i(null,g),g},yu}var hm;function C5(){if(hm)return Kn;hm=1;const t=o5(),e=k5(),r=S5(),n=T5();function s(o,a,i,c,l){const u=[].slice.call(arguments,1),p=u.length,h=typeof u[p-1]=="function";if(!h&&!t())throw new Error("Callback required as last argument");if(h){if(p<2)throw new Error("Too few arguments provided");p===2?(l=i,i=a,a=c=void 0):p===3&&(a.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=i,i=a,a=void 0))}else{if(p<1)throw new Error("Too few arguments provided");return p===1?(i=a,a=c=void 0):p===2&&!a.getContext&&(c=i,i=a,a=void 0),new Promise(function(d,f){try{const v=e.create(i,c);d(o(v,a,c))}catch(v){f(v)}})}try{const d=e.create(i,c);l(null,o(d,a,c))}catch(d){l(d)}}return Kn.create=e.create,Kn.toCanvas=s.bind(null,r.render),Kn.toDataURL=s.bind(null,r.renderToDataURL),Kn.toString=s.bind(null,function(o,a,i){return n.render(o,i)}),Kn}var $5=C5();const mm=rn($5);class gm{constructor(e,{size:r=200,margin:n=4,color:s="#000",bgColor:o="#fff"}){this.value=e,this.size=r,this.margin=n,this.color=s,this.bgColor=o}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return mm.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return mm.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const E5={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class x5{constructor(e,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof e=="string"?document.querySelector(e):e,!this.el)throw new Error("Tooltip: invalid element");this.opts={...E5,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const e=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),e==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const e=this.opts.trigger;e==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):e==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):e==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const e=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
49
+ `);const A=m(b,x,L),N=e.getSymbolSize(b),U=new n(N);return f(U,b),g(U),_(U,b),w(U,x,0),b>=7&&y(U,b),v(U,A),isNaN(I)&&(I=a.getBestMask(U,w.bind(null,U,x))),a.applyMask(I,U),w(U,x,I),{modules:U,version:b,errorCorrectionLevel:x,maskPattern:I,segments:L}}return Lu.create=function(b,x){if(typeof b>"u"||b==="")throw new Error("No input text");let I=t.M,L,O;return typeof x<"u"&&(I=t.from(x.errorCorrectionLevel,t.M),L=c.from(x.version),O=a.from(x.maskPattern),x.toSJISFunc&&e.setToSJISFunction(x.toSJISFunc)),k(b,L,I,O)},Lu}var nd={},od={},e2;function t2(){return e2||(e2=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,h=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let f=0;f<c;f++){let g=(p*c+f)*4,_=s.color.light;if(p>=u&&f>=u&&p<c-u&&f<c-u){const y=Math.floor((p-u)/l),w=Math.floor((f-u)/l);_=h[i[y*a+w]?1:0]}n[g++]=_.r,n[g++]=_.g,n[g++]=_.b,n[g]=_.a}}})(od)),od}var r2;function U6(){return r2||(r2=1,(function(e){const t=t2();function r(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),h=c.getContext("2d"),p=h.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(h,c,u),h.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}})(nd)),nd}var sd={},n2;function z6(){if(n2)return sd;n2=1;const e=t2();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let h=0;h<o.length;h++){const p=Math.floor(h%s),f=Math.floor(h/s);!p&&!c&&(c=!0),o[h]?(u++,h>0&&p>0&&o[h-1]||(i+=c?r("M",p+a,.5+f+a):r("m",l,0),l=0,c=!1),p+1<s&&o[h+1]||(i+=r("h",u),u=0)):l++}return i}return sd.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,h=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",f="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+h+" "+h+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+f+`</svg>
50
+ `;return typeof i=="function"&&i(null,y),y},sd}var o2;function Z6(){if(o2)return $o;o2=1;const e=k6(),t=D6(),r=U6(),n=z6();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),h=u.length,p=typeof u[h-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(c=i,i=a,a=l=void 0):h===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(i=a,a=l=void 0):h===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(f,g){try{const _=t.create(i,l);f(s(_,a,l))}catch(_){g(_)}})}try{const f=t.create(i,l);c(null,s(f,a,l))}catch(f){c(f)}}return $o.create=t.create,$o.toCanvas=o.bind(null,r.render),$o.toDataURL=o.bind(null,r.renderToDataURL),$o.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),$o}var F6=Z6();const s2=Pn(F6);class a2{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return s2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return s2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const V6={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class H6{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...V6,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
51
51
  <div class="${this.opts.className}__arrow"></div>
52
- <div class="${this.opts.className}__inner">${e}</div>
53
- `}reposition(){const e=this.placementList(this.opts.placement);for(const r of e){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(e){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),s=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,c="center"]=e.split("-");let l=0,u=0;return i==="top"?l=r.top+s-n.height-a:i==="bottom"?l=r.bottom+s+a:i==="left"?u=r.left+o-n.width-a:i==="right"&&(u=r.right+o+a),(i==="top"||i==="bottom")&&(c==="start"?u=r.left+o:c==="end"?u=r.right+o-n.width:u=(r.left+r.right)/2+o-n.width/2),(i==="left"||i==="right")&&(c==="start"?l=r.top+s:c==="end"?l=r.bottom+s-n.height:l=(r.top+r.bottom)/2+s-n.height/2),{top:Math.round(l),left:Math.round(u)}}applyStyle({top:e,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${e}px`,left:`${r}px`})}checkViewport({top:e,left:r}){const s=window.innerWidth,o=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&e>=5&&r+a.width<=s-5&&e+a.height<=o-5}placementList(e){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[e.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=e=>{const r=e.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const ym="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(ym))return;const t=document.createElement("style");t.id=ym,t.textContent=`
52
+ <div class="${this.opts.className}__inner">${t}</div>
53
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const i2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(i2))return;const e=document.createElement("style");e.id=i2,e.textContent=`
54
54
  .tiny-remoter-native-tooltip {
55
55
  position: absolute;
56
56
  z-index: 9999;
@@ -97,11 +97,11 @@ Minimum version required to store current data is: `+O+`.
97
97
  transform: translateY(-50%);
98
98
  border-right-color: rgba(0,0,0,.75);
99
99
  }
100
- `,document.head.appendChild(t)})();const I5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",R5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",P5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",O5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",A5="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",M5="https://agent.opentiny.design/tiny-robot",N5="https://ai.opentiny.design/next-remoter",L5="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",_m=t=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:O5},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:I5},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${t.remoteUrl}`,active:!0,tip:t.remoteUrl,showCopyIcon:!0,icon:P5},{action:"remote-control",show:!0,text:"识别码",desc:`${t.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:R5}];class j5{constructor(e){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const s=this.getImageUrl(r.icon);s&&n.appendChild(s)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new x5(n,{content:"复制",placement:"top",trigger:"hover"})},!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||N5,remoteUrl:e.remoteUrl||M5,logoUrl:e.logoUrl||L5},e.menuItems&&e.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?_m(this.options).map(r=>{const n=e.find(s=>s.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):_m(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
100
+ `,document.head.appendChild(e)})();const B6="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",J6="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",W6="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",G6="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",K6="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",Y6="https://chat.opentiny.design",Q6="https://ai.opentiny.design/next-remoter",X6="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",l2=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:G6},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:B6},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:W6},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:J6}];class e5{constructor(t){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new H6(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||Q6,remoteUrl:t.remoteUrl||Y6,logoUrl:t.logoUrl||X6},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?l2(this.options).map(r=>{const n=t.find(o=>o.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):l2(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
101
101
  <div class="tiny-remoter-floating-block__icon">
102
102
  <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
103
103
  </div>
104
- `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
104
+ `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(r=>r.show!==!1).map(r=>`
105
105
  <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
106
106
  <div id="tiny-remoter-icon-item-${r.action}" class="tiny-remoter-dropdown-item__icon">
107
107
  </div>
@@ -112,14 +112,14 @@ Minimum version required to store current data is: `+O+`.
112
112
  <div>
113
113
  ${r.showCopyIcon?`
114
114
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
115
- <img src="${A5}"/>
115
+ <img src="${K6}"/>
116
116
  </div>
117
117
  `:""}
118
118
  </div>
119
119
  </div>
120
120
  </div>
121
121
  </div>
122
- `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",e=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",e=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,n=r.closest(".tiny-remoter-copy-icon");if(n){e.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const o=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;o&&this.handleAction(o)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new gm((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
122
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new a2((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
123
123
  <div style="text-align: center; padding: 32px;">
124
124
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
125
125
  <div style="
@@ -200,18 +200,18 @@ Minimum version required to store current data is: `+O+`.
200
200
  <span>支持微信、浏览器等多种方式</span>
201
201
  </div>
202
202
  </div>
203
- `);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(e,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
203
+ `);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(t,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
204
204
  <div class="tiny-remoter-modal-overlay"></div>
205
205
  <div class="tiny-remoter-modal-content">
206
206
  <div class="tiny-remoter-modal-header">
207
- <h3>${e}</h3>
207
+ <h3>${t}</h3>
208
208
  <button class="tiny-remoter-modal-close">&times;</button>
209
209
  </div>
210
210
  <div class="tiny-remoter-modal-body">
211
211
  ${r}
212
212
  </div>
213
213
  </div>
214
- `;const s=n.querySelector(".tiny-remoter-modal-close"),o=n.querySelector(".tiny-remoter-modal-overlay");return s.addEventListener("click",()=>this.hideModal(n)),o.addEventListener("click",()=>this.hideModal(n)),n}showModal(e){document.body.appendChild(e),setTimeout(()=>e.classList.add("show"),10)}hideModal(e){e.classList.remove("show"),setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},100)}addStyles(){const e=document.createElement("style");e.textContent=`
214
+ `;const o=n.querySelector(".tiny-remoter-modal-close"),s=n.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(n)),s.addEventListener("click",()=>this.hideModal(n)),n}showModal(t){document.body.appendChild(t),setTimeout(()=>t.classList.add("show"),10)}hideModal(t){t.classList.remove("show"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},100)}addStyles(){const t=document.createElement("style");t.textContent=`
215
215
  /* 浮动块样式 */
216
216
  .tiny-remoter-floating-block {
217
217
  position: fixed;
@@ -545,55 +545,63 @@ Minimum version required to store current data is: `+O+`.
545
545
  color: white;
546
546
  }
547
547
  }
548
- `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const q5=(t={})=>new j5(t);var vm="vercel.ai.error",z5=Symbol.for(vm),wm,D5=class w_ extends Error{constructor({name:e,message:r,cause:n}){super(r),this[wm]=!0,this.name=e,this.cause=n}static isInstance(e){return w_.hasMarker(e,vm)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};wm=z5;var we=D5,bm="AI_APICallError",km=`vercel.ai.error.${bm}`,U5=Symbol.for(km),Sm,gt=class extends we{constructor({message:e,url:r,requestBodyValues:n,statusCode:s,responseHeaders:o,responseBody:a,cause:i,isRetryable:c=s!=null&&(s===408||s===409||s===429||s>=500),data:l}){super({name:bm,message:e,cause:i}),this[Sm]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=s,this.responseHeaders=o,this.responseBody=a,this.isRetryable=c,this.data=l}static isInstance(e){return we.hasMarker(e,km)}};Sm=U5;var Tm="AI_EmptyResponseBodyError",Cm=`vercel.ai.error.${Tm}`,Z5=Symbol.for(Cm),$m,F5=class extends we{constructor({message:e="Empty response body"}={}){super({name:Tm,message:e}),this[$m]=!0}static isInstance(e){return we.hasMarker(e,Cm)}};$m=Z5;function Yn(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Em="AI_InvalidArgumentError",xm=`vercel.ai.error.${Em}`,V5=Symbol.for(xm),Im,Rm=class extends we{constructor({message:e,cause:r,argument:n}){super({name:Em,message:e,cause:r}),this[Im]=!0,this.argument=n}static isInstance(e){return we.hasMarker(e,xm)}};Im=V5;var Pm="AI_InvalidPromptError",Om=`vercel.ai.error.${Pm}`,H5=Symbol.for(Om),Am,Qn=class extends we{constructor({prompt:e,message:r,cause:n}){super({name:Pm,message:`Invalid prompt: ${r}`,cause:n}),this[Am]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,Om)}};Am=H5;var Mm="AI_InvalidResponseDataError",Nm=`vercel.ai.error.${Mm}`,B5=Symbol.for(Nm),Lm,jm=class extends we{constructor({data:e,message:r=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Mm,message:r}),this[Lm]=!0,this.data=e}static isInstance(e){return we.hasMarker(e,Nm)}};Lm=B5;var qm="AI_JSONParseError",zm=`vercel.ai.error.${qm}`,J5=Symbol.for(zm),Dm,pi=class extends we{constructor({text:e,cause:r}){super({name:qm,message:`JSON parsing failed: Text: ${e}.
549
- Error message: ${Yn(r)}`,cause:r}),this[Dm]=!0,this.text=e}static isInstance(e){return we.hasMarker(e,zm)}};Dm=J5;var Um="AI_LoadAPIKeyError",Zm=`vercel.ai.error.${Um}`,G5=Symbol.for(Zm),Fm,fi=class extends we{constructor({message:e}){super({name:Um,message:e}),this[Fm]=!0}static isInstance(e){return we.hasMarker(e,Zm)}};Fm=G5;var Vm="AI_NoSuchModelError",Hm=`vercel.ai.error.${Vm}`,W5=Symbol.for(Hm),Bm,Jm=class extends we{constructor({errorName:t=Vm,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[Bm]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return we.hasMarker(t,Hm)}};Bm=W5;var Gm="AI_TypeValidationError",Wm=`vercel.ai.error.${Gm}`,K5=Symbol.for(Wm),Km,Y5=class wd extends we{constructor({value:e,cause:r}){super({name:Gm,message:`Type validation failed: Value: ${JSON.stringify(e)}.
550
- Error message: ${Yn(r)}`,cause:r}),this[Km]=!0,this.value=e}static isInstance(e){return we.hasMarker(e,Wm)}static wrap({value:e,cause:r}){return wd.isInstance(r)&&r.value===e?r:new wd({value:e,cause:r})}};Km=K5;var co=Y5,Ym="AI_UnsupportedFunctionalityError",Qm=`vercel.ai.error.${Ym}`,Q5=Symbol.for(Qm),Xm,e2=class extends we{constructor({functionality:e,message:r=`'${e}' functionality not supported.`}){super({name:Ym,message:r}),this[Xm]=!0,this.functionality=e}static isInstance(e){return we.hasMarker(e,Qm)}};Xm=Q5;function Xn(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function X5(t,e){if(t==null)return Promise.resolve();const r=e?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(t2());return}const o=setTimeout(()=>{a(),n()},t),a=()=>{clearTimeout(o),r?.removeEventListener("abort",i)},i=()=>{a(),s(t2())};r?.addEventListener("abort",i)})}function t2(){return new DOMException("Delay was aborted","AbortError")}var hi=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function lo(t){return Object.fromEntries([...t.headers])}var uo=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new Rm({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},po=uo();function _u(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function vn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var eT=["fetch failed","failed to fetch"];function r2({error:t,url:e,requestBodyValues:r}){if(vn(t))return t;if(t instanceof TypeError&&eT.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new gt({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function fo(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function tT(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Kr(t,...e){const r=new Headers(tT(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var n2="3.0.18",rT=()=>globalThis.fetch,s2=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=rT()})=>{try{const a=await o(t,{method:"GET",headers:Kr(e,`ai-sdk/provider-utils/${n2}`,fo()),signal:s}),i=lo(a);if(!a.ok){let c;try{c=await n({response:a,url:t,requestBodyValues:{}})}catch(l){throw vn(l)||gt.isInstance(l)?l:new gt({message:"Failed to process error response",cause:l,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw c.value}try{return await r({response:a,url:t,requestBodyValues:{}})}catch(c){throw c instanceof Error&&(vn(c)||gt.isInstance(c))?c:new gt({message:"Failed to process successful response",cause:c,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw r2({error:a,url:t,requestBodyValues:{}})}};function nT({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function sT({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new fi({message:`${n} API key must be a string.`});if(typeof process>"u")throw new fi({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new fi({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new fi({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function mi({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var oT=/"__proto__"\s*:/,aT=/"constructor"\s*:/;function o2(t){const e=JSON.parse(t);return e===null||typeof e!="object"||oT.test(t)===!1&&aT.test(t)===!1?e:iT(e)}function iT(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function vu(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return o2(t)}try{return o2(t)}finally{Error.stackTraceLimit=e}}var gi=Symbol.for("vercel.ai.validator");function cT(t){return{[gi]:!0,validate:t}}function lT(t){return typeof t=="object"&&t!==null&&gi in t&&t[gi]===!0&&"validate"in t}function es(t){let e;return()=>(e==null&&(e=t()),e)}function uT(t){return lT(t)?t:typeof t=="function"?t():dT(t)}function dT(t){return cT(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new co({value:e,cause:r.issues})}})}async function wu({value:t,schema:e}){const r=await er({value:t,schema:e});if(!r.success)throw co.wrap({value:t,cause:r.error});return r.value}async function er({value:t,schema:e}){const r=uT(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:co.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:co.wrap({value:t,cause:n}),rawValue:t}}}async function pT({text:t,schema:e}){try{const r=vu(t);return e==null?r:wu({value:r,schema:e})}catch(r){throw pi.isInstance(r)||co.isInstance(r)?r:new pi({text:t,cause:r})}}async function wn({text:t,schema:e}){try{const r=vu(t);return e==null?{success:!0,value:r,rawValue:r}:await er({value:r,schema:e})}catch(r){return{success:!1,error:pi.isInstance(r)?r:new pi({text:t,cause:r}),rawValue:void 0}}}function a2(t){try{return vu(t),!0}catch{return!1}}function fT({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await wn({text:r,schema:e}))}}))}async function i2({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await er({value:e[t],schema:r});if(!n.success)throw new Rm({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var hT=()=>globalThis.fetch,ts=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>mT({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),mT=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=hT()})=>{try{const i=await a(t,{method:"POST",headers:Kr(e,`ai-sdk/provider-utils/${n2}`,fo()),body:r.content,signal:o}),c=lo(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw vn(u)||gt.isInstance(u)?u:new gt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(vn(l)||gt.isInstance(l))?l:new gt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw r2({error:i,url:t,requestBodyValues:r.values})}};function DR(t){return t}function c2(t){return{...t,type:"dynamic"}}async function dr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var bn=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=lo(n);if(a.trim()==="")return{responseHeaders:i,value:new gt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await pT({text:a,schema:t});return{responseHeaders:i,value:new gt({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new gt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},l2=t=>async({response:e})=>{const r=lo(e);if(e.body==null)throw new F5({});return{responseHeaders:r,value:fT({stream:e.body,schema:t})}},rs=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await wn({text:s,schema:t}),a=lo(e);if(!o.success)throw new gt({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},gT=(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("/")},yT=Symbol("Let zodToJsonSchema decide on which parser to use"),u2={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},_T=t=>typeof t=="string"?{...u2,name:t}:{...u2,...t};function Ot(){return{}}function vT(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function wT(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function bT(){return{type:"boolean"}}function d2(t,e){return ze(t.type._def,e)}var kT=(t,e)=>ze(t.innerType._def,e);function p2(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>p2(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 ST(t)}}var ST=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function TT(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function CT(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Ot()}function $T(t){return{type:"string",enum:Array.from(t.values)}}var ET=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function xT(t,e){const r=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(ET(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function IT(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var bu=void 0,tr={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:()=>(bu===void 0&&(bu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),bu),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 f2(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":rr(r,"email",n.message,e);break;case"format:idn-email":rr(r,"idn-email",n.message,e);break;case"pattern:zod":yt(r,tr.email,n.message,e);break}break;case"url":rr(r,"uri",n.message,e);break;case"uuid":rr(r,"uuid",n.message,e);break;case"regex":yt(r,n.regex,n.message,e);break;case"cuid":yt(r,tr.cuid,n.message,e);break;case"cuid2":yt(r,tr.cuid2,n.message,e);break;case"startsWith":yt(r,RegExp(`^${ku(n.value,e)}`),n.message,e);break;case"endsWith":yt(r,RegExp(`${ku(n.value,e)}$`),n.message,e);break;case"datetime":rr(r,"date-time",n.message,e);break;case"date":rr(r,"date",n.message,e);break;case"time":rr(r,"time",n.message,e);break;case"duration":rr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{yt(r,RegExp(ku(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&rr(r,"ipv4",n.message,e),n.version!=="v4"&&rr(r,"ipv6",n.message,e);break}case"base64url":yt(r,tr.base64url,n.message,e);break;case"jwt":yt(r,tr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&yt(r,tr.ipv4Cidr,n.message,e),n.version!=="v4"&&yt(r,tr.ipv6Cidr,n.message,e);break}case"emoji":yt(r,tr.emoji(),n.message,e);break;case"ulid":{yt(r,tr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{rr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{yt(r,tr.base64,n.message,e);break}}break}case"nanoid":yt(r,tr.nanoid,n.message,e)}return r}function ku(t,e){return e.patternStrategy==="escape"?PT(t):t}var RT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PT(t){let e="";for(let r=0;r<t.length;r++)RT.has(t[r])||(e+="\\"),e+=t[r];return e}function rr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function yt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:h2(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=h2(e,n)}function h2(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
551
- ]))`;continue}else if(s[l]==="$"){o+=`($|(?=[\r
552
- ]))`;continue}}if(n.s&&s[l]==="."){o+=i?`${s[l]}\r
553
- `:`[${s[l]}\r
554
- ]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function m2(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=f2(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=d2(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function OT(t,e){if(e.mapStrategy==="record")return m2(t,e);const r=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ot(),n=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ot();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function AT(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function MT(){return{not:Ot()}}function NT(){return{type:"null"}}var Su={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function LT(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Su&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Su[o._def.typeName];return a&&!s.includes(a)?[...s,a]: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,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return jT(t,e)}var jT=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>ze(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 qT(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Su[t.innerType._def.typeName],"null"]};const r=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function zT(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function DT(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=ZT(i),l=ze(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=UT(t,e);return o!==void 0&&(r.additionalProperties=o),r}function UT(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function ZT(t){try{return t.isOptional()}catch{return!0}}var FT=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return ze(t.innerType._def,e);const n=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ot()},n]}:Ot()},VT=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const r=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function HT(t,e){return ze(t.type._def,e)}function BT(t,e){const n={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function JT(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function GT(){return{not:Ot()}}function WT(){return Ot()}var KT=(t,e)=>ze(t.innerType._def,e),YT=(t,e,r)=>{switch(e){case z.ZodString:return f2(t,r);case z.ZodNumber:return zT(t);case z.ZodObject:return DT(t,r);case z.ZodBigInt:return wT(t);case z.ZodBoolean:return bT();case z.ZodDate:return p2(t,r);case z.ZodUndefined:return GT();case z.ZodNull:return NT();case z.ZodArray:return vT(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return LT(t,r);case z.ZodIntersection:return xT(t,r);case z.ZodTuple:return JT(t,r);case z.ZodRecord:return m2(t,r);case z.ZodLiteral:return IT(t);case z.ZodEnum:return $T(t);case z.ZodNativeEnum:return AT(t);case z.ZodNullable:return qT(t,r);case z.ZodOptional:return FT(t,r);case z.ZodMap:return OT(t,r);case z.ZodSet:return BT(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return HT(t,r);case z.ZodNaN:case z.ZodNever:return MT();case z.ZodEffects:return CT(t,r);case z.ZodAny:return Ot();case z.ZodUnknown:return WT();case z.ZodDefault:return TT(t,r);case z.ZodBranded:return d2(t,r);case z.ZodReadonly:return KT(t,r);case z.ZodCatch:return kT(t,r);case z.ZodPipeline:return VT(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function ze(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==yT)return c}if(s&&!r){const c=QT(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=YT(t,t.typeName,e),i=typeof a=="function"?ze(a(),e):a;if(i&&XT(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var QT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gT(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`),Ot()):e.$refStrategy==="seen"?Ot():void 0}},XT=(t,e,r)=>(t.description&&(r.description=t.description),r),eC=t=>{const e=_T(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,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}]))}},tC=(t,e)=>{var r;const n=eC(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>{var h;return{...l,[u]:(h=ze(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Ot()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=ze(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Ot(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},rC=tC;function nC(t,e){var r;const n=(r=void 0)!=null?r:!1;return ho(()=>rC(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function sC(t,e){var r;const n=(r=void 0)!=null?r:!1;return ho(()=>yc(t,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await _c(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function oC(t){return"_zod"in t}function kn(t,e){return oC(t)?sC(t):nC(t)}var Tu=Symbol.for("vercel.ai.schema");function ho(t,{validate:e}={}){return{[Tu]:!0,_type:void 0,[gi]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function aC(t){return typeof t=="object"&&t!==null&&Tu in t&&t[Tu]===!0&&"jsonSchema"in t&&"validate"in t}function yi(t){return t==null?ho({properties:{},additionalProperties:!1}):aC(t)?t:typeof t=="function"?t():kn(t)}var{btoa:iC,atob:cC}=globalThis;function Cu(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=cC(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function _i(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return iC(e)}function lC(t){return t instanceof Uint8Array?_i(t):t}function g2(t){return t?.replace(/\/$/,"")}function uC(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*y2({execute:t,input:e,options:r}){const n=t(e,r);if(uC(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var $u,_2;function dC(){if(_2)return $u;_2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(u,p)=>{for(var h in p)t(u,h,{get:p[h],enumerable:!0})},o=(u,p,h,d)=>{if(p&&typeof p=="object"||typeof p=="function")for(let f of r(p))!n.call(u,f)&&f!==h&&t(u,f,{get:()=>p[f],enumerable:!(d=e(p,f))||d.enumerable});return u},a=u=>o(t({},"__esModule",{value:!0}),u),i={};s(i,{SYMBOL_FOR_REQ_CONTEXT:()=>c,getContext:()=>l}),$u=a(i);const c=Symbol.for("@vercel/request-context");function l(){return globalThis[c]?.get?.()??{}}return $u}var Eu,v2;function pC(){if(v2)return Eu;v2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(p,h)=>{for(var d in h)t(p,d,{get:h[d],enumerable:!0})},o=(p,h,d,f)=>{if(h&&typeof h=="object"||typeof h=="function")for(let v of r(h))!n.call(p,v)&&v!==d&&t(p,v,{get:()=>h[v],enumerable:!(f=e(h,v))||f.enumerable});return p},a=p=>o(t({},"__esModule",{value:!0}),p),i={};s(i,{getContext:()=>c.getContext,getVercelOidcToken:()=>l,getVercelOidcTokenSync:()=>u}),Eu=a(i);var c=dC();async function l(){return""}function u(){return""}return Eu}var w2=pC(),fC="vercel.ai.gateway.error",xu=Symbol.for(fC),b2,k2,At=class b_ extends(k2=Error,b2=xu,k2){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[b2]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return b_.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&xu in e&&e[xu]===!0}},S2="GatewayAuthenticationError",hC=`vercel.ai.gateway.error.${S2}`,T2=Symbol.for(hC),C2,$2,Iu=class k_ extends($2=At,C2=T2,$2){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[C2]=!0,this.name=S2,this.type="authentication_error"}static isInstance(e){return At.hasMarker(e)&&T2 in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
548
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const t5=(e={})=>new e5(e);var c2="vercel.ai.error",r5=Symbol.for(c2),u2,d2,ve=class D1 extends(d2=Error,u2=r5,d2){constructor({name:t,message:r,cause:n}){super(r),this[u2]=!0,this.name=t,this.cause=n}static isInstance(t){return D1.hasMarker(t,c2)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},p2="AI_APICallError",f2=`vercel.ai.error.${p2}`,n5=Symbol.for(f2),h2,m2,ut=class extends(m2=ve,h2=n5,m2){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:p2,message:t,cause:i}),this[h2]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return ve.hasMarker(t,f2)}},g2="AI_EmptyResponseBodyError",y2=`vercel.ai.error.${g2}`,o5=Symbol.for(y2),v2,_2,s5=class extends(_2=ve,v2=o5,_2){constructor({message:t="Empty response body"}={}){super({name:g2,message:t}),this[v2]=!0}static isInstance(t){return ve.hasMarker(t,y2)}};function Jn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var w2="AI_InvalidArgumentError",b2=`vercel.ai.error.${w2}`,a5=Symbol.for(b2),k2,T2,C2=class extends(T2=ve,k2=a5,T2){constructor({message:t,cause:r,argument:n}){super({name:w2,message:t,cause:r}),this[k2]=!0,this.argument=n}static isInstance(t){return ve.hasMarker(t,b2)}},S2="AI_InvalidPromptError",I2=`vercel.ai.error.${S2}`,i5=Symbol.for(I2),E2,x2,Wn=class extends(x2=ve,E2=i5,x2){constructor({prompt:e,message:t,cause:r}){super({name:S2,message:`Invalid prompt: ${t}`,cause:r}),this[E2]=!0,this.prompt=e}static isInstance(e){return ve.hasMarker(e,I2)}},$2="AI_InvalidResponseDataError",R2=`vercel.ai.error.${$2}`,l5=Symbol.for(R2),P2,M2,ad=class extends(M2=ve,P2=l5,M2){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:$2,message:r}),this[P2]=!0,this.data=t}static isInstance(t){return ve.hasMarker(t,R2)}},O2="AI_JSONParseError",N2=`vercel.ai.error.${O2}`,c5=Symbol.for(N2),A2,q2,Xi=class extends(q2=ve,A2=c5,q2){constructor({text:t,cause:r}){super({name:O2,message:`JSON parsing failed: Text: ${t}.
549
+ Error message: ${Jn(r)}`,cause:r}),this[A2]=!0,this.text=t}static isInstance(t){return ve.hasMarker(t,N2)}},L2="AI_LoadAPIKeyError",j2=`vercel.ai.error.${L2}`,u5=Symbol.for(j2),D2,U2,el=class extends(U2=ve,D2=u5,U2){constructor({message:t}){super({name:L2,message:t}),this[D2]=!0}static isInstance(t){return ve.hasMarker(t,j2)}},z2="AI_TooManyEmbeddingValuesForCallError",Z2=`vercel.ai.error.${z2}`,d5=Symbol.for(Z2),F2,V2,p5=class extends(V2=ve,F2=d5,V2){constructor(e){super({name:z2,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[F2]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ve.hasMarker(e,Z2)}},H2="AI_TypeValidationError",B2=`vercel.ai.error.${H2}`,f5=Symbol.for(B2),J2,W2,Gn=class pp extends(W2=ve,J2=f5,W2){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:H2,message:`${o}: Value: ${JSON.stringify(t)}.
550
+ Error message: ${Jn(r)}`,cause:r}),this[J2]=!0,this.value=t,this.context=n}static isInstance(t){return ve.hasMarker(t,B2)}static wrap({value:t,cause:r,context:n}){var o,s,a;return pp.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new pp({value:t,cause:r,context:n})}},G2="AI_UnsupportedFunctionalityError",K2=`vercel.ai.error.${G2}`,h5=Symbol.for(K2),Y2,Q2,qr=class extends(Q2=ve,Y2=h5,Q2){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:G2,message:r}),this[Y2]=!0,this.functionality=t}static isInstance(t){return ve.hasMarker(t,K2)}};function Nt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function m5({tools:e=[],providerToolNames:t}){const r={},n={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];r[o.name]=s,n[s]=o.name}return{toProviderToolName:o=>{var s;return(s=r[o])!=null?s:o},toCustomToolName:o=>{var s;return(s=n[o])!=null?s:o}}}async function g5(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(X2());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(X2())};r?.addEventListener("abort",i)})}function X2(){return new DOMException("Delay was aborted","AbortError")}var js=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function Ro(e){return Object.fromEntries([...e.headers])}var{btoa:y5,atob:v5}=globalThis;function Po(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=v5(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Mo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return y5(t)}function Oo(e){return e instanceof Uint8Array?Mo(e):e}function _5(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var eg="AI_DownloadError",tg=`vercel.ai.error.${eg}`,w5=Symbol.for(tg),rg,ng,Sn=class extends(ng=ve,rg=w5,ng){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:eg,message:o,cause:n}),this[rg]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ve.hasMarker(e,tg)}},id=2*1024*1024*1024;async function og({response:e,url:t,maxBytes:r=id}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Sn({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:h}=await s.read();if(u)break;if(i+=h.length,i>r)throw new Sn({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(h)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}async function sg(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Sn({url:e,statusCode:o.status,statusText:o.statusText});const s=await og({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:id}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw Sn.isInstance(o)?o:new Sn({url:e,cause:o})}}var Ds=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new C2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Ut=Ds();function ld(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Kn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var b5=["fetch failed","failed to fetch"],k5=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function T5(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&k5.includes(t))}function ag({error:e,url:t,requestBodyValues:r}){if(Kn(e))return e;if(e instanceof TypeError&&b5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ut({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return T5(e)?new ut({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Us(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function C5(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function In(e,...t){const r=new Headers(C5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var ig="4.0.15",S5=()=>globalThis.fetch,lg=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=S5()})=>{try{const a=await s(e,{method:"GET",headers:In(t,`ai-sdk/provider-utils/${ig}`,Us()),signal:o}),i=Ro(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw Kn(c)||ut.isInstance(c)?c:new ut({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Kn(l)||ut.isInstance(l))?l:new ut({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw ag({error:a,url:e,requestBodyValues:{}})}};function I5(e){return e!=null}function E5({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function x5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new el({message:`${n} API key must be a string.`});if(typeof process>"u")throw new el({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new el({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new el({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function No({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function $5(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var R5=/"__proto__"\s*:/,P5=/"constructor"\s*:/;function cg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||R5.test(e)===!1&&P5.test(e)===!1?t:M5(t)}function M5(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function cd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return cg(e)}try{return cg(e)}finally{Error.stackTraceLimit=t}}function ud(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=Yn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Yn):Yn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Yn)),e.allOf!=null&&(e.allOf=e.allOf.map(Yn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Yn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Yn(t[r]);return e}function Yn(e){return typeof e=="boolean"?e:ud(e)}var O5=Symbol("Let zodToJsonSchema decide on which parser to use"),ug={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},N5=e=>typeof e=="string"?{...ug,name:e}:{...ug,...e};function tr(){return{}}function A5(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==B.ZodAny&&(s.items=We(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function q5(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function L5(){return{type:"boolean"}}function dg(e,t){return We(e.type._def,t)}var j5=(e,t)=>We(e.innerType._def,t);function pg(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>pg(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return D5(e)}}var D5=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function U5(e,t){return{...We(e.innerType._def,t),default:e.defaultValue()}}function z5(e,t){return t.effectStrategy==="input"?We(e.schema._def,t):tr()}function Z5(e){return{type:"string",enum:Array.from(e.values)}}var F5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function V5(e,t){const r=[We(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),We(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(F5(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function H5(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var dd=void 0,Cr={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:()=>(dd===void 0&&(dd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dd),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 fg(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Sr(r,"email",n.message,t);break;case"format:idn-email":Sr(r,"idn-email",n.message,t);break;case"pattern:zod":zt(r,Cr.email,n.message,t);break}break;case"url":Sr(r,"uri",n.message,t);break;case"uuid":Sr(r,"uuid",n.message,t);break;case"regex":zt(r,n.regex,n.message,t);break;case"cuid":zt(r,Cr.cuid,n.message,t);break;case"cuid2":zt(r,Cr.cuid2,n.message,t);break;case"startsWith":zt(r,RegExp(`^${pd(n.value,t)}`),n.message,t);break;case"endsWith":zt(r,RegExp(`${pd(n.value,t)}$`),n.message,t);break;case"datetime":Sr(r,"date-time",n.message,t);break;case"date":Sr(r,"date",n.message,t);break;case"time":Sr(r,"time",n.message,t);break;case"duration":Sr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{zt(r,RegExp(pd(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Sr(r,"ipv4",n.message,t),n.version!=="v4"&&Sr(r,"ipv6",n.message,t);break}case"base64url":zt(r,Cr.base64url,n.message,t);break;case"jwt":zt(r,Cr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&zt(r,Cr.ipv4Cidr,n.message,t),n.version!=="v4"&&zt(r,Cr.ipv6Cidr,n.message,t);break}case"emoji":zt(r,Cr.emoji(),n.message,t);break;case"ulid":{zt(r,Cr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Sr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{zt(r,Cr.base64,n.message,t);break}}break}case"nanoid":zt(r,Cr.nanoid,n.message,t)}return r}function pd(e,t){return t.patternStrategy==="escape"?J5(e):e}var B5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J5(e){let t="";for(let r=0;r<e.length;r++)B5.has(e[r])||(t+="\\"),t+=e[r];return t}function Sr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function zt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:hg(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=hg(t,n)}function hg(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
551
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
552
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
553
+ `:`[${o[c]}\r
554
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function mg(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=We(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===B.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=fg(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===B.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===B.ZodBranded&&e.keyType._def.type._def.typeName===B.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=dg(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function W5(e,t){if(t.mapStrategy==="record")return mg(e,t);const r=We(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||tr(),n=We(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||tr();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function G5(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function K5(){return{not:tr()}}function Y5(){return{type:"null"}}var fd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Q5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in fd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=fd[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return X5(e,t)}var X5=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>We(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function eI(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[fd[e.innerType._def.typeName],"null"]};const r=We(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function tI(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function rI(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=oI(i),c=We(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=nI(e,t);return s!==void 0&&(r.additionalProperties=s),r}function nI(e,t){if(e.catchall._def.typeName!=="ZodNever")return We(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function oI(e){try{return e.isOptional()}catch{return!0}}var sI=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return We(e.innerType._def,t);const n=We(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:tr()},n]}:tr()},aI=(e,t)=>{if(t.pipeStrategy==="input")return We(e.in._def,t);if(t.pipeStrategy==="output")return We(e.out._def,t);const r=We(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=We(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function iI(e,t){return We(e.type._def,t)}function lI(e,t){const n={type:"array",uniqueItems:!0,items:We(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function cI(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>We(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:We(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>We(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function uI(){return{not:tr()}}function dI(){return tr()}var pI=(e,t)=>We(e.innerType._def,t),fI=(e,t,r)=>{switch(t){case B.ZodString:return fg(e,r);case B.ZodNumber:return tI(e);case B.ZodObject:return rI(e,r);case B.ZodBigInt:return q5(e);case B.ZodBoolean:return L5();case B.ZodDate:return pg(e,r);case B.ZodUndefined:return uI();case B.ZodNull:return Y5();case B.ZodArray:return A5(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return Q5(e,r);case B.ZodIntersection:return V5(e,r);case B.ZodTuple:return cI(e,r);case B.ZodRecord:return mg(e,r);case B.ZodLiteral:return H5(e);case B.ZodEnum:return Z5(e);case B.ZodNativeEnum:return G5(e);case B.ZodNullable:return eI(e,r);case B.ZodOptional:return sI(e,r);case B.ZodMap:return W5(e,r);case B.ZodSet:return lI(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return iI(e,r);case B.ZodNaN:case B.ZodNever:return K5();case B.ZodEffects:return z5(e,r);case B.ZodAny:return tr();case B.ZodUnknown:return dI();case B.ZodDefault:return U5(e,r);case B.ZodBranded:return dg(e,r);case B.ZodReadonly:return pI(e,r);case B.ZodCatch:return j5(e,r);case B.ZodPipeline:return aI(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}},hI=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function We(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==O5)return l}if(o&&!r){const l=mI(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=fI(e,e.typeName,t),i=typeof a=="function"?We(a(),t):a;if(i&&gI(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var mI=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:hI(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),tr()):t.$refStrategy==="seen"?tr():void 0}},gI=(e,t,r)=>(e.description&&(r.description=e.description),r),yI=e=>{const t=N5(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},vI=(e,t)=>{var r;const n=yI(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var p;return{...c,[u]:(p=We(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:tr()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=We(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:tr(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},hd=Symbol.for("vercel.ai.schema");function Ce(e){let t;return()=>(t==null&&(t=e()),t)}function Ao(e,{validate:t}={}){return{[hd]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function _I(e){return typeof e=="object"&&e!==null&&hd in e&&e[hd]===!0&&"jsonSchema"in e&&"validate"in e}function Qn(e){return e==null?Ao({properties:{},additionalProperties:!1}):_I(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Te(e):wI(e):e()}function wI(e){return Ao(()=>ud(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new Gn({value:t,cause:r.issues})}}})}function bI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Ao(()=>vI(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function kI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Ao(()=>ud(Ah(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Lh(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function TI(e){return"_zod"in e}function Te(e,t){return TI(e)?kI(e):bI(e)}async function Pt({value:e,schema:t,context:r}){const n=await cr({value:e,schema:t,context:r});if(!n.success)throw Gn.wrap({value:e,cause:n.error,context:r});return n.value}async function cr({value:e,schema:t,context:r}){const n=Qn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:Gn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Gn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function CI({text:e,schema:t}){try{const r=cd(e);return t==null?r:Pt({value:r,schema:t})}catch(r){throw Xi.isInstance(r)||Gn.isInstance(r)?r:new Xi({text:e,cause:r})}}async function ur({text:e,schema:t}){try{const r=cd(e);return t==null?{success:!0,value:r,rawValue:r}:await cr({value:r,schema:t})}catch(r){return{success:!1,error:Xi.isInstance(r)?r:new Xi({text:e,cause:r}),rawValue:void 0}}}function gg(e){try{return cd(e),!0}catch{return!1}}function yg({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Io).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await ur({text:r,schema:t}))}}))}async function tn({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await cr({value:t[e],schema:r});if(!n.success)throw new C2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var SI=()=>globalThis.fetch,Jt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>_g({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),vg=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>_g({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),_g=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=SI()})=>{try{const i=await a(e,{method:"POST",headers:In(t,`ai-sdk/provider-utils/${ig}`,Us()),body:r.content,signal:s}),l=Ro(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Kn(u)||ut.isInstance(u)?u:new ut({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Kn(c)||ut.isInstance(c))?c:new ut({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw ag({error:i,url:e,requestBodyValues:r.values})}};function iM(e){return e}function wg(e){return{...e,type:"dynamic"}}function Ir({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Wt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var En=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Ro(n);if(a.trim()==="")return{responseHeaders:i,value:new ut({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await CI({text:a,schema:e});return{responseHeaders:i,value:new ut({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new ut({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},tl=e=>async({response:t})=>{const r=Ro(t);if(t.body==null)throw new s5({});return{responseHeaders:r,value:yg({stream:t.body,schema:e})}},dr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await ur({text:o,schema:e}),a=Ro(t);if(!s.success)throw new ut({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},II=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Ro(e);if(!e.body)throw new ut({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new ut({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function bg(e){return e?.replace(/\/$/,"")}function EI(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*xI({execute:e,input:t,options:r}){const n=e(t,r);if(EI(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}var md,kg;function $I(){if(kg)return md;kg=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,h)=>{for(var p in h)e(u,p,{get:h[p],enumerable:!0})},s=(u,h,p,f)=>{if(h&&typeof h=="object"||typeof h=="function")for(let g of r(h))!n.call(u,g)&&g!==p&&e(u,g,{get:()=>h[g],enumerable:!(f=t(h,g))||f.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),md=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return md}var gd,Tg;function RI(){if(Tg)return gd;Tg=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(h,p)=>{for(var f in p)e(h,f,{get:p[f],enumerable:!0})},s=(h,p,f,g)=>{if(p&&typeof p=="object"||typeof p=="function")for(let _ of r(p))!n.call(h,_)&&_!==f&&e(h,_,{get:()=>p[_],enumerable:!(g=t(p,_))||g.enumerable});return h},a=h=>s(e({},"__esModule",{value:!0}),h),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),gd=a(i);var l=$I();async function c(){return""}function u(){return""}return gd}var Cg=RI(),PI="vercel.ai.gateway.error",yd=Symbol.for(PI),Sg,Ig,Zt=class U1 extends(Ig=Error,Sg=yd,Ig){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Sg]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return U1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&yd in t&&t[yd]===!0}},Eg="GatewayAuthenticationError",MI=`vercel.ai.gateway.error.${Eg}`,xg=Symbol.for(MI),$g,Rg,vd=class z1 extends(Rg=Zt,$g=xg,Rg){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[$g]=!0,this.name=Eg,this.type="authentication_error"}static isInstance(t){return Zt.hasMarker(t)&&xg in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
555
555
 
556
556
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
557
557
 
558
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?a=`AI Gateway authentication failed: Invalid OIDC token.
558
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?i=`AI Gateway authentication failed: Invalid OIDC token.
559
559
 
560
560
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
561
561
 
562
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
562
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:i=`AI Gateway authentication failed: No authentication provided.
563
563
 
564
564
  Option 1 - API key:
565
565
  Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
566
566
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
567
567
 
568
568
  Option 2 - OIDC token:
569
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new k_({message:a,statusCode:s,cause:o})}},E2="GatewayInvalidRequestError",mC=`vercel.ai.gateway.error.${E2}`,x2=Symbol.for(mC),I2,R2,gC=class extends(R2=At,I2=x2,R2){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[I2]=!0,this.name=E2,this.type="invalid_request_error"}static isInstance(t){return At.hasMarker(t)&&x2 in t}},P2="GatewayRateLimitError",yC=`vercel.ai.gateway.error.${P2}`,O2=Symbol.for(yC),A2,M2,_C=class extends(M2=At,A2=O2,M2){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[A2]=!0,this.name=P2,this.type="rate_limit_exceeded"}static isInstance(t){return At.hasMarker(t)&&O2 in t}},N2="GatewayModelNotFoundError",vC=`vercel.ai.gateway.error.${N2}`,L2=Symbol.for(vC),wC=es(()=>kn(C({modelId:m()}))),j2,q2,z2=class extends(q2=At,j2=L2,q2){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[j2]=!0,this.name=N2,this.type="model_not_found",this.modelId=r}static isInstance(t){return At.hasMarker(t)&&L2 in t}},D2="GatewayInternalServerError",bC=`vercel.ai.gateway.error.${D2}`,U2=Symbol.for(bC),Z2,F2,V2=class extends(F2=At,Z2=U2,F2){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Z2]=!0,this.name=D2,this.type="internal_server_error"}static isInstance(t){return At.hasMarker(t)&&U2 in t}},H2="GatewayResponseError",kC=`vercel.ai.gateway.error.${H2}`,B2=Symbol.for(kC),J2,G2,SC=class extends(G2=At,J2=B2,G2){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:s}={}){super({message:t,statusCode:e,cause:s}),this[J2]=!0,this.name=H2,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return At.hasMarker(t)&&B2 in t}};async function W2({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await er({value:t,schema:TC});if(!o.success)return new SC({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:o.error,cause:n});const a=o.value,i=a.error.type,c=a.error.message;switch(i){case"authentication_error":return Iu.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new gC({message:c,statusCode:e,cause:n});case"rate_limit_exceeded":return new _C({message:c,statusCode:e,cause:n});case"model_not_found":{const l=await er({value:a.error.param,schema:wC});return new z2({message:c,statusCode:e,modelId:l.success?l.value.modelId:void 0,cause:n})}case"internal_server_error":return new V2({message:c,statusCode:e,cause:n});default:return new V2({message:c,statusCode:e,cause:n})}}var TC=es(()=>kn(C({error:C({message:m(),type:m().nullish(),param:Pe().nullish(),code:ie([m(),N()]).nullish()})})));function Yr(t,e){var r;return At.isInstance(t)?t:gt.isInstance(t)?W2({response:CC(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):W2({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function CC(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var K2="ai-gateway-auth-method";async function ns(t){const e=await er({value:t[K2],schema:$C});return e.success?e.value:void 0}var $C=es(()=>kn(ie([L("api-key"),L("oidc")]))),Y2=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await s2({url:`${this.config.baseURL}/config`,headers:await dr(this.config.headers()),successfulResponseHandler:rs(EC),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Yr(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await s2({url:`${t.origin}/v1/credits`,headers:await dr(this.config.headers()),successfulResponseHandler:rs(xC),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Yr(t)}}},EC=es(()=>kn(C({models:M(C({id:m(),name:m(),description:m().nullish(),pricing:C({input:m(),output:m(),input_cache_read:m().nullish(),input_cache_write:m().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:L("v2"),provider:m(),modelId:m()}),modelType:xe(["language","embedding","image"]).nullish()}))}))),xC=es(()=>kn(C({balance:m(),total_used:m()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),IC=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await dr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:i}=await ts({url:this.getUrl(),headers:Xn(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await dr(this.config.o11yHeaders)),body:e,successfulResponseHandler:rs(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:e},response:{headers:o,body:i},warnings:r}}catch(o){throw await Yr(o,await ns(s))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await dr(this.config.headers());try{const{value:o,responseHeaders:a}=await ts({url:this.getUrl(),headers:Xn(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await dr(this.config.o11yHeaders)),body:e,successfulResponseHandler:l2(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,c){if(i.success){const l=i.value;if(l.type==="raw"&&!t.includeRawChunks)return;l.type==="response-metadata"&&l.timestamp&&typeof l.timestamp=="string"&&(l.timestamp=new Date(l.timestamp)),c.enqueue(l)}else c.error(i.error)}})),request:{body:e},response:{headers:a}}}catch(o){throw await Yr(o,await ns(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},RC=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;const o=await dr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:c}=await ts({url:this.getUrl(),headers:Xn(o,e??{},this.getModelConfigHeaders(),await dr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...n?{providerOptions:n}:{}},successfulResponseHandler:rs(PC),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(s=i.usage)!=null?s:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:c}}}catch(a){throw await Yr(a,await ns(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},PC=es(()=>kn(C({embeddings:M(M(N())),usage:C({tokens:N()}).nullish(),providerMetadata:be(m(),be(m(),Pe())).optional()}))),OC=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c;const l=await dr(this.config.headers());try{const{responseHeaders:u,value:p,rawValue:h}=await ts({url:this.getUrl(),headers:Xn(l,a??{},this.getModelConfigHeaders(),await dr(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...s&&{seed:s},...o&&{providerOptions:o}},successfulResponseHandler:rs(MC),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:p.images,warnings:(c=p.warnings)!=null?c:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw Yr(u,await ns(l))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},AC=C({images:M(Pe()).optional()}).catchall(Pe()),MC=C({images:M(m()),warnings:M(C({type:L("other"),message:m()})).optional(),providerMetadata:be(m(),AC).optional()});async function NC(){var t;return(t=w2.getContext().headers)==null?void 0:t["x-vercel-id"]}var LC="2.0.18",jC="0.0.1";function qC(t={}){var e,r;let n=null,s=null;const o=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let a=0;const i=(r=g2(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",c=async()=>{const f=await DC(t);if(f)return Kr({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":jC,[K2]:f.authMethod,...t.headers},`ai-sdk/gateway/${LC}`);throw Iu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{const f=mi({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=mi({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),g=mi({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await NC();return{...f&&{"ai-o11y-deployment-id":f},...v&&{"ai-o11y-environment":v},...g&&{"ai-o11y-region":g},...w&&{"ai-o11y-request-id":w}}}},u=f=>new IC(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),p=async()=>{var f,v,g;const w=(g=(v=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:v.call(f).getTime())!=null?g:Date.now();return(!n||w-a>o)&&(a=w,n=new Y2({baseURL:i,headers:c,fetch:t.fetch}).getAvailableModels().then(y=>(s=y,y)).catch(async y=>{throw await Yr(y,await ns(await c()))})),s?Promise.resolve(s):n},h=async()=>new Y2({baseURL:i,headers:c,fetch:t.fetch}).getCredits().catch(async f=>{throw await Yr(f,await ns(await c()))}),d=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(f)};return d.getAvailableModels=p,d.getCredits=h,d.imageModel=f=>new OC(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),d.languageModel=u,d.textEmbeddingModel=f=>new RC(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),d}var zC=qC();async function DC(t){const e=mi({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await w2.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var UC=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Sn="1.9.0",Q2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function ZC(t){var e=new Set([t]),r=new Set,n=t.match(Q2);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function o(i){return r.add(i),!1}function a(i){return e.add(i),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(Q2);if(!l)return o(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||s.major!==u.major?o(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?a(c):o(c):s.minor<=u.minor?a(c):o(c)}}var FC=ZC(Sn),VC=Sn.split(".")[0],mo=Symbol.for("opentelemetry.js.api."+VC),go=UC;function yo(t,e,r,n){var s;n===void 0&&(n=!1);var o=go[mo]=(s=go[mo])!==null&&s!==void 0?s:{version:Sn};if(!n&&o[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(o.version!==Sn){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+Sn);return r.error(a.stack||a.message),!1}return o[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Sn+"."),!0}function Tn(t){var e,r,n=(e=go[mo])===null||e===void 0?void 0:e.version;if(!(!n||!FC(n)))return(r=go[mo])===null||r===void 0?void 0:r[t]}function _o(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Sn+".");var r=go[mo];r&&delete r[t]}var HC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},BC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},JC=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("verbose",this._namespace,e)},t})();function vo(t,e,r){var n=Tn("diag");if(n)return r.unshift(e),n[t].apply(n,BC([],HC(r),!1))}var Mt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Mt||(Mt={}));function GC(t,e){t<Mt.NONE?t=Mt.NONE:t>Mt.ALL&&(t=Mt.ALL),e=e||{};function r(n,s){var o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",Mt.ERROR),warn:r("warn",Mt.WARN),info:r("info",Mt.INFO),debug:r("debug",Mt.DEBUG),verbose:r("verbose",Mt.VERBOSE)}}var WC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},KC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},YC="diag",pr=(function(){function t(){function e(s){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var i=Tn("diag");if(i)return i[s].apply(i,KC([],WC(o),!1))}}var r=this,n=function(s,o){var a,i,c;if(o===void 0&&(o={logLevel:Mt.INFO}),s===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof o=="number"&&(o={logLevel:o});var u=Tn("diag"),p=GC((i=o.logLevel)!==null&&i!==void 0?i:Mt.INFO,s);if(u&&!o.suppressOverrideMessage){var h=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return yo("diag",p,r,!0)};r.setLogger=n,r.disable=function(){_o(YC,r)},r.createComponentLogger=function(s){return new JC(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),QC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},XC=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},e8=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=QC(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new t(this._entries);try{for(var a=XC(n),i=a.next();!i.done;i=a.next()){var c=i.value;o._entries.delete(c)}}catch(l){e={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return o},t.prototype.clear=function(){return new t},t})();pr.instance();function t8(t){return t===void 0&&(t={}),new e8(new Map(Object.entries(t)))}function X2(t){return Symbol.for(t)}var r8=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),n8=new r8,Cn=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),s8=(function(){function t(){}return t.prototype.createGauge=function(e,r){return h8},t.prototype.createHistogram=function(e,r){return m8},t.prototype.createCounter=function(e,r){return f8},t.prototype.createUpDownCounter=function(e,r){return g8},t.prototype.createObservableGauge=function(e,r){return _8},t.prototype.createObservableCounter=function(e,r){return y8},t.prototype.createObservableUpDownCounter=function(e,r){return v8},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),vi=(function(){function t(){}return t})(),o8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(vi),a8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(vi),i8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(vi),c8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(vi),Ru=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),l8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Ru),u8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Ru),d8=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Ru),p8=new s8,f8=new o8,h8=new i8,m8=new c8,g8=new a8,y8=new l8,_8=new u8,v8=new d8,w8={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},b8={set:function(t,e,r){t!=null&&(t[e]=r)}},k8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},S8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},T8=(function(){function t(){}return t.prototype.active=function(){return n8},t.prototype.with=function(e,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,S8([n],k8(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),C8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},$8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},Pu="context",E8=new T8,wi=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return yo(Pu,e,pr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(s=this._getContextManager()).with.apply(s,$8([e,r,n],C8(o),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Tn(Pu)||E8},t.prototype.disable=function(){this._getContextManager().disable(),_o(Pu,pr.instance())},t})(),Ou;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Ou||(Ou={}));var eg="0000000000000000",tg="00000000000000000000000000000000",x8={traceId:tg,spanId:eg,traceFlags:Ou.NONE},wo=(function(){function t(e){e===void 0&&(e=x8),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})(),Au=X2("OpenTelemetry Context Key SPAN");function Mu(t){return t.getValue(Au)||void 0}function I8(){return Mu(wi.getInstance().active())}function Nu(t,e){return t.setValue(Au,e)}function R8(t){return t.deleteValue(Au)}function P8(t,e){return Nu(t,new wo(e))}function rg(t){var e;return(e=Mu(t))===null||e===void 0?void 0:e.spanContext()}var O8=/^([0-9a-f]{32})$/i,A8=/^[0-9a-f]{16}$/i;function M8(t){return O8.test(t)&&t!==tg}function N8(t){return A8.test(t)&&t!==eg}function ng(t){return M8(t.traceId)&&N8(t.spanId)}function L8(t){return new wo(t)}var Lu=wi.getInstance(),sg=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Lu.active());var s=!!r?.root;if(s)return new wo;var o=n&&rg(n);return j8(o)&&ng(o)?new wo(o):new wo},t.prototype.startActiveSpan=function(e,r,n,s){var o,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,a=n,i=s);var c=a??Lu.active(),l=this.startSpan(e,o,c),u=Nu(c,l);return Lu.with(u,i,void 0,l)}},t})();function j8(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var q8=new sg,z8=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):q8},t})(),D8=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new sg},t})(),U8=new D8,og=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new z8(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:U8},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})(),bi;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(bi||(bi={})),wi.getInstance(),pr.instance();var Z8=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return p8},t})(),F8=new Z8,ju="metrics",V8=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return yo(ju,e,pr.instance())},t.prototype.getMeterProvider=function(){return Tn(ju)||F8},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){_o(ju,pr.instance())},t})();V8.getInstance();var H8=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})(),qu=X2("OpenTelemetry Baggage Key");function ag(t){return t.getValue(qu)||void 0}function B8(){return ag(wi.getInstance().active())}function J8(t,e){return t.setValue(qu,e)}function G8(t){return t.deleteValue(qu)}var zu="propagation",W8=new H8,K8=(function(){function t(){this.createBaggage=t8,this.getBaggage=ag,this.getActiveBaggage=B8,this.setBaggage=J8,this.deleteBaggage=G8}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return yo(zu,e,pr.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=b8),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=w8),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){_o(zu,pr.instance())},t.prototype._getGlobalPropagator=function(){return Tn(zu)||W8},t})();K8.getInstance();var Du="trace",Y8=(function(){function t(){this._proxyTracerProvider=new og,this.wrapSpanContext=L8,this.isSpanContextValid=ng,this.deleteSpan=R8,this.getSpan=Mu,this.getActiveSpan=I8,this.getSpanContext=rg,this.setSpan=Nu,this.setSpanContext=P8}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=yo(Du,this._proxyTracerProvider,pr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Tn(Du)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){_o(Du,pr.instance()),this._proxyTracerProvider=new og},t})(),Q8=Y8.getInstance(),X8=Object.defineProperty,e$=(t,e)=>{for(var r in e)X8(t,r,{get:e[r],enumerable:!0})},ig="AI_NoOutputSpecifiedError",cg=`vercel.ai.error.${ig}`,t$=Symbol.for(cg),lg,ug=class extends we{constructor({message:t="No output specified."}={}){super({name:ig,message:t}),this[lg]=!0}static isInstance(t){return we.hasMarker(t,cg)}};lg=t$;function r$(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let n=`${e} The tool "${r}" is not supported by this model`;return t.details&&(n+=` - ${t.details}`),n}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var n$="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",dg=!1,pg=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}dg||(dg=!0,console.info(n$));for(const r of t)console.warn(r$(r))}},fg="AI_InvalidArgumentError",hg=`vercel.ai.error.${fg}`,s$=Symbol.for(hg),mg,fr=class extends we{constructor({parameter:e,value:r,message:n}){super({name:fg,message:`Invalid argument for parameter ${e}: ${n}`}),this[mg]=!0,this.parameter=e,this.value=r}static isInstance(e){return we.hasMarker(e,hg)}};mg=s$;var gg="AI_InvalidToolInputError",yg=`vercel.ai.error.${gg}`,o$=Symbol.for(yg),_g,vg=class extends we{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Yn(r)}`}){super({name:gg,message:n,cause:r}),this[_g]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return we.hasMarker(t,yg)}};_g=o$;var wg="AI_NoObjectGeneratedError",bg=`vercel.ai.error.${wg}`,a$=Symbol.for(bg),kg,Sg=class extends we{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s,finishReason:o}){super({name:wg,message:t,cause:e}),this[kg]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(t){return we.hasMarker(t,bg)}};kg=a$;var Tg="AI_NoOutputGeneratedError",Cg=`vercel.ai.error.${Tg}`,i$=Symbol.for(Cg),$g,c$=class extends we{constructor({message:t="No output generated.",cause:e}={}){super({name:Tg,message:t,cause:e}),this[$g]=!0}static isInstance(t){return we.hasMarker(t,Cg)}};$g=i$;var Eg="AI_NoSuchToolError",xg=`vercel.ai.error.${Eg}`,l$=Symbol.for(xg),Ig,Uu=class extends we{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:Eg,message:r}),this[Ig]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return we.hasMarker(t,xg)}};Ig=l$;var Rg="AI_ToolCallRepairError",Pg=`vercel.ai.error.${Rg}`,u$=Symbol.for(Pg),Og,d$=class extends we{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Yn(t)}`}){super({name:Rg,message:r,cause:t}),this[Og]=!0,this.originalError=e}static isInstance(t){return we.hasMarker(t,Pg)}};Og=u$;var p$=class extends we{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Ag="AI_InvalidMessageRoleError",Mg=`vercel.ai.error.${Ag}`,f$=Symbol.for(Mg),Ng,h$=class extends we{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ag,message:e}),this[Ng]=!0,this.role=t}static isInstance(t){return we.hasMarker(t,Mg)}};Ng=f$;var Lg="AI_DownloadError",jg=`vercel.ai.error.${Lg}`,m$=Symbol.for(jg),qg,Zu=class extends we{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Lg,message:s,cause:n}),this[qg]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return we.hasMarker(t,jg)}};qg=m$;var zg="AI_RetryError",Dg=`vercel.ai.error.${zg}`,g$=Symbol.for(Dg),Ug,Zg=class extends we{constructor({message:t,reason:e,errors:r}){super({name:zg,message:t}),this[Ug]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return we.hasMarker(t,Dg)}};Ug=g$;function ki(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new p$({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return y$().languageModel(t)}function y$(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:zC}var _$=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],v$=t=>{const e=typeof t=="string"?Cu(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function w$(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?v$(t):t}function b$({data:t,signatures:e}){const r=w$(t),n=typeof r=="string"?Cu(r.substring(0,Math.min(r.length,24))):r;for(const s of e)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,a)=>o===null||n[a]===o))return s.mediaType}var Fg="5.0.106",k$=async({url:t})=>{var e;const r=t.toString();try{const n=await fetch(r,{headers:Kr({},`ai-sdk/${Fg}`,fo())});if(!n.ok)throw new Zu({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw Zu.isInstance(n)?n:new Zu({url:r,cause:n})}},S$=(t=k$)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function T$(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Vg=ie([m(),La(Uint8Array),La(ArrayBuffer),ah(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Hg(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=T$(t.toString());if(e==null||r==null)throw new we({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function C$(t){return typeof t=="string"?t:t instanceof ArrayBuffer?_i(new Uint8Array(t)):_i(t)}async function Bg({prompt:t,supportedUrls:e,download:r=S$()}){const n=await E$(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(s=>$$({message:s,downloadedAssets:n}))]}function $$({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>x$(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:a}=Hg(n.data);return{type:"file",data:o,filename:n.filename,mediaType:a??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:t.providerOptions};default:{const n=r;throw new h$({role:n})}}}async function E$(t,e,r){const n=t.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const i=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let c=o.type==="image"?o.image:o.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:i,data:c}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&nT({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await e(n);return Object.fromEntries(s.map((o,a)=>o==null?null:[n[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function x$(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n;const s=t.type;switch(s){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:a}=Hg(n);let i=a??t.mediaType,c=o;if(c instanceof URL){const l=e[c.toString()];l&&(c=l.data,i??(i=l.mediaType))}switch(s){case"image":return(c instanceof Uint8Array||typeof c=="string")&&(i=(r=b$({data:c,signatures:_$}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:c,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:c,providerOptions:t.providerOptions}}}}function Fu({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:a,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new fr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new fr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new fr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new fr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new fr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new fr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new fr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new fr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:i,seed:a}}function I$(t){return t!=null&&Object.keys(t).length>0}function Jg({tools:t,toolChoice:e,activeTools:r}){return I$(t)?{tools:(r!=null?Object.entries(t).filter(([s])=>r.includes(s)):Object.entries(t)).map(([s,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:yi(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var bo=oh(()=>ie([wc(),m(),N(),me(),be(m(),bo),M(bo)])),hr=be(m(),be(m(),bo)),Gg=C({type:L("text"),text:m(),providerOptions:hr.optional()}),R$=C({type:L("image"),image:ie([Vg,La(URL)]),mediaType:m().optional(),providerOptions:hr.optional()}),Wg=C({type:L("file"),data:ie([Vg,La(URL)]),filename:m().optional(),mediaType:m(),providerOptions:hr.optional()}),P$=C({type:L("reasoning"),text:m(),providerOptions:hr.optional()}),O$=C({type:L("tool-call"),toolCallId:m(),toolName:m(),input:Pe(),providerOptions:hr.optional(),providerExecuted:me().optional()}),A$=Xe("type",[C({type:L("text"),value:m()}),C({type:L("json"),value:bo}),C({type:L("error-text"),value:m()}),C({type:L("error-json"),value:bo}),C({type:L("content"),value:M(ie([C({type:L("text"),text:m()}),C({type:L("media"),data:m(),mediaType:m()})]))})]),Kg=C({type:L("tool-result"),toolCallId:m(),toolName:m(),output:A$,providerOptions:hr.optional()}),M$=C({role:L("system"),content:m(),providerOptions:hr.optional()}),N$=C({role:L("user"),content:ie([m(),M(ie([Gg,R$,Wg]))]),providerOptions:hr.optional()}),L$=C({role:L("assistant"),content:ie([m(),M(ie([Gg,Wg,P$,O$,Kg]))]),providerOptions:hr.optional()}),j$=C({role:L("tool"),content:M(Kg),providerOptions:hr.optional()}),q$=ie([M$,N$,L$,j$]);async function Yg(t){if(t.prompt==null&&t.messages==null)throw new Qn({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Qn({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Qn({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Qn({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Qn({prompt:t,message:"messages must not be empty"});const r=await er({value:e,schema:M(q$)});if(!r.success)throw new Qn({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Qg(t){return Iu.isInstance(t)||z2.isInstance(t)?new we({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function ss({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function Xg({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((o,[a,i])=>(o[`ai.settings.${a}`]=i,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[a,i])=>(o[`ai.telemetry.metadata.${a}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[a,i])=>(i!==void 0&&(o[`ai.request.headers.${a}`]=i),o),{})}}var z$={startSpan(){return Si},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Si);if(typeof r=="function")return r(Si);if(typeof n=="function")return n(Si)}},Si={spanContext(){return D$},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},D$={traceId:"",spanId:"",traceFlags:0};function ey({isEnabled:t=!1,tracer:e}={}){return t?e||Q8.getTracer("ai"):z$}function os({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async o=>{try{const a=await n(o);return s&&o.end(),a}catch(a){try{Vu(o,a)}finally{o.end()}throw a}})}function Vu(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:bi.ERROR,message:e.message})):t.setStatus({code:bi.ERROR})}function Dt({telemetry:t,attributes:e}){return t?.isEnabled!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(t?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(t?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function ty(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?C$(r.data):r.data}:r)})))}function ry(t,e){return{inputTokens:ko(t.inputTokens,e.inputTokens),outputTokens:ko(t.outputTokens,e.outputTokens),totalTokens:ko(t.totalTokens,e.totalTokens),reasoningTokens:ko(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:ko(t.cachedInputTokens,e.cachedInputTokens)}}function ko(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function Hu(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function U$({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let n;const s=r["retry-after-ms"];if(s){const a=parseFloat(s);Number.isNaN(a)||(n=a)}const o=r["retry-after"];if(o&&n===void 0){const a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var Z$=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>ny(s,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function ny(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:s},o=[]){try{return await t()}catch(a){if(vn(a)||e===0)throw a;const i=_u(a),c=[...o,a],l=c.length;if(l>e)throw new Zg({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:c});if(a instanceof Error&&gt.isInstance(a)&&a.isRetryable===!0&&l<=e)return await X5(U$({error:a,exponentialBackoffDelay:r}),{abortSignal:s}),ny(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:s},c);throw l===1?a:new Zg({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:c})}}function sy({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new fr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new fr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:Z$({maxRetries:r,abortSignal:e})}}function oy(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var ay=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=_i(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Cu(this.base64Data)),this.uint8ArrayData}},F$=class extends ay{constructor(t){super(t),this.type="file"}};async function iy({toolCall:t,tools:e,repairToolCall:r,system:n,messages:s}){try{if(e==null)throw new Uu({toolName:t.toolName});try{return await cy({toolCall:t,tools:e})}catch(o){if(r==null||!(Uu.isInstance(o)||vg.isInstance(o)))throw o;let a=null;try{a=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:c}=e[i];return yi(c).jsonSchema},system:n,messages:s,error:o})}catch(i){throw new d$({cause:i,originalError:o})}if(a==null)throw o;return await cy({toolCall:a,tools:e})}}catch(o){const a=await wn({text:t.input}),i=a.success?a.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:o,providerMetadata:t.providerMetadata}}}async function cy({toolCall:t,tools:e}){const r=t.toolName,n=e[r];if(n==null)throw new Uu({toolName:t.toolName,availableTools:Object.keys(e)});const s=yi(n.inputSchema),o=t.input.trim()===""?await er({value:{},schema:s}):await wn({text:t.input,schema:s});if(o.success===!1)throw new vg({toolName:r,toolInput:t.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var ly=class{constructor({content:t,finishReason:e,usage:r,warnings:n,request:s,response:o,providerMetadata:a}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=a}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function Bu(t){return({steps:e})=>e.length===t}async function uy({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function Ju({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Yn(t)}:r==="json"?{type:"error-json",value:dy(t)}:e?.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:dy(t)}}function dy(t){return t===void 0?null:t}function Gu({content:t,tools:e}){const r=[],n=t.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Ju({tool:e?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Ju({tool:e?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=t.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Ju({tool:e?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"}),...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}}));return s.length>0&&r.push({role:"tool",content:s}),r}var V$=uo({prefix:"aitxt",size:24});async function py({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Bu(1),experimental_output:u,experimental_telemetry:p,providerOptions:h,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:v,prepareStep:g=v,experimental_repairToolCall:w,experimental_download:y,experimental_context:_,_internal:{generateId:b=V$,currentDate:k=()=>new Date}={},onStepFinish:S,...T}){const x=ki(t),R=Hu(l),{maxRetries:j,retry:O}=sy({maxRetries:a,abortSignal:i}),D=Fu(T),U=Kr(c??{},`ai/${Fg}`),V=Xg({model:x,telemetry:p,headers:U,settings:{...D,maxRetries:j}}),ne=await Yg({system:n,prompt:s,messages:o}),fe=ey(p);try{return await os({name:"ai.generateText",attributes:Dt({telemetry:p,attributes:{...ss({operationId:"ai.generateText",telemetry:p}),...V,"ai.model.provider":x.provider,"ai.model.id":x.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:s,messages:o})}}}),tracer:fe,fn:async de=>{var te,ye,H,P,F,q,E;const I=Fu(T);let $,B=[],W=[];const _e=[],pe=[];do{const G=[...ne.messages,..._e],K=await g?.({model:x,steps:pe,stepNumber:pe.length,messages:G}),Q=ki((te=K?.model)!=null?te:x),ue=await Bg({prompt:{system:(ye=K?.system)!=null?ye:ne.system,messages:(H=K?.messages)!=null?H:G},supportedUrls:await Q.supportedUrls,download:y}),{toolChoice:he,tools:Ve}=Jg({tools:e,toolChoice:(P=K?.toolChoice)!=null?P:r,activeTools:(F=K?.activeTools)!=null?F:f});$=await O(()=>{var Ee;return os({name:"ai.generateText.doGenerate",attributes:Dt({telemetry:p,attributes:{...ss({operationId:"ai.generateText.doGenerate",telemetry:p}),...V,"ai.model.provider":Q.provider,"ai.model.id":Q.modelId,"ai.prompt.messages":{input:()=>ty(ue)},"ai.prompt.tools":{input:()=>Ve?.map($t=>JSON.stringify($t))},"ai.prompt.toolChoice":{input:()=>he!=null?JSON.stringify(he):void 0},"gen_ai.system":Q.provider,"gen_ai.request.model":Q.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(Ee=T.temperature)!=null?Ee:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:fe,fn:async $t=>{var Or,Et,ct,Zt,en,tn,ds,qi;const rt=await Q.doGenerate({...I,tools:Ve,toolChoice:he,responseFormat:u?.responseFormat,prompt:ue,providerOptions:h,abortSignal:i,headers:U}),Ar={id:(Et=(Or=rt.response)==null?void 0:Or.id)!=null?Et:b(),timestamp:(Zt=(ct=rt.response)==null?void 0:ct.timestamp)!=null?Zt:k(),modelId:(tn=(en=rt.response)==null?void 0:en.modelId)!=null?tn:Q.modelId,headers:(ds=rt.response)==null?void 0:ds.headers,body:(qi=rt.response)==null?void 0:qi.body};return $t.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":rt.finishReason,"ai.response.text":{output:()=>oy(rt.content)},"ai.response.toolCalls":{output:()=>{const Mr=fy(rt.content);return Mr==null?void 0:JSON.stringify(Mr)}},"ai.response.id":Ar.id,"ai.response.model":Ar.modelId,"ai.response.timestamp":Ar.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(rt.providerMetadata),"ai.usage.promptTokens":rt.usage.inputTokens,"ai.usage.completionTokens":rt.usage.outputTokens,"gen_ai.response.finish_reasons":[rt.finishReason],"gen_ai.response.id":Ar.id,"gen_ai.response.model":Ar.modelId,"gen_ai.usage.input_tokens":rt.usage.inputTokens,"gen_ai.usage.output_tokens":rt.usage.outputTokens}})),{...rt,response:Ar}}})});const Be=await Promise.all($.content.filter(Ee=>Ee.type==="tool-call").map(Ee=>iy({toolCall:Ee,tools:e,repairToolCall:w,system:n,messages:G})));for(const Ee of Be){if(Ee.invalid)continue;const $t=e[Ee.toolName];$t?.onInputAvailable!=null&&await $t.onInputAvailable({input:Ee.input,toolCallId:Ee.toolCallId,messages:G,abortSignal:i,experimental_context:_})}const X=Be.filter(Ee=>Ee.invalid&&Ee.dynamic);W=[];for(const Ee of X)W.push({type:"tool-error",toolCallId:Ee.toolCallId,toolName:Ee.toolName,input:Ee.input,error:_u(Ee.error),dynamic:!0});B=Be.filter(Ee=>!Ee.providerExecuted),e!=null&&W.push(...await H$({toolCalls:B.filter(Ee=>!Ee.invalid),tools:e,tracer:fe,telemetry:p,messages:G,abortSignal:i,experimental_context:_}));const ke=J$({content:$.content,toolCalls:Be,toolOutputs:W});_e.push(...Gu({content:ke,tools:e}));const wt=new ly({content:ke,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(q=$.request)!=null?q:{},response:{...$.response,messages:structuredClone(_e)}});pg((E=$.warnings)!=null?E:[]),pe.push(wt),await S?.(wt)}while(B.length>0&&W.length===B.length&&!await uy({stopConditions:R,steps:pe}));de.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>oy($.content)},"ai.response.toolCalls":{output:()=>{const G=fy($.content);return G==null?void 0:JSON.stringify(G)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const A=pe[pe.length-1];let Z;return A.finishReason==="stop"&&(Z=await u?.parseOutput({text:A.text},{response:A.response,usage:A.usage,finishReason:A.finishReason})),new B$({steps:pe,resolvedOutput:Z})}})}catch(de){throw Qg(de)}}async function H$({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:o,experimental_context:a}){return(await Promise.all(t.map(async({toolCallId:c,toolName:l,input:u})=>{const p=e[l];if(p?.execute!=null)return os({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...ss({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=y2({execute:p.execute.bind(p),input:u,options:{toolCallId:c,messages:s,abortSignal:o,experimental_context:a}});let f;for await(const v of d)v.type==="final"&&(f=v.output);try{h.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:u,output:f,dynamic:p.type==="dynamic"}}catch(d){return Vu(h,d),{type:"tool-error",toolCallId:c,toolName:l,input:u,error:d,dynamic:p.type==="dynamic"}}}})}))).filter(c=>c!=null)}var B$=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>ry(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new ug;return this.resolvedOutput}};function fy(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function J$({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new ay(n)};case"tool-call":return e.find(s=>s.toolCallId===n.toolCallId);case"tool-result":{const s=e.find(o=>o.toolCallId===n.toolCallId);if(s==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,error:n.result,providerExecuted:!0,dynamic:s.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,output:n.result,providerExecuted:!0,dynamic:s.dynamic}}}}),...r]}function Ti(t,e){const r=new Headers(t??{});for(const[n,s]of Object.entries(e))r.has(n)||r.set(n,s);return r}function G$({status:t,statusText:e,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:Ti(r,{"content-type":"text/plain; charset=utf-8"})})}function hy({response:t,status:e,statusText:r,headers:n,stream:s}){t.writeHead(e??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:i,value:c}=await o.read();if(i)break;t.write(c)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function W$({response:t,status:e,statusText:r,headers:n,textStream:s}){hy({response:t,status:e,statusText:r,headers:Object.fromEntries(Ti(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var my=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
569
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new z1({message:i,statusCode:o,cause:s,generationId:a})}},Pg="GatewayInvalidRequestError",OI=`vercel.ai.gateway.error.${Pg}`,Mg=Symbol.for(OI),Og,Ng,NI=class extends(Ng=Zt,Og=Mg,Ng){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Og]=!0,this.name=Pg,this.type="invalid_request_error"}static isInstance(e){return Zt.hasMarker(e)&&Mg in e}},Ag="GatewayRateLimitError",AI=`vercel.ai.gateway.error.${Ag}`,qg=Symbol.for(AI),Lg,jg,qI=class extends(jg=Zt,Lg=qg,jg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Lg]=!0,this.name=Ag,this.type="rate_limit_exceeded"}static isInstance(e){return Zt.hasMarker(e)&&qg in e}},Dg="GatewayModelNotFoundError",LI=`vercel.ai.gateway.error.${Dg}`,Ug=Symbol.for(LI),jI=Ce(()=>Te(C({modelId:d()}))),zg,Zg,DI=class extends(Zg=Zt,zg=Ug,Zg){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[zg]=!0,this.name=Dg,this.type="model_not_found",this.modelId=r}static isInstance(e){return Zt.hasMarker(e)&&Ug in e}},Fg="GatewayInternalServerError",UI=`vercel.ai.gateway.error.${Fg}`,Vg=Symbol.for(UI),Hg,Bg,Jg=class extends(Bg=Zt,Hg=Vg,Bg){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Hg]=!0,this.name=Fg,this.type="internal_server_error"}static isInstance(e){return Zt.hasMarker(e)&&Vg in e}},Wg="GatewayResponseError",zI=`vercel.ai.gateway.error.${Wg}`,Gg=Symbol.for(zI),Kg,Yg,ZI=class extends(Yg=Zt,Kg=Gg,Yg){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[Kg]=!0,this.name=Wg,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Zt.hasMarker(e)&&Gg in e}};async function Qg({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await cr({value:e,schema:FI});if(!a.success){const h=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new ZI({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:h})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return vd.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new NI({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new qI({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const h=await cr({value:i.error.param,schema:jI});return new DI({message:c,statusCode:t,modelId:h.success?h.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Jg({message:c,statusCode:t,cause:n,generationId:u});default:return new Jg({message:c,statusCode:t,cause:n,generationId:u})}}var FI=Ce(()=>Te(C({error:C({message:d(),type:d().nullish(),param:Me().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),Xg="GatewayTimeoutError",VI=`vercel.ai.gateway.error.${Xg}`,ey=Symbol.for(VI),ty,ry,ny=class Z1 extends(ry=Zt,ty=ey,ry){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[ty]=!0,this.name=Xg,this.type="timeout_error"}static isInstance(t){return Zt.hasMarker(t)&&ey in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
570
570
 
571
- `)},flush(t){t.enqueue(`data: [DONE]
571
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new Z1({message:s,statusCode:r,cause:n,generationId:o})}};function oy(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function rn(e,t){var r;return Zt.isInstance(e)?e:oy(e)?ny.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ut.isInstance(e)?e.cause&&oy(e.cause)?ny.createTimeoutError({originalMessage:e.message,cause:e}):await Qg({response:HI(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Qg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function HI(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var sy="ai-gateway-auth-method";async function Xn(e){const t=await cr({value:e[sy],schema:BI});return t.success?t.value:void 0}var BI=Ce(()=>Te(oe([$("api-key"),$("oidc")]))),ay=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await lg({url:`${this.config.baseURL}/config`,headers:await Wt(this.config.headers()),successfulResponseHandler:dr(JI),failedResponseHandler:En({errorSchema:bt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await rn(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await lg({url:`${e.origin}/v1/credits`,headers:await Wt(this.config.headers()),successfulResponseHandler:dr(WI),failedResponseHandler:En({errorSchema:bt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await rn(e)}}},JI=Ce(()=>Te(C({models:q(C({id:d(),name:d(),description:d().nullish(),pricing:C({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:$("v3"),provider:d(),modelId:d()}),modelType:we(["embedding","image","language","video"]).nullish()}))}))),WI=Ce(()=>Te(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),GI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Wt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Jt({url:this.getUrl(),headers:Nt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Wt(this.config.o11yHeaders)),body:t,successfulResponseHandler:dr(bt()),failedResponseHandler:En({errorSchema:bt(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await rn(s,await Xn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Wt(this.config.headers());try{const{value:s,responseHeaders:a}=await Jt({url:this.getUrl(),headers:Nt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Wt(this.config.o11yHeaders)),body:t,successfulResponseHandler:tl(bt()),failedResponseHandler:En({errorSchema:bt(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await rn(s,await Xn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},KI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Wt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Jt({url:this.getUrl(),headers:Nt(s,t??{},this.getModelConfigHeaders(),await Wt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:dr(YI),failedResponseHandler:En({errorSchema:bt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await rn(a,await Xn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},YI=Ce(()=>Te(C({embeddings:q(q(j())),usage:C({tokens:j()}).nullish(),providerMetadata:ye(d(),ye(d(),Me())).optional()}))),QI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,h,p,f;const g=await Wt(this.config.headers());try{const{responseHeaders:_,value:y,rawValue:w}=await Jt({url:this.getUrl(),headers:Nt(g,l??{},this.getModelConfigHeaders(),await Wt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(v=>iy(v))},...a&&{mask:iy(a)}},successfulResponseHandler:dr(rE),failedResponseHandler:En({errorSchema:bt(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(u=y.warnings)!=null?u:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:_},...y.usage!=null&&{usage:{inputTokens:(h=y.usage.inputTokens)!=null?h:void 0,outputTokens:(p=y.usage.outputTokens)!=null?p:void 0,totalTokens:(f=y.usage.totalTokens)!=null?f:void 0}}}}catch(_){throw await rn(_,await Xn(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function iy(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Mo(e.data)}:e}var XI=C({images:q(Me()).optional()}).catchall(Me()),eE=ze("type",[C({type:$("unsupported"),feature:d(),details:d().optional()}),C({type:$("compatibility"),feature:d(),details:d().optional()}),C({type:$("other"),message:d()})]),tE=C({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),rE=C({images:q(d()),warnings:q(eE).optional(),providerMetadata:ye(d(),XI).optional(),usage:tE.optional()}),nE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var h;const p=await Wt(this.config.headers());try{const{responseHeaders:f,value:g}=await Jt({url:this.getUrl(),headers:Nt(p,c??{},this.getModelConfigHeaders(),await Wt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:oE(i)}},successfulResponseHandler:async({response:_,url:y,requestBodyValues:w})=>{if(_.body==null)throw new ut({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:_.status});const m=yg({stream:_.body,schema:lE}).getReader(),{done:S,value:k}=await m.read();if(m.releaseLock(),S||!k)throw new ut({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:_.status});if(!k.success)throw new ut({message:"Failed to parse video SSE event",cause:k.error,url:y,requestBodyValues:w,statusCode:_.status});const T=k.value;if(T.type==="error")throw new ut({message:T.message,statusCode:T.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([..._.headers]),responseBody:JSON.stringify(T),data:{error:{message:T.message,type:T.errorType,param:T.param}}});return{value:{videos:T.videos,warnings:T.warnings,providerMetadata:T.providerMetadata},responseHeaders:Object.fromEntries([..._.headers])}},failedResponseHandler:En({errorSchema:bt(),errorToMessage:_=>_}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:g.videos,warnings:(h=g.warnings)!=null?h:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await rn(f,await Xn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function oE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Mo(e.data)}:e}var sE=C({videos:q(Me()).optional()}).catchall(Me()),aE=oe([C({type:$("url"),url:d(),mediaType:d()}),C({type:$("base64"),data:d(),mediaType:d()})]),iE=ze("type",[C({type:$("unsupported"),feature:d(),details:d().optional()}),C({type:$("compatibility"),feature:d(),details:d().optional()}),C({type:$("other"),message:d()})]),lE=ze("type",[C({type:$("result"),videos:q(aE),warnings:q(iE).optional(),providerMetadata:ye(d(),sE).optional()}),C({type:$("error"),message:d(),errorType:d(),statusCode:j(),param:Me().nullable()})]),cE=Ce(()=>Te(Ft({objective:Fe().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Gr(Fe()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:as(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:sr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Ft({include_domains:Gr(Fe()).optional().describe("List of domains to include in search results."),exclude_domains:Gr(Fe()).optional().describe("List of domains to exclude from search results."),after_date:Fe().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:Ft({max_chars_per_result:sr().optional().describe("Maximum characters per result."),max_chars_total:sr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Ft({max_age_seconds:sr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),uE=Ce(()=>Te(pi([Ft({searchId:Fe(),results:Gr(Ft({url:Fe(),title:Fe(),excerpt:Fe(),publishDate:Fe().nullable().optional(),relevanceScore:sr().optional()}))}),Ft({error:as(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:sr().optional(),message:Fe()})]))),dE=Ir({id:"gateway.parallel_search",inputSchema:cE,outputSchema:uE}),pE=(e={})=>dE(e),fE=Ce(()=>Te(Ft({query:pi([Fe(),Gr(Fe())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:sr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:sr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:sr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Fe().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Gr(Fe()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Gr(Fe()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Fe().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Fe().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Fe().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Fe().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:as(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),hE=Ce(()=>Te(pi([Ft({results:Gr(Ft({title:Fe(),url:Fe(),snippet:Fe(),date:Fe().optional(),lastUpdated:Fe().optional()})),id:Fe()}),Ft({error:as(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:sr().optional(),message:Fe()})]))),mE=Ir({id:"gateway.perplexity_search",inputSchema:fE,outputSchema:hE}),gE=(e={})=>mE(e),yE={parallelSearch:pE,perplexitySearch:gE};async function vE(){var e;return(e=Cg.getContext().headers)==null?void 0:e["x-vercel-id"]}var _E="3.0.55",wE="0.0.1";function bE(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=bg(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const _=await TE(e);return In({Authorization:`Bearer ${_.token}`,"ai-gateway-protocol-version":wE,[sy]:_.authMethod,...e.headers},`ai-sdk/gateway/${_E}`)}catch(_){throw vd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:_})}},c=()=>{const _=No({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=No({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=No({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),v=No({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const m=await vE();return{..._&&{"ai-o11y-deployment-id":_},...y&&{"ai-o11y-environment":y},...w&&{"ai-o11y-region":w},...m&&{"ai-o11y-request-id":m},...v&&{"ai-o11y-project-id":v}}}},u=_=>new GI(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var _,y,w;const v=(w=(y=(_=e._internal)==null?void 0:_.currentDate)==null?void 0:y.call(_).getTime())!=null?w:Date.now();return(!n||v-a>s)&&(a=v,n=new ay({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(m=>(o=m,m)).catch(async m=>{throw await rn(m,await Xn(await l()))})),o?Promise.resolve(o):n},p=async()=>new ay({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async _=>{throw await rn(_,await Xn(await l()))}),f=function(_){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(_)};f.specificationVersion="v3",f.getAvailableModels=h,f.getCredits=p,f.imageModel=_=>new QI(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=_=>new KI(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=_=>new nE(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.chat=f.languageModel,f.embedding=f.embeddingModel,f.image=f.imageModel,f.video=f.videoModel,f.tools=yE,f}var kE=bE();async function TE(e){const t=No({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Cg.getVercelOidcToken(),authMethod:"oidc"}}var CE=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},eo="1.9.0",ly=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function SE(e){var t=new Set([e]),r=new Set,n=e.match(ly);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(ly);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var IE=SE(eo),EE=eo.split(".")[0],zs=Symbol.for("opentelemetry.js.api."+EE),Zs=CE;function Fs(e,t,r,n){var o;n===void 0&&(n=!1);var s=Zs[zs]=(o=Zs[zs])!==null&&o!==void 0?o:{version:eo};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==eo){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+eo);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+eo+"."),!0}function to(e){var t,r,n=(t=Zs[zs])===null||t===void 0?void 0:t.version;if(!(!n||!IE(n)))return(r=Zs[zs])===null||r===void 0?void 0:r[e]}function Vs(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+eo+".");var r=Zs[zs];r&&delete r[e]}var xE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},$E=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},RE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Hs("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Hs("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Hs("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Hs("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Hs("verbose",this._namespace,t)},e})();function Hs(e,t,r){var n=to("diag");if(n)return r.unshift(t),n[e].apply(n,$E([],xE(r),!1))}var rr;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(rr||(rr={}));function PE(e,t){e<rr.NONE?e=rr.NONE:e>rr.ALL&&(e=rr.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",rr.ERROR),warn:r("warn",rr.WARN),info:r("info",rr.INFO),debug:r("debug",rr.DEBUG),verbose:r("verbose",rr.VERBOSE)}}var ME=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},OE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},NE="diag",Lr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=to("diag");if(i)return i[o].apply(i,OE([],ME(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:rr.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=to("diag"),h=PE((i=s.logLevel)!==null&&i!==void 0?i:rr.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),h.warn("Current logger will overwrite one already registered from "+p)}return Fs("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Vs(NE,r)},r.createComponentLogger=function(o){return new RE(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),AE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},qE=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},LE=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=AE(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=qE(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();Lr.instance();function jE(e){return e===void 0&&(e={}),new LE(new Map(Object.entries(e)))}function cy(e){return Symbol.for(e)}var DE=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),UE=new DE,ro=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),zE=(function(){function e(){}return e.prototype.createGauge=function(t,r){return YE},e.prototype.createHistogram=function(t,r){return QE},e.prototype.createCounter=function(t,r){return KE},e.prototype.createUpDownCounter=function(t,r){return XE},e.prototype.createObservableGauge=function(t,r){return tx},e.prototype.createObservableCounter=function(t,r){return ex},e.prototype.createObservableUpDownCounter=function(t,r){return rx},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),rl=(function(){function e(){}return e})(),ZE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(rl),FE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(rl),VE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(rl),HE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(rl),_d=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),BE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(_d),JE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(_d),WE=(function(e){ro(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(_d),GE=new zE,KE=new ZE,YE=new VE,QE=new HE,XE=new FE,ex=new BE,tx=new JE,rx=new WE,nx={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},ox={set:function(e,t,r){e!=null&&(e[t]=r)}},sx=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},ax=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},ix=(function(){function e(){}return e.prototype.active=function(){return UE},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,ax([n],sx(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),lx=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},cx=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},wd="context",ux=new ix,nl=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Fs(wd,t,Lr.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,cx([t,r,n],lx(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return to(wd)||ux},e.prototype.disable=function(){this._getContextManager().disable(),Vs(wd,Lr.instance())},e})(),bd;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(bd||(bd={}));var uy="0000000000000000",dy="00000000000000000000000000000000",dx={traceId:dy,spanId:uy,traceFlags:bd.NONE},Bs=(function(){function e(t){t===void 0&&(t=dx),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),kd=cy("OpenTelemetry Context Key SPAN");function Td(e){return e.getValue(kd)||void 0}function px(){return Td(nl.getInstance().active())}function Cd(e,t){return e.setValue(kd,t)}function fx(e){return e.deleteValue(kd)}function hx(e,t){return Cd(e,new Bs(t))}function py(e){var t;return(t=Td(e))===null||t===void 0?void 0:t.spanContext()}var mx=/^([0-9a-f]{32})$/i,gx=/^[0-9a-f]{16}$/i;function yx(e){return mx.test(e)&&e!==dy}function vx(e){return gx.test(e)&&e!==uy}function fy(e){return yx(e.traceId)&&vx(e.spanId)}function _x(e){return new Bs(e)}var Sd=nl.getInstance(),hy=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Sd.active());var o=!!r?.root;if(o)return new Bs;var s=n&&py(n);return wx(s)&&fy(s)?new Bs(s):new Bs},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??Sd.active(),c=this.startSpan(t,s,l),u=Cd(l,c);return Sd.with(u,i,void 0,c)}},e})();function wx(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var bx=new hy,kx=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):bx},e})(),Tx=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new hy},e})(),Cx=new Tx,my=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new kx(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Cx},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),ol;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ol||(ol={}));var gy=nl.getInstance();Lr.instance();var Sx=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return GE},e})(),Ix=new Sx,Id="metrics",Ex=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Fs(Id,t,Lr.instance())},e.prototype.getMeterProvider=function(){return to(Id)||Ix},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Vs(Id,Lr.instance())},e})();Ex.getInstance();var xx=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ed=cy("OpenTelemetry Baggage Key");function yy(e){return e.getValue(Ed)||void 0}function $x(){return yy(nl.getInstance().active())}function Rx(e,t){return e.setValue(Ed,t)}function Px(e){return e.deleteValue(Ed)}var xd="propagation",Mx=new xx,Ox=(function(){function e(){this.createBaggage=jE,this.getBaggage=yy,this.getActiveBaggage=$x,this.setBaggage=Rx,this.deleteBaggage=Px}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Fs(xd,t,Lr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=ox),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=nx),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Vs(xd,Lr.instance())},e.prototype._getGlobalPropagator=function(){return to(xd)||Mx},e})();Ox.getInstance();var $d="trace",Nx=(function(){function e(){this._proxyTracerProvider=new my,this.wrapSpanContext=_x,this.isSpanContextValid=fy,this.deleteSpan=fx,this.getSpan=Td,this.getActiveSpan=px,this.getSpanContext=py,this.setSpan=Cd,this.setSpanContext=hx}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Fs($d,this._proxyTracerProvider,Lr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return to($d)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Vs($d,Lr.instance()),this._proxyTracerProvider=new my},e})(),Ax=Nx.getInstance(),qx=Object.defineProperty,Lx=(e,t)=>{for(var r in t)qx(e,r,{get:t[r],enumerable:!0})},vy="AI_InvalidArgumentError",_y=`vercel.ai.error.${vy}`,jx=Symbol.for(_y),wy,jr=class extends ve{constructor({parameter:t,value:r,message:n}){super({name:vy,message:`Invalid argument for parameter ${t}: ${n}`}),this[wy]=!0,this.parameter=t,this.value=r}static isInstance(t){return ve.hasMarker(t,_y)}};wy=jx;var by="AI_InvalidToolApprovalError",ky=`vercel.ai.error.${by}`,Dx=Symbol.for(ky),Ty,Ux=class extends ve{constructor({approvalId:e}){super({name:by,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Ty]=!0,this.approvalId=e}static isInstance(e){return ve.hasMarker(e,ky)}};Ty=Dx;var Cy="AI_InvalidToolInputError",Sy=`vercel.ai.error.${Cy}`,zx=Symbol.for(Sy),Iy,Rd=class extends ve{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Jn(r)}`}){super({name:Cy,message:n,cause:r}),this[Iy]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ve.hasMarker(e,Sy)}};Iy=zx;var Ey="AI_ToolCallNotFoundForApprovalError",xy=`vercel.ai.error.${Ey}`,Zx=Symbol.for(xy),$y,Pd=class extends ve{constructor({toolCallId:e,approvalId:t}){super({name:Ey,message:`Tool call "${e}" not found for approval request "${t}".`}),this[$y]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ve.hasMarker(e,xy)}};$y=Zx;var Ry="AI_MissingToolResultsError",Py=`vercel.ai.error.${Ry}`,Fx=Symbol.for(Py),My,Oy=class extends ve{constructor({toolCallIds:e}){super({name:Ry,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[My]=!0,this.toolCallIds=e}static isInstance(e){return ve.hasMarker(e,Py)}};My=Fx;var Ny="AI_NoObjectGeneratedError",Ay=`vercel.ai.error.${Ny}`,Vx=Symbol.for(Ay),qy,xn=class extends ve{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Ny,message:e,cause:t}),this[qy]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ve.hasMarker(e,Ay)}};qy=Vx;var Ly="AI_NoOutputGeneratedError",jy=`vercel.ai.error.${Ly}`,Hx=Symbol.for(jy),Dy,Uy=class extends ve{constructor({message:e="No output generated.",cause:t}={}){super({name:Ly,message:e,cause:t}),this[Dy]=!0}static isInstance(e){return ve.hasMarker(e,jy)}};Dy=Hx;var zy="AI_NoSuchToolError",Zy=`vercel.ai.error.${zy}`,Bx=Symbol.for(Zy),Fy,Md=class extends ve{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:zy,message:r}),this[Fy]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ve.hasMarker(e,Zy)}};Fy=Bx;var Vy="AI_ToolCallRepairError",Hy=`vercel.ai.error.${Vy}`,Jx=Symbol.for(Hy),By,Wx=class extends ve{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Jn(e)}`}){super({name:Vy,message:r,cause:e}),this[By]=!0,this.originalError=t}static isInstance(e){return ve.hasMarker(e,Hy)}};By=Jx;var Gx=class extends ve{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Jy="AI_UIMessageStreamError",Wy=`vercel.ai.error.${Jy}`,Kx=Symbol.for(Wy),Gy,qo=class extends ve{constructor({chunkType:e,chunkId:t,message:r}){super({name:Jy,message:r}),this[Gy]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ve.hasMarker(e,Wy)}};Gy=Kx;var Ky="AI_InvalidMessageRoleError",Yy=`vercel.ai.error.${Ky}`,Yx=Symbol.for(Yy),Qy,Qx=class extends ve{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ky,message:t}),this[Qy]=!0,this.role=e}static isInstance(e){return ve.hasMarker(e,Yy)}};Qy=Yx;var Xy="AI_RetryError",ev=`vercel.ai.error.${Xy}`,Xx=Symbol.for(ev),tv,rv=class extends ve{constructor({message:e,reason:t,errors:r}){super({name:Xy,message:e}),this[tv]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ve.hasMarker(e,ev)}};tv=Xx;function e8({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var t8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",nv=!1,Od=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}nv||(nv=!0,console.info(t8));for(const r of e.warnings)console.warn(e8({warning:r,provider:e.provider,model:e.model}))}};function r8({provider:e,modelId:t}){Od({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function n8(e){return e.specificationVersion==="v3"?e:(r8({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:ov(o.finishReason),usage:sv(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:o8(o.stream)}};default:return t[r]}}}))}function o8(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:ov(t.finishReason),usage:sv(t.usage)});break;default:r.enqueue(t);break}}}))}function ov(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function sv(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function sl(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new Gx({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return n8(e)}return s8().languageModel(e)}function s8(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:kE}function Nd(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function av(e){if(!(e==null||typeof e=="number"))return e.stepMs}function a8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var i8=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],l8=e=>{const t=typeof e=="string"?Po(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function c8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?l8(e):e}function u8({data:e,signatures:t}){const r=c8(e),n=typeof r=="string"?Po(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var iv="6.0.99",d8=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:In({},`ai-sdk/${iv}`,Us()),signal:r});if(!s.ok)throw new Sn({url:o,statusCode:s.status,statusText:s.statusText});return{data:await og({response:s,url:o,maxBytes:t??id}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Sn.isInstance(s)?s:new Sn({url:o,cause:s})}},p8=(e=d8)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function f8(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var lv=oe([d(),Ti(Uint8Array),Ti(ArrayBuffer),Kh(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function cv(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=f8(e.toString());if(t==null||r==null)throw new ve({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function h8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Mo(new Uint8Array(e)):Mo(e)}function Js(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function uv({prompt:e,supportedUrls:t,download:r=p8()}){const n=await g8(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const h=o.get(u.approvalId);h&&s.add(h)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Js(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>m8({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new Oy({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Oy({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function m8({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>y8(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=cv(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:dv(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:dv(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new Qx({role:n})}}}async function g8(e,t,r){const n=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&E5({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function y8(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=cv(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=u8({data:l,signatures:i8}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function dv(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function Ws({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Jn(r)}:o==="json"?{type:"error-json",value:pv(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:pv(r)}}function pv(e){return e===void 0?null:e}function Ad({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new jr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new jr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new jr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new jr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new jr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new jr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new jr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new jr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function v8(e){return e!=null&&Object.keys(e).length>0}async function fv({tools:e,toolChoice:t,activeTools:r}){if(!v8(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Qn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var Gs=dc(()=>oe([ki(),d(),j(),me(),ye(d(),Gs.optional()),q(Gs)])),dt=ye(d(),ye(d(),Gs.optional())),hv=C({type:$("text"),text:d(),providerOptions:dt.optional()}),_8=C({type:$("image"),image:oe([lv,Ti(URL)]),mediaType:d().optional(),providerOptions:dt.optional()}),mv=C({type:$("file"),data:oe([lv,Ti(URL)]),filename:d().optional(),mediaType:d(),providerOptions:dt.optional()}),w8=C({type:$("reasoning"),text:d(),providerOptions:dt.optional()}),b8=C({type:$("tool-call"),toolCallId:d(),toolName:d(),input:Me(),providerOptions:dt.optional(),providerExecuted:me().optional()}),k8=ze("type",[C({type:$("text"),value:d(),providerOptions:dt.optional()}),C({type:$("json"),value:Gs,providerOptions:dt.optional()}),C({type:$("execution-denied"),reason:d().optional(),providerOptions:dt.optional()}),C({type:$("error-text"),value:d(),providerOptions:dt.optional()}),C({type:$("error-json"),value:Gs,providerOptions:dt.optional()}),C({type:$("content"),value:q(oe([C({type:$("text"),text:d(),providerOptions:dt.optional()}),C({type:$("media"),data:d(),mediaType:d()}),C({type:$("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:dt.optional()}),C({type:$("file-url"),url:d(),providerOptions:dt.optional()}),C({type:$("file-id"),fileId:oe([d(),ye(d(),d())]),providerOptions:dt.optional()}),C({type:$("image-data"),data:d(),mediaType:d(),providerOptions:dt.optional()}),C({type:$("image-url"),url:d(),providerOptions:dt.optional()}),C({type:$("image-file-id"),fileId:oe([d(),ye(d(),d())]),providerOptions:dt.optional()}),C({type:$("custom"),providerOptions:dt.optional()})]))})]),gv=C({type:$("tool-result"),toolCallId:d(),toolName:d(),output:k8,providerOptions:dt.optional()}),T8=C({type:$("tool-approval-request"),approvalId:d(),toolCallId:d()}),C8=C({type:$("tool-approval-response"),approvalId:d(),approved:me(),reason:d().optional()}),S8=C({role:$("system"),content:d(),providerOptions:dt.optional()}),I8=C({role:$("user"),content:oe([d(),q(oe([hv,_8,mv]))]),providerOptions:dt.optional()}),E8=C({role:$("assistant"),content:oe([d(),q(oe([hv,mv,w8,b8,gv,T8]))]),providerOptions:dt.optional()}),x8=C({role:$("tool"),content:q(oe([gv,C8])),providerOptions:dt.optional()}),$8=oe([S8,I8,E8,x8]);async function yv(e){if(e.prompt==null&&e.messages==null)throw new Wn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Wn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Js(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Wn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Wn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Wn({prompt:e,message:"messages must not be empty"});const r=await cr({value:t,schema:q($8)});if(!r.success)throw new Wn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function vv(e){if(!vd.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new ve({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
572
572
 
573
- `)}})}},gy={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function K$({status:t,statusText:e,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new my);if(s){const[a,i]=o.tee();o=a,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:Ti(r,gy)})}function Y$({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return r?.role==="assistant"?r.id:typeof e=="function"?e():e}function Q$(t){return t.type.startsWith("data-")}function yy(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(s===void 0)continue;const o=n in t?t[n]:void 0,a=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&i?r[n]=yy(o,s):r[n]=s}return r}function X$(t){const e=["ROOT"];let r=-1,n=null;function s(c,l,u){switch(c){case'"':{r=l,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=l,n=l,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=l,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=l,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function o(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=l,e.pop();break}}}function a(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}}}for(let c=0;c<t.length;c++){const l=t[c];switch(e[e.length-1]){case"ROOT":s(l,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(l,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,c);break}case"INSIDE_STRING":{switch(l){case'"':{e.pop(),r=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{r=c,e.pop();break}default:{r=c,s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=c;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,c+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c)):r=c;break}}}let i=t.slice(0,r+1);for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(n,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function _y(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await wn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await wn({text:X$(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Wu(t){return t.type.startsWith("tool-")}function vy(t){return t.type.split("-").slice(1).join("-")}function eE({lastMessage:t,messageId:e}){return{message:t?.role==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function tE({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:a}){return t.pipeThrough(new TransformStream({async transform(i,c){await n(async({state:l,write:u})=>{var p,h,d,f;function v(b){const S=l.message.parts.filter(Wu).find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function g(b){const S=l.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function w(b){var k;const S=l.message.parts.find(R=>Wu(R)&&R.toolCallId===b.toolCallId),T=b,x=S;S!=null?(S.state=b.state,x.input=T.input,x.output=T.output,x.errorText=T.errorText,x.rawInput=T.rawInput,x.preliminary=T.preliminary,x.providerExecuted=(k=T.providerExecuted)!=null?k:S.providerExecuted,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function y(b){var k,S;const T=l.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===b.toolCallId),x=b,R=T;T!=null?(T.state=b.state,R.toolName=b.toolName,R.input=x.input,R.output=x.output,R.errorText=x.errorText,R.rawInput=(k=x.rawInput)!=null?k:R.rawInput,R.preliminary=x.preliminary,R.providerExecuted=(S=x.providerExecuted)!=null?S:T.providerExecuted,x.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=x.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function _(b){if(b!=null){const k=l.message.metadata!=null?yy(l.message.metadata,b):b;e!=null&&await wu({value:k,schema:e}),l.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeTextParts[i.id]=b,l.message.parts.push(b),u();break}case"text-delta":{const b=l.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,u();break}case"text-end":{const b=l.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete l.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeReasoningParts[i.id]=b,l.message.parts.push(b),u();break}case"reasoning-delta":{const b=l.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=l.activeReasoningParts[i.id];b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,b.state="done",delete l.activeReasoningParts[i.id],u();break}case"file":{l.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=l.message.parts.filter(Wu);l.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=l.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await _y(b.text);b.dynamic?y({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):w({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=g(i.toolCallId);y({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:vy(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=g(i.toolCallId);y({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:vy(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{i.messageId!=null&&(l.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(l.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{s?.(new Error(i.errorText));break}default:if(Q$(i)){r?.[i.type]!=null&&await wu({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?l.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:l.message.parts.push(b),a?.(b),u()}}c.enqueue(i)})}}))}function rE({messageId:t,originalMessages:e=[],onFinish:r,onError:n,stream:s}){let o=e?.[e.length-1];o?.role!=="assistant"?o=void 0:t=o.id;let a=!1;const i=s.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const f=h;f.messageId==null&&t!=null&&(f.messageId=t)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const c=eE({lastMessage:o?structuredClone(o):void 0,messageId:t??""}),l=async h=>{await h({state:c,write:()=>{}})};let u=!1;const p=async()=>{if(u||!r)return;u=!0;const h=c.message.id===o?.id;await r({isAborted:a,isContinuation:h,responseMessage:c.message,messages:[...h?e.slice(0,-1):e,c.message],finishReason:c.finishReason})};return tE({stream:i,runUpdateMessageJob:l,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function nE({response:t,status:e,statusText:r,headers:n,stream:s,consumeSseStream:o}){let a=s.pipeThrough(new my);if(o){const[i,c]=a.tee();a=i,o({stream:c})}hy({response:t,status:e,statusText:r,headers:Object.fromEntries(Ti(n,gy).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ci(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var a;n=!0;try{o&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:a}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},e}async function sE({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){e?.(n)}finally{r.releaseLock()}}function wy(){let t,e;return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}function oE(){let t=[],e=null,r=!1,n=wy();const s=()=>{r=!0,n.resolve(),t.forEach(a=>a.cancel()),t=[],e?.close()},o=async()=>{if(r&&t.length===0){e?.close();return}if(t.length===0)return n=wy(),await n.promise,o();try{const{value:a,done:i}=await t[0].read();i?(t.shift(),t.length>0?await o():r&&e?.close()):e?.enqueue(a)}catch(a){e?.error(a),t.shift(),s()}};return{stream:new ReadableStream({start(a){e=a},pull:o,async cancel(){for(const a of t)await a.cancel();t=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),t.length===0&&e?.close()},terminate:s}}function aE(){var t,e;return(e=(t=globalThis?.performance)==null?void 0:t.now())!=null?e:Date.now()}function iE({tools:t,generatorStream:e,tracer:r,telemetry:n,system:s,messages:o,abortSignal:a,repairToolCall:i,experimental_context:c}){let l=null;const u=new ReadableStream({start(w){l=w}}),p=new Set,h=new Map;let d=!1,f;function v(){d&&p.size===0&&(f!=null&&l.enqueue(f),l.close())}const g=new TransformStream({async transform(w,y){const _=w.type;switch(_){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{y.enqueue(w);break}case"file":{y.enqueue({type:"file",file:new F$({data:w.data,mediaType:w.mediaType})});break}case"finish":{f={type:"finish",finishReason:w.finishReason,usage:w.usage,providerMetadata:w.providerMetadata};break}case"tool-call":{try{const b=await iy({toolCall:w,tools:t,repairToolCall:i,system:s,messages:o});if(y.enqueue(b),b.invalid){l.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:_u(b.error),dynamic:!0});break}const k=t[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}),k.execute!=null&&b.providerExecuted!==!0){const S=po();p.add(S),os({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...ss({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async T=>{let x;try{const R=y2({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}});for await(const j of R)l.enqueue({...b,type:"tool-result",output:j.output,...j.type==="preliminary"&&{preliminary:!0}}),j.type==="final"&&(x=j.output)}catch(R){Vu(T,R),l.enqueue({...b,type:"tool-error",error:R}),p.delete(S),v();return}p.delete(S),v();try{T.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(b){l.enqueue({type:"error",error:b})}break}case"tool-result":{const b=w.toolName;w.isError?l.enqueue({type:"tool-error",toolCallId:w.toolCallId,toolName:b,input:h.get(w.toolCallId),providerExecuted:w.providerExecuted,error:w.result}):y.enqueue({type:"tool-result",toolCallId:w.toolCallId,toolName:b,input:h.get(w.toolCallId),output:w.result,providerExecuted:w.providerExecuted});break}default:{const b=_;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,v()}});return new ReadableStream({async start(w){return Promise.all([e.pipeThrough(g).pipeTo(new WritableStream({write(y){w.enqueue(y)},close(){}})),u.pipeTo(new WritableStream({write(y){w.enqueue(y)},close(){w.close()}}))])}})}var cE=uo({prefix:"aitxt",size:24});function Ku({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Bu(1),experimental_output:u,experimental_telemetry:p,prepareStep:h,providerOptions:d,experimental_activeTools:f,activeTools:v=f,experimental_repairToolCall:g,experimental_transform:w,experimental_download:y,includeRawChunks:_=!1,onChunk:b,onError:k=({error:V})=>{console.error(V)},onFinish:S,onAbort:T,onStepFinish:x,experimental_context:R,_internal:{now:j=aE,generateId:O=cE,currentDate:D=()=>new Date}={},...U}){return new uE({model:ki(t),telemetry:p,headers:c,settings:U,maxRetries:a,abortSignal:i,system:n,prompt:s,messages:o,tools:e,toolChoice:r,transforms:Hu(w),activeTools:v,repairToolCall:g,stopConditions:Hu(l),output:u,providerOptions:d,prepareStep:h,includeRawChunks:_,onChunk:b,onError:k,onFinish:S,onAbort:T,onStepFinish:x,now:j,currentDate:D,generateId:O,experimental_context:R,download:y})}function lE(t){if(!t)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let e,r="",n="",s="";function o({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:e,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&o({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(e==null)e=a.id;else if(a.id!==e){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const c=await t.parsePartial({text:r});if(c!=null){const l=JSON.stringify(c.partial);l!==s&&(o({controller:i,partialOutput:c.partial}),s=l)}}})}var uE=class{constructor({model:t,telemetry:e,headers:r,settings:n,maxRetries:s,abortSignal:o,system:a,prompt:i,messages:c,tools:l,toolChoice:u,transforms:p,activeTools:h,repairToolCall:d,stopConditions:f,output:v,providerOptions:g,prepareStep:w,includeRawChunks:y,now:_,currentDate:b,generateId:k,onChunk:S,onError:T,onFinish:x,onAbort:R,onStepFinish:j,experimental_context:O,download:D}){this._totalUsage=new hi,this._finishReason=new hi,this._steps=new hi,this.output=v,this.includeRawChunks=y,this.tools=l;let U,V=[];const ne=[];let fe,de,te={},ye=[];const H=[];let P,F={},q={};const E=new TransformStream({async transform(K,Q){var ue,he,Ve,Be;Q.enqueue(K);const{part:X}=K;if((X.type==="text-delta"||X.type==="reasoning-delta"||X.type==="source"||X.type==="tool-call"||X.type==="tool-result"||X.type==="tool-input-start"||X.type==="tool-input-delta"||X.type==="raw")&&await S?.({chunk:X}),X.type==="error"&&await T({error:Qg(X.error)}),X.type==="text-start"&&(F[X.id]={type:"text",text:"",providerMetadata:X.providerMetadata},V.push(F[X.id])),X.type==="text-delta"){const ke=F[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}ke.text+=X.text,ke.providerMetadata=(ue=X.providerMetadata)!=null?ue:ke.providerMetadata}if(X.type==="text-end"){const ke=F[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(he=X.providerMetadata)!=null?he:ke.providerMetadata,delete F[X.id]}if(X.type==="reasoning-start"&&(q[X.id]={type:"reasoning",text:"",providerMetadata:X.providerMetadata},V.push(q[X.id])),X.type==="reasoning-delta"){const ke=q[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}ke.text+=X.text,ke.providerMetadata=(Ve=X.providerMetadata)!=null?Ve:ke.providerMetadata}if(X.type==="reasoning-end"){const ke=q[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(Be=X.providerMetadata)!=null?Be:ke.providerMetadata,delete q[X.id]}if(X.type==="file"&&V.push({type:"file",file:X.file}),X.type==="source"&&V.push(X),X.type==="tool-call"&&V.push(X),X.type==="tool-result"&&!X.preliminary&&V.push(X),X.type==="tool-error"&&V.push(X),X.type==="start-step"&&(te=X.request,ye=X.warnings),X.type==="finish-step"){const ke=Gu({content:V,tools:l}),wt=new ly({content:V,finishReason:X.finishReason,usage:X.usage,warnings:ye,request:te,response:{...X.response,messages:[...ne,...ke]},providerMetadata:X.providerMetadata});await j?.(wt),pg(ye),H.push(wt),V=[],q={},F={},ne.push(...ke),U.resolve()}X.type==="finish"&&(de=X.totalUsage,fe=X.finishReason)},async flush(K){try{if(H.length===0){const Ve=new c$({message:"No output generated. Check the stream for errors."});G._finishReason.reject(Ve),G._totalUsage.reject(Ve),G._steps.reject(Ve);return}const Q=fe??"unknown",ue=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};G._finishReason.resolve(Q),G._totalUsage.resolve(ue),G._steps.resolve(H);const he=H[H.length-1];await x?.({finishReason:Q,totalUsage:ue,usage:he.usage,content:he.content,text:he.text,reasoningText:he.reasoningText,reasoning:he.reasoning,files:he.files,sources:he.sources,toolCalls:he.toolCalls,staticToolCalls:he.staticToolCalls,dynamicToolCalls:he.dynamicToolCalls,toolResults:he.toolResults,staticToolResults:he.staticToolResults,dynamicToolResults:he.dynamicToolResults,request:he.request,response:he.response,warnings:he.warnings,providerMetadata:he.providerMetadata,steps:H}),P.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":Q,"ai.response.text":{output:()=>he.text},"ai.response.toolCalls":{output:()=>{var Ve;return(Ve=he.toolCalls)!=null&&Ve.length?JSON.stringify(he.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(he.providerMetadata),"ai.usage.inputTokens":ue.inputTokens,"ai.usage.outputTokens":ue.outputTokens,"ai.usage.totalTokens":ue.totalTokens,"ai.usage.reasoningTokens":ue.reasoningTokens,"ai.usage.cachedInputTokens":ue.cachedInputTokens}}))}catch(Q){K.error(Q)}finally{P.end()}}}),I=oE();this.addStream=I.addStream,this.closeStream=I.close;const $=I.stream.getReader();let B=new ReadableStream({async start(K){K.enqueue({type:"start"})},async pull(K){function Q(){R?.({steps:H}),K.enqueue({type:"abort"}),K.close()}try{const{done:ue,value:he}=await $.read();if(ue){K.close();return}if(o?.aborted){Q();return}K.enqueue(he)}catch(ue){vn(ue)&&o?.aborted?Q():K.error(ue)}},cancel(K){return I.stream.cancel(K)}});for(const K of p)B=B.pipeThrough(K({tools:l,stopStream(){I.terminate()}}));this.baseStream=B.pipeThrough(lE(v)).pipeThrough(E);const{maxRetries:W,retry:_e}=sy({maxRetries:s,abortSignal:o}),pe=ey(e),A=Fu(n),Z=Xg({model:t,telemetry:e,headers:r,settings:{...A,maxRetries:W}}),G=this;os({name:"ai.streamText",attributes:Dt({telemetry:e,attributes:{...ss({operationId:"ai.streamText",telemetry:e}),...Z,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:c})}}}),tracer:pe,endWhenDone:!1,fn:async K=>{P=K;async function Q({currentStep:ue,responseMessages:he,usage:Ve}){var Be,X,ke,wt,Ee;const $t=G.includeRawChunks;U=new hi;const Or=await Yg({system:a,prompt:i,messages:c}),Et=[...Or.messages,...he],ct=await w?.({model:t,steps:H,stepNumber:H.length,messages:Et}),Zt=ki((Be=ct?.model)!=null?Be:t),en=await Bg({prompt:{system:(X=ct?.system)!=null?X:Or.system,messages:(ke=ct?.messages)!=null?ke:Et},supportedUrls:await Zt.supportedUrls,download:D}),{toolChoice:tn,tools:ds}=Jg({tools:l,toolChoice:(wt=ct?.toolChoice)!=null?wt:u,activeTools:(Ee=ct?.activeTools)!=null?Ee:h}),{result:{stream:qi,response:rt,request:Ar},doStreamSpan:Mr,startTimestampMs:m_}=await _e(()=>os({name:"ai.streamText.doStream",attributes:Dt({telemetry:e,attributes:{...ss({operationId:"ai.streamText.doStream",telemetry:e}),...Z,"ai.model.provider":Zt.provider,"ai.model.id":Zt.modelId,"ai.prompt.messages":{input:()=>ty(en)},"ai.prompt.tools":{input:()=>ds?.map(ve=>JSON.stringify(ve))},"ai.prompt.toolChoice":{input:()=>tn!=null?JSON.stringify(tn):void 0},"gen_ai.system":Zt.provider,"gen_ai.request.model":Zt.modelId,"gen_ai.request.frequency_penalty":A.frequencyPenalty,"gen_ai.request.max_tokens":A.maxOutputTokens,"gen_ai.request.presence_penalty":A.presencePenalty,"gen_ai.request.stop_sequences":A.stopSequences,"gen_ai.request.temperature":A.temperature,"gen_ai.request.top_k":A.topK,"gen_ai.request.top_p":A.topP}}),tracer:pe,endWhenDone:!1,fn:async ve=>({startTimestampMs:_(),doStreamSpan:ve,result:await Zt.doStream({...A,tools:ds,toolChoice:tn,responseFormat:v?.responseFormat,prompt:en,providerOptions:g,abortSignal:o,headers:r,includeRawChunks:$t})})})),wR=iE({tools:l,generatorStream:qi,tracer:pe,telemetry:e,system:a,messages:Et,repairToolCall:d,abortSignal:o,experimental_context:O}),bR=Ar??{},zi=[],pd=[];let fd;const hd={};let ps="unknown",ar={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},md,g_=!0,yr={id:k(),timestamp:b(),modelId:t.modelId},y_="";G.addStream(wR.pipeThrough(new TransformStream({async transform(ve,lt){var xo,Io,Di,Nr;if(ve.type==="stream-start"){fd=ve.warnings;return}if(g_){const bt=_()-m_;g_=!1,Mr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":bt}),Mr.setAttributes({"ai.response.msToFirstChunk":bt}),lt.enqueue({type:"start-step",request:bR,warnings:fd??[]})}const __=ve.type;switch(__){case"text-start":case"text-end":{lt.enqueue(ve);break}case"text-delta":{ve.delta.length>0&&(lt.enqueue({type:"text-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata}),y_+=ve.delta);break}case"reasoning-start":case"reasoning-end":{lt.enqueue(ve);break}case"reasoning-delta":{lt.enqueue({type:"reasoning-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata});break}case"tool-call":{lt.enqueue(ve),zi.push(ve);break}case"tool-result":{lt.enqueue(ve),ve.preliminary||pd.push(ve);break}case"tool-error":{lt.enqueue(ve),pd.push(ve);break}case"response-metadata":{yr={id:(xo=ve.id)!=null?xo:yr.id,timestamp:(Io=ve.timestamp)!=null?Io:yr.timestamp,modelId:(Di=ve.modelId)!=null?Di:yr.modelId};break}case"finish":{ar=ve.usage,ps=ve.finishReason,md=ve.providerMetadata;const bt=_()-m_;Mr.addEvent("ai.stream.finish"),Mr.setAttributes({"ai.response.msToFinish":bt,"ai.response.avgOutputTokensPerSecond":1e3*((Nr=ar.outputTokens)!=null?Nr:0)/bt});break}case"file":{lt.enqueue(ve);break}case"source":{lt.enqueue(ve);break}case"tool-input-start":{hd[ve.id]=ve.toolName;const bt=l?.[ve.toolName];bt?.onInputStart!=null&&await bt.onInputStart({toolCallId:ve.id,messages:Et,abortSignal:o,experimental_context:O}),lt.enqueue({...ve,dynamic:bt?.type==="dynamic"});break}case"tool-input-end":{delete hd[ve.id],lt.enqueue(ve);break}case"tool-input-delta":{const bt=hd[ve.id],gd=l?.[bt];gd?.onInputDelta!=null&&await gd.onInputDelta({inputTextDelta:ve.delta,toolCallId:ve.id,messages:Et,abortSignal:o,experimental_context:O}),lt.enqueue(ve);break}case"error":{lt.enqueue(ve),ps="error";break}case"raw":{$t&&lt.enqueue(ve);break}default:{const bt=__;throw new Error(`Unknown chunk type: ${bt}`)}}},async flush(ve){const lt=zi.length>0?JSON.stringify(zi):void 0;try{Mr.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":ps,"ai.response.text":{output:()=>y_},"ai.response.toolCalls":{output:()=>lt},"ai.response.id":yr.id,"ai.response.model":yr.modelId,"ai.response.timestamp":yr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(md),"ai.usage.inputTokens":ar.inputTokens,"ai.usage.outputTokens":ar.outputTokens,"ai.usage.totalTokens":ar.totalTokens,"ai.usage.reasoningTokens":ar.reasoningTokens,"ai.usage.cachedInputTokens":ar.cachedInputTokens,"gen_ai.response.finish_reasons":[ps],"gen_ai.response.id":yr.id,"gen_ai.response.model":yr.modelId,"gen_ai.usage.input_tokens":ar.inputTokens,"gen_ai.usage.output_tokens":ar.outputTokens}}))}catch{}finally{Mr.end()}ve.enqueue({type:"finish-step",finishReason:ps,usage:ar,providerMetadata:md,response:{...yr,headers:rt?.headers}});const xo=ry(Ve,ar);await U.promise;const Io=zi.filter(Nr=>Nr.providerExecuted!==!0),Di=pd.filter(Nr=>Nr.providerExecuted!==!0);if(Io.length>0&&Di.length===Io.length&&!await uy({stopConditions:f,steps:H})){he.push(...Gu({content:H[H.length-1].content,tools:l}));try{await Q({currentStep:ue+1,responseMessages:he,usage:xo})}catch(Nr){ve.enqueue({type:"error",error:Nr}),G.closeStream()}}else ve.enqueue({type:"finish",finishReason:ps,totalUsage:xo}),G.closeStream()}})))}await Q({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(K=>{G.addStream(new ReadableStream({start(Q){Q.enqueue({type:"error",error:K}),Q.close()}})),G.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return Ci(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return Ci(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await sE({stream:this.fullStream,onError:t?.onError})}catch(r){(e=t?.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new ug;return Ci(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:i=!0,onError:c=Yn}={}){const l=e!=null?Y$({originalMessages:t,responseMessageId:e}):void 0,u={},p=d=>{var f,v;const g=u[d];return((v=(f=this.tools)==null?void 0:f[g])==null?void 0:v.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const v=n?.({part:d}),g=d.type;switch(g){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{s&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{o&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),o&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const w=p(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const w=p(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...w!=null?{dynamic:w}:{},errorText:c(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...w!=null?{dynamic:w}:{}});break}case"tool-result":{const w=p(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=p(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:c(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"error":{f.enqueue({type:"error",errorText:c(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...l!=null?{messageId:l}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:d.finishReason,...v!=null?{messageMetadata:v}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const w=g;throw new Error(`Unknown chunk type: ${w}`)}}v!=null&&g!=="start"&&g!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:v})}}));return Ci(rE({stream:h,messageId:l??e?.(),originalMessages:t,onFinish:r,onError:c}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l,...u}={}){nE({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l}),...u})}pipeTextStreamToResponse(t,e){W$({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c,...l}={}){return K$({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c}),...l})}toTextStreamResponse(t){return G$({textStream:this.textStream,...t})}};uo({prefix:"aiobj",size:24}),uo({prefix:"aiobj",size:24});var dE={};e$(dE,{object:()=>fE,text:()=>pE});var pE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),fE=({schema:t})=>{const e=yi(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const n=await _y(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await wn({text:r});if(!s.success)throw new Sg({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await er({value:s.value,schema:e});if(!o.success)throw new Sg({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},hE="AI_MCPClientError",by=`vercel.ai.error.${hE}`,mE=Symbol.for(by),ky,Sy,De=class extends(Sy=we,ky=mE,Sy){constructor({name:t="MCPClientError",message:e,cause:r,data:n,code:s}){super({name:t,message:e,cause:r}),this[ky]=!0,this.data=n,this.code=s}static isInstance(t){return we.hasMarker(t,by)}},as="2025-06-18",gE=[as,"2025-03-26","2024-11-05"],yE=Ke({name:m(),version:m()}),$i=Ke({_meta:le(C({}).loose())}),Ir=$i,Ty=C({method:m(),params:le($i)}),Cy=C({applyDefaults:le(me())}).loose(),_E=Ke({experimental:le(C({}).loose()),logging:le(C({}).loose()),prompts:le(Ke({listChanged:le(me())})),resources:le(Ke({subscribe:le(me()),listChanged:le(me())})),tools:le(Ke({listChanged:le(me())})),elicitation:le(Cy)});C({elicitation:le(Cy)}).loose();var vE=Ir.extend({protocolVersion:m(),capabilities:_E,serverInfo:yE,instructions:le(m())}),Yu=Ir.extend({nextCursor:le(m())}),wE=C({name:m(),description:le(m()),inputSchema:C({type:L("object"),properties:le(C({}).loose())}).loose()}).loose(),bE=Yu.extend({tools:M(wE)}),$y=C({type:L("text"),text:m()}).loose(),Ey=C({type:L("image"),data:Yf(),mimeType:m()}).loose(),kE=C({uri:m(),name:m(),title:le(m()),description:le(m()),mimeType:le(m()),size:le(N())}).loose(),SE=Yu.extend({resources:M(kE)}),xy=C({uri:m(),name:le(m()),title:le(m()),mimeType:le(m())}).loose(),Iy=xy.extend({text:m()}),Ry=xy.extend({blob:Yf()}),Py=C({type:L("resource"),resource:ie([Iy,Ry])}).loose(),TE=Ir.extend({content:M(ie([$y,Ey,Py])),isError:me().default(!1).optional()}).or(Ir.extend({toolResult:Pe()})),CE=C({uriTemplate:m(),name:m(),title:le(m()),description:le(m()),mimeType:le(m())}).loose(),$E=Ir.extend({resourceTemplates:M(CE)}),EE=Ir.extend({contents:M(ie([Iy,Ry]))}),xE=C({name:m(),description:le(m()),required:le(me())}).loose(),IE=C({name:m(),title:le(m()),description:le(m()),arguments:le(M(xE))}).loose(),RE=Yu.extend({prompts:M(IE)}),PE=C({role:ie([L("user"),L("assistant")]),content:ie([$y,Ey,Py])}).loose(),OE=Ir.extend({description:le(m()),messages:M(PE)}),AE=$i.extend({message:m(),requestedSchema:Pe()}),Oy=Ty.extend({method:L("elicitation/create"),params:AE}),ME=Ir.extend({action:ie([L("accept"),L("decline"),L("cancel")]),content:le(be(m(),Pe()))}),Ei="2.0",NE=C({jsonrpc:L(Ei),id:ie([m(),N().int()])}).merge(Ty).strict(),LE=C({jsonrpc:L(Ei),id:ie([m(),N().int()]),result:Ir}).strict(),jE=C({jsonrpc:L(Ei),id:ie([m(),N().int()]),error:C({code:N().int(),message:m(),data:le(Pe())})}).strict(),qE=C({jsonrpc:L(Ei)}).merge(C({method:m(),params:le($i)})).strict(),So=ie([NE,qE,LE,jE]),Ay=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",My=C({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:N().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Ct=m().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:ch.custom,message:"URL must be parseable",fatal:!0}),of}).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"}),zE=C({resource:m().url(),authorization_servers:M(Ct).optional(),jwks_uri:m().url().optional(),scopes_supported:M(m()).optional(),bearer_methods_supported:M(m()).optional(),resource_signing_alg_values_supported:M(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:M(m()).optional(),dpop_signing_alg_values_supported:M(m()).optional(),dpop_bound_access_tokens_required:me().optional()}).passthrough(),Ny=C({issuer:m(),authorization_endpoint:Ct,token_endpoint:Ct,registration_endpoint:Ct.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),grant_types_supported:M(m()).optional(),code_challenge_methods_supported:M(m()),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional()}).passthrough(),DE=C({issuer:m(),authorization_endpoint:Ct,token_endpoint:Ct,userinfo_endpoint:Ct.optional(),jwks_uri:Ct,registration_endpoint:Ct.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),grant_types_supported:M(m()).optional(),subject_types_supported:M(m()),id_token_signing_alg_values_supported:M(m()),claims_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional()}).passthrough(),UE=DE.merge(Ny.pick({code_challenge_methods_supported:!0})),ZE=C({client_id:m(),client_secret:m().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),FE=C({redirect_uris:M(Ct),token_endpoint_auth_method:m().optional(),grant_types:M(m()).optional(),response_types:M(m()).optional(),client_name:m().optional(),client_uri:Ct.optional(),logo_uri:Ct.optional(),scope:m().optional(),contacts:M(m()).optional(),tos_uri:Ct.optional(),policy_uri:m().optional(),jwks_uri:Ct.optional(),jwks:ht().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),VE=C({error:m(),error_description:m().optional(),error_uri:m().optional()}),HE=FE.merge(ZE),BE="AI_MCPClientOAuthError",Ly=`vercel.ai.error.${BE}`,JE=Symbol.for(Ly),jy,qy,To=class extends(qy=we,jy=JE,qy){constructor({name:t="MCPClientOAuthError",message:e,cause:r}){super({name:t,message:e,cause:r}),this[jy]=!0}static isInstance(t){return we.hasMarker(t,Ly)}},is=class extends To{};is.errorCode="server_error";var xi=class extends To{};xi.errorCode="invalid_client";var Ii=class extends To{};Ii.errorCode="invalid_grant";var Ri=class extends To{};Ri.errorCode="unauthorized_client";var GE={[is.errorCode]:is,[xi.errorCode]:xi,[Ii.errorCode]:Ii,[Ri.errorCode]:Ri};function WE(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function KE({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+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var Pi=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Oi(t){var e;const r=(e=t.headers.get("www-authenticate"))!=null?e:t.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,a=r.match(o);if(a)try{return new URL(a[1])}catch{return}}function YE(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Qu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Qu(t,void 0,r):void 0;throw n}}async function zy(t,e,r=fetch){return await Qu(t,{"MCP-Protocol-Version":e},r)}function QE(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function XE(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!=null?s:as;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const u=YE(e,a.pathname);c=new URL(u,(o=n?.metadataServerUrl)!=null?o:a),c.search=a.search}let l=await zy(c,i,r);if(!n?.metadataUrl&&QE(l,a.pathname)){const u=new URL(`/.well-known/${e}`,a);l=await zy(u,i,r)}return l}async function e7(t,e,r=fetch){const n=await XE(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return zE.parse(await n.json())}function t7(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/oauth-authorization-server",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 r7(t,{fetchFn:e=fetch,protocolVersion:r=as}={}){var n;const s={"MCP-Protocol-Version":r},o=t7(t);for(const{url:a,type:i}of o){const c=await Qu(a,s,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return Ny.parse(await c.json());{const l=UE.parse(await c.json());if(!((n=l.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return l}}}}async function n7(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){const i="code",c="S256";let l;if(e){if(l=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(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",t);const u=await p0(),p=u.code_verifier,h=u.code_challenge;return l.searchParams.set("response_type",i),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",h),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(n)),o&&l.searchParams.set("state",o),s&&l.searchParams.set("scope",s),s?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:p}}function Dy(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":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 Uy(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":s7(s,o,r);return;case"client_secret_post":o7(s,o,n);return;case"none":a7(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function s7(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 o7(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function a7(t,e){e.set("client_id",t)}async function Xu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=VE.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=GE[s]||is;return new i({message:o||"",cause:a})}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new is({message:s})}}async function i7(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:c}){var l;const u="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,d,t,e);else{const v=(l=e?.token_endpoint_auth_methods_supported)!=null?l:[],g=Dy(r,v);Uy(g,r,h,d)}a&&d.set("resource",a.href);const f=await(c??fetch)(p,{method:"POST",headers:h,body:d});if(!f.ok)throw await Xu(f);return My.parse(await f.json())}async function c7(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const c="refresh_token";let l;if(e){if(l=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(u,p,t,e);else{const d=(i=e?.token_endpoint_auth_methods_supported)!=null?i:[],f=Dy(r,d);Uy(f,r,u,p)}s&&p.set("resource",s.href);const h=await(a??fetch)(l,{method:"POST",headers:u,body:p});if(!h.ok)throw await Xu(h);return My.parse({refresh_token:n,...await h.json()})}async function l7(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 o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Xu(o);return HE.parse(await o.json())}async function Ai(t,e){var r,n;try{return await ed(t,e)}catch(s){if(s instanceof xi||s instanceof Ri)return await((r=t.invalidateCredentials)==null?void 0:r.call(t,"all")),await ed(t,e);if(s instanceof Ii)return await((n=t.invalidateCredentials)==null?void 0:n.call(t,"tokens")),await ed(t,e);throw s}}async function u7(t,e,r){const n=WE(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!KE({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function ed(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await e7(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=e);const c=await u7(e,t,a),l=await r7(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await l7(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),g=await i7(i,{metadata:l,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}const p=await t.tokens();if(p?.refresh_token)try{const v=await c7(i,{metadata:l,clientInformation:u,refreshToken:p.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof To)||v instanceof is))throw v}const h=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:f}=await n7(i,{metadata:l,clientInformation:u,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(f),await t.redirectToAuthorization(d),"REDIRECT"}var d7=class{constructor({url:t,headers:e,authProvider:r}){this.connected=!1,this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":as};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Kr(e,`ai-sdk/${Ay}`,fo())}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,a,i,c;try{const l=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:l,signal:(s=this.abortController)==null?void 0:s.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Oi(u);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Pi;return(o=this.onerror)==null||o.call(this,v),e(v)}}catch(f){return(a=this.onerror)==null||a.call(this,f),e(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const v=new De({message:f});return(i=this.onerror)==null||i.call(this,v),e(v)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),d=async()=>{var f,v,g;try{for(;;){const{done:w,value:y}=await h.read();if(w){if(this.connected)throw this.connected=!1,new De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:_,data:b}=y;if(_==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new De({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,t()}else if(_==="message")try{const k=So.parse(JSON.parse(b));(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(v=this.onerror)==null||v.call(this,S)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(g=this.onerror)==null||g.call(this,w),e(w)}};this.sseConnection={close:()=>h.cancel()},d()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(c=this.onerror)==null||c.call(this,l),e(l)}};r()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){if(!this.endpoint||!this.connected)throw new De({message:"MCP SSE Transport Error: Not connected"});const e=this.endpoint,r=async(n=!1)=>{var s,o,a,i,c;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(t),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(e,u);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Oi(p);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new Pi;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),d=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(l){(c=this.onerror)==null||c.call(this,l);return}};await r()}},p7=class{constructor({url:t,headers:e,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":as};if(this.sessionId&&(e["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Kr(e,`ai-sdk/${Ay}`,fo())}async start(){if(this.abortController)throw new De({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var t,e,r;(t=this.inboundSseConnection)==null||t.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){const e=async(r=!1)=>{var n,s,o,a,i,c,l;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(t),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Oi(h);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Pi}catch(g){throw(s=this.onerror)==null||s.call(this,g),g}return e(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const g=await h.text().catch(()=>null);let w=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${g}`;h.status===404&&(w+=". This server does not support HTTP transport. Try using `sse` transport instead");const y=new De({message:w});throw(o=this.onerror)==null||o.call(this,y),y}const f=h.headers.get("content-type")||"";if(f.includes("application/json")){const g=await h.json(),w=Array.isArray(g)?g.map(y=>So.parse(y)):[So.parse(g)];for(const y of w)(a=this.onmessage)==null||a.call(this,y);return}if(f.includes("text/event-stream")){if(!h.body){const _=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,_),_}const w=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader();(async()=>{var _,b,k;try{for(;;){const{done:S,value:T}=await w.read();if(S)return;const{event:x,data:R}=T;if(x==="message")try{const j=So.parse(JSON.parse(R));(_=this.onmessage)==null||_.call(this,j)}catch(j){const O=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:j});(b=this.onerror)==null||b.call(this,O)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const v=new De({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`});throw(c=this.onerror)==null||c.call(this,v),v}catch(u){throw(l=this.onerror)==null||l.call(this,u),u}};await e()}getNextReconnectionDelay(t){const{initialReconnectionDelay:e,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(e*Math.pow(r,t),n)}scheduleInboundSseReconnection(){var t;const{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){(t=this.onerror)==null||t.call(this,new De({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(t=!1,e){var r,n,s,o,a,i;try{const c=await this.commonHeaders({Accept:"text/event-stream"});e&&(c["last-event-id"]=e);const l=await fetch(this.url.href,{method:"GET",headers:c,signal:(r=this.abortController)==null?void 0:r.signal}),u=l.headers.get("mcp-session-id");if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!t){this.resourceMetadataUrl=Oi(l);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Pi;(n=this.onerror)==null||n.call(this,v);return}}catch(f){(s=this.onerror)==null||s.call(this,f);return}return this.openInboundSse(!0,e)}if(l.status===405)return;if(!l.ok||!l.body){const f=new De({message:`MCP HTTP Transport Error: GET SSE failed: ${l.status} ${l.statusText}`});(o=this.onerror)==null||o.call(this,f);return}const h=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),d=async()=>{var f,v,g,w;try{for(;;){const{done:y,value:_}=await h.read();if(y)return;const{event:b,data:k,id:S}=_;if(S&&(this.lastInboundEventId=S),b==="message")try{const T=So.parse(JSON.parse(k));(f=this.onmessage)==null||f.call(this,T)}catch(T){const x=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:T});(v=this.onerror)==null||v.call(this,x)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(g=this.onerror)==null||g.call(this,y),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(a=this.onerror)==null||a.call(this,c),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function f7(t){switch(t.type){case"sse":return new d7(t);case"http":return new p7(t);default:throw new De({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function h7(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var m7="1.0.0";async function g7(t){const e=new y7(t);return await e.init(),e}var y7=class{constructor({transport:t,name:e="ai-sdk-mcp-client",version:r=m7,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},h7(t)?this.transport=t:this.transport=f7(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new De({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:e,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:as,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:vE});if(t===void 0)throw new De({message:"Server sent invalid initialize result"});if(!gE.includes(t.protocolVersion))throw new De({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new De({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new De({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new De({message:"Server does not support prompts"});break;default:throw new De({message:`Unsupported method: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new De({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const o=r?.signal;o?.throwIfAborted();const a=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:a},c=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,l=>{if(o?.aborted)return s(new De({message:"Request was aborted",cause:o.reason}));if(l instanceof Error)return s(l);try{const u=e.parse(l.result);n(u)}catch(u){const p=new De({message:"Failed to parse server response",cause:u});s(p)}}),this.transport.send(i).catch(l=>{c(),s(l)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:bE,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:TE,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:t,options:e}={}){try{return this.request({request:{method:"resources/list",params:t},resultSchema:SE,options:e})}catch(r){throw r}}async readResourceInternal({uri:t,options:e}){try{return this.request({request:{method:"resources/read",params:{uri:t}},resultSchema:EE,options:e})}catch(r){throw r}}async listResourceTemplatesInternal({options:t}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:$E,options:t})}catch(e){throw e}}async listPromptsInternal({params:t,options:e}={}){try{return this.request({request:{method:"prompts/list",params:t},resultSchema:RE,options:e})}catch(r){throw r}}async getPromptInternal({name:t,args:e,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:t,arguments:e}},resultSchema:OE,options:r})}catch(n){throw n}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:a}of n.tools){if(t!=="automatic"&&!(s in t))continue;const i=this,c=async(u,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:u,options:p})},l=t==="automatic"?c2({description:o,inputSchema:ho({...a,properties:(e=a.properties)!=null?e:{},additionalProperties:!1}),execute:c}):{description:o,inputSchema:t[s].inputSchema,execute:c};r[s]=l}return r}catch(n){throw n}}listResources({params:t,options:e}={}){return this.listResourcesInternal({params:t,options:e})}readResource({uri:t,options:e}){return this.readResourceInternal({uri:t,options:e})}listResourceTemplates({options:t}={}){return this.listResourceTemplatesInternal({options:t})}listPrompts({params:t,options:e}={}){return this.listPromptsInternal({params:t,options:e})}getPrompt({name:t,arguments:e,options:r}){return this.getPromptInternal({name:t,args:e,options:r})}onElicitationRequest(t,e){if(t!==Oy)throw new De({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=e}async onRequestMessage(t){try{if(t.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Unsupported request method: ${t.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const e=Oy.safeParse({method:t.method,params:t.params});if(!e.success){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32602,message:`Invalid elicitation request: ${e.error.message}`,data:e.error.issues}});return}try{const r=await this.elicitationRequestHandler(e.data),n=ME.parse(r);await this.transport.send({jsonrpc:"2.0",id:t.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new De({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new De({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}},Zy="vercel.ai.error",_7=Symbol.for(Zy),Fy,Vy,Ye=class S_ extends(Vy=Error,Fy=_7,Vy){constructor({name:e,message:r,cause:n}){super(r),this[Fy]=!0,this.name=e,this.cause=n}static isInstance(e){return S_.hasMarker(e,Zy)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},Hy="AI_APICallError",By=`vercel.ai.error.${Hy}`,v7=Symbol.for(By),Jy,Gy,Ut=class extends(Gy=Ye,Jy=v7,Gy){constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:Hy,message:t,cause:a}),this[Jy]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=c}static isInstance(t){return Ye.hasMarker(t,By)}},Wy="AI_EmptyResponseBodyError",Ky=`vercel.ai.error.${Wy}`,w7=Symbol.for(Ky),Yy,Qy,b7=class extends(Qy=Ye,Yy=w7,Qy){constructor({message:t="Empty response body"}={}){super({name:Wy,message:t}),this[Yy]=!0}static isInstance(t){return Ye.hasMarker(t,Ky)}};function Xy(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var e1="AI_InvalidArgumentError",t1=`vercel.ai.error.${e1}`,k7=Symbol.for(t1),r1,n1,s1=class extends(n1=Ye,r1=k7,n1){constructor({message:t,cause:e,argument:r}){super({name:e1,message:t,cause:e}),this[r1]=!0,this.argument=r}static isInstance(t){return Ye.hasMarker(t,t1)}},o1="AI_InvalidPromptError",a1=`vercel.ai.error.${o1}`,S7=Symbol.for(a1),i1,c1,T7=class extends(c1=Ye,i1=S7,c1){constructor({prompt:t,message:e,cause:r}){super({name:o1,message:`Invalid prompt: ${e}`,cause:r}),this[i1]=!0,this.prompt=t}static isInstance(t){return Ye.hasMarker(t,a1)}},l1="AI_InvalidResponseDataError",u1=`vercel.ai.error.${l1}`,C7=Symbol.for(u1),d1,p1,td=class extends(p1=Ye,d1=C7,p1){constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:l1,message:e}),this[d1]=!0,this.data=t}static isInstance(t){return Ye.hasMarker(t,u1)}},f1="AI_JSONParseError",h1=`vercel.ai.error.${f1}`,$7=Symbol.for(h1),m1,g1,Mi=class extends(g1=Ye,m1=$7,g1){constructor({text:t,cause:e}){super({name:f1,message:`JSON parsing failed: Text: ${t}.
574
- Error message: ${Xy(e)}`,cause:e}),this[m1]=!0,this.text=t}static isInstance(t){return Ye.hasMarker(t,h1)}},y1="AI_LoadAPIKeyError",_1=`vercel.ai.error.${y1}`,E7=Symbol.for(_1),v1,w1,Ni=class extends(w1=Ye,v1=E7,w1){constructor({message:t}){super({name:y1,message:t}),this[v1]=!0}static isInstance(t){return Ye.hasMarker(t,_1)}},b1="AI_TooManyEmbeddingValuesForCallError",k1=`vercel.ai.error.${b1}`,x7=Symbol.for(k1),S1,T1,I7=class extends(T1=Ye,S1=x7,T1){constructor(t){super({name:b1,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[S1]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Ye.hasMarker(t,k1)}},C1="AI_TypeValidationError",$1=`vercel.ai.error.${C1}`,R7=Symbol.for($1),E1,x1,Co=class bd extends(x1=Ye,E1=R7,x1){constructor({value:e,cause:r}){super({name:C1,message:`Type validation failed: Value: ${JSON.stringify(e)}.
575
- Error message: ${Xy(r)}`,cause:r}),this[E1]=!0,this.value=e}static isInstance(e){return Ye.hasMarker(e,$1)}static wrap({value:e,cause:r}){return bd.isInstance(r)&&r.value===e?r:new bd({value:e,cause:r})}},I1="AI_UnsupportedFunctionalityError",R1=`vercel.ai.error.${I1}`,P7=Symbol.for(R1),P1,O1,Rr=class extends(O1=Ye,P1=P7,O1){constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:I1,message:e}),this[P1]=!0,this.functionality=t}static isInstance(t){return Ye.hasMarker(t,R1)}};function mr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function $o(t){return Object.fromEntries([...t.headers])}var O7=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new s1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},nr=O7();function rd(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var A7=["fetch failed","failed to fetch"];function M7({error:t,url:e,requestBodyValues:r}){if(rd(t))return t;if(t instanceof TypeError&&A7.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ut({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function N7(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function L7(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function A1(t,...e){const r=new Headers(L7(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var j7="3.0.20";function q7({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Ni({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Ni({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Ni({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Ni({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function z7({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function D7(t){var e;const[r,n=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?e:n}var U7=/"__proto__"\s*:/,Z7=/"constructor"\s*:/;function M1(t){const e=JSON.parse(t);return e===null||typeof e!="object"||U7.test(t)===!1&&Z7.test(t)===!1?e:F7(e)}function F7(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function nd(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return M1(t)}try{return M1(t)}finally{Error.stackTraceLimit=e}}var Li=Symbol.for("vercel.ai.validator");function V7(t){return{[Li]:!0,validate:t}}function H7(t){return typeof t=="object"&&t!==null&&Li in t&&t[Li]===!0&&"validate"in t}function _t(t){let e;return()=>(e==null&&(e=t()),e)}function B7(t){return H7(t)?t:typeof t=="function"?t():J7(t)}function J7(t){return V7(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Co({value:e,cause:r.issues})}})}async function Qr({value:t,schema:e}){const r=await sd({value:t,schema:e});if(!r.success)throw Co.wrap({value:t,cause:r.error});return r.value}async function sd({value:t,schema:e}){const r=B7(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:Co.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:Co.wrap({value:t,cause:n}),rawValue:t}}}async function G7({text:t,schema:e}){try{const r=nd(t);return e==null?r:Qr({value:r,schema:e})}catch(r){throw Mi.isInstance(r)||Co.isInstance(r)?r:new Mi({text:t,cause:r})}}async function N1({text:t,schema:e}){try{const r=nd(t);return e==null?{success:!0,value:r,rawValue:r}:await sd({value:r,schema:e})}catch(r){return{success:!1,error:Mi.isInstance(r)?r:new Mi({text:t,cause:r}),rawValue:void 0}}}function L1(t){try{return nd(t),!0}catch{return!1}}function W7({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await N1({text:r,schema:e}))}}))}async function Xr({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await sd({value:e[t],schema:r});if(!n.success)throw new s1({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var K7=()=>globalThis.fetch,Pr=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>j1({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),Y7=async({url:t,headers:e,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>j1({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),j1=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=K7()})=>{try{const i=await a(t,{method:"POST",headers:A1(e,`ai-sdk/provider-utils/${j7}`,N7()),body:r.content,signal:o}),c=$o(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw rd(u)||Ut.isInstance(u)?u:new Ut({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(rd(l)||Ut.isInstance(l))?l:new Ut({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw M7({error:i,url:t,requestBodyValues:r.values})}};function UR(t){return t}function cs({id:t,name:e,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c,...l})=>({type:"provider-defined",id:t,name:e,args:l,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c})}var Q7=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=$o(n);if(a.trim()==="")return{responseHeaders:i,value:new Ut({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await G7({text:a,schema:t});return{responseHeaders:i,value:new Ut({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new Ut({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},od=t=>async({response:e})=>{const r=$o(e);if(e.body==null)throw new b7({});return{responseHeaders:r,value:W7({stream:e.body,schema:t})}},ls=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await N1({text:s,schema:t}),a=$o(e);if(!o.success)throw new Ut({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},X7=()=>async({response:t,url:e,requestBodyValues:r})=>{const n=$o(t);if(!t.body)throw new Ut({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0});try{const s=await t.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new Ut({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0,cause:s})}};function ji(t){if(t.type==="object"){t.additionalProperties=!1;const e=t.properties;if(e!=null)for(const r in e)e[r]=ji(e[r])}return t.type==="array"&&t.items!=null&&(Array.isArray(t.items)?t.items=t.items.map(e=>ji(e)):t.items=ji(t.items)),t}var ex=(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("/")},tx=Symbol("Let zodToJsonSchema decide on which parser to use"),q1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},rx=t=>typeof t=="string"?{...q1,name:t}:{...q1,...t};function Nt(){return{}}function nx(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=Ue(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function sx(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function ox(){return{type:"boolean"}}function z1(t,e){return Ue(t.type._def,e)}var ax=(t,e)=>Ue(t.innerType._def,e);function D1(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>D1(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 ix(t)}}var ix=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function cx(t,e){return{...Ue(t.innerType._def,e),default:t.defaultValue()}}function lx(t,e){return e.effectStrategy==="input"?Ue(t.schema._def,e):Nt()}function ux(t){return{type:"string",enum:Array.from(t.values)}}var dx=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function px(t,e){const r=[Ue(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ue(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(dx(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function fx(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var ad=void 0,sr={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:()=>(ad===void 0&&(ad=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ad),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 U1(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":vt(r,sr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":vt(r,n.regex,n.message,e);break;case"cuid":vt(r,sr.cuid,n.message,e);break;case"cuid2":vt(r,sr.cuid2,n.message,e);break;case"startsWith":vt(r,RegExp(`^${id(n.value,e)}`),n.message,e);break;case"endsWith":vt(r,RegExp(`${id(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{vt(r,RegExp(id(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":vt(r,sr.base64url,n.message,e);break;case"jwt":vt(r,sr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&vt(r,sr.ipv4Cidr,n.message,e),n.version!=="v4"&&vt(r,sr.ipv6Cidr,n.message,e);break}case"emoji":vt(r,sr.emoji(),n.message,e);break;case"ulid":{vt(r,sr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{vt(r,sr.base64,n.message,e);break}}break}case"nanoid":vt(r,sr.nanoid,n.message,e)}return r}function id(t,e){return e.patternStrategy==="escape"?mx(t):t}var hx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mx(t){let e="";for(let r=0;r<t.length;r++)hx.has(t[r])||(e+="\\"),e+=t[r];return e}function or(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function vt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Z1(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Z1(e,n)}function Z1(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
576
- ]))`;continue}else if(s[l]==="$"){o+=`($|(?=[\r
577
- ]))`;continue}}if(n.s&&s[l]==="."){o+=i?`${s[l]}\r
578
- `:`[${s[l]}\r
579
- ]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function F1(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=U1(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=z1(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function gx(t,e){if(e.mapStrategy==="record")return F1(t,e);const r=Ue(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Nt(),n=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Nt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function yx(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function _x(){return{not:Nt()}}function vx(){return{type:"null"}}var cd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wx(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in cd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=cd[o._def.typeName];return a&&!s.includes(a)?[...s,a]: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,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return bx(t,e)}var bx=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ue(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 kx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[cd[t.innerType._def.typeName],"null"]};const r=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Sx(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Tx(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=$x(i),l=Ue(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=Cx(t,e);return o!==void 0&&(r.additionalProperties=o),r}function Cx(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ue(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 $x(t){try{return t.isOptional()}catch{return!0}}var Ex=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ue(t.innerType._def,e);const n=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Nt()},n]}:Nt()},xx=(t,e)=>{if(e.pipeStrategy==="input")return Ue(t.in._def,e);if(e.pipeStrategy==="output")return Ue(t.out._def,e);const r=Ue(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ue(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Ix(t,e){return Ue(t.type._def,e)}function Rx(t,e){const n={type:"array",uniqueItems:!0,items:Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function Px(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ue(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ox(){return{not:Nt()}}function Ax(){return Nt()}var Mx=(t,e)=>Ue(t.innerType._def,e),Nx=(t,e,r)=>{switch(e){case z.ZodString:return U1(t,r);case z.ZodNumber:return Sx(t);case z.ZodObject:return Tx(t,r);case z.ZodBigInt:return sx(t);case z.ZodBoolean:return ox();case z.ZodDate:return D1(t,r);case z.ZodUndefined:return Ox();case z.ZodNull:return vx();case z.ZodArray:return nx(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return wx(t,r);case z.ZodIntersection:return px(t,r);case z.ZodTuple:return Px(t,r);case z.ZodRecord:return F1(t,r);case z.ZodLiteral:return fx(t);case z.ZodEnum:return ux(t);case z.ZodNativeEnum:return yx(t);case z.ZodNullable:return kx(t,r);case z.ZodOptional:return Ex(t,r);case z.ZodMap:return gx(t,r);case z.ZodSet:return Rx(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return Ix(t,r);case z.ZodNaN:case z.ZodNever:return _x();case z.ZodEffects:return lx(t,r);case z.ZodAny:return Nt();case z.ZodUnknown:return Ax();case z.ZodDefault:return cx(t,r);case z.ZodBranded:return z1(t,r);case z.ZodReadonly:return Mx(t,r);case z.ZodCatch:return ax(t,r);case z.ZodPipeline:return xx(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ue(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==tx)return c}if(s&&!r){const c=Lx(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=Nx(t,t.typeName,e),i=typeof a=="function"?Ue(a(),e):a;if(i&&jx(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var Lx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ex(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`),Nt()):e.$refStrategy==="seen"?Nt():void 0}},jx=(t,e,r)=>(t.description&&(r.description=t.description),r),qx=t=>{const e=rx(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,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}]))}},zx=(t,e)=>{var r;const n=qx(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>{var h;return{...l,[u]:(h=Ue(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Nt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Ue(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Nt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},Dx=zx;function Ux(t,e){var r;const n=(r=void 0)!=null?r:!1;return V1(()=>Dx(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Zx(t,e){var r;const n=(r=void 0)!=null?r:!1;return V1(()=>ji(yc(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async s=>{const o=await _c(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Fx(t){return"_zod"in t}function Le(t,e){return Fx(t)?Zx(t):Ux(t)}var Vx=Symbol.for("vercel.ai.schema");function dt(t){let e;return()=>(e==null&&(e=t()),e)}function V1(t,{validate:e}={}){return{[Vx]:!0,_type:void 0,[Li]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}var{btoa:Hx,atob:Bx}=globalThis;function Jx(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Bx(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Gx(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Hx(e)}function us(t){return t instanceof Uint8Array?Gx(t):t}function Wx(t){return t?.replace(/\/$/,"")}var ld=C({error:C({message:m(),type:m().nullish(),param:ht().nullish(),code:ie([m(),N()]).nullish()})}),gr=Q7({errorSchema:ld,errorToMessage:t=>t.error.message});function H1(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),n=!(t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("chatgpt-4o")||t.startsWith("gpt-5-chat")),s=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:e,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:s}}function Kx({prompt:t,systemMessageMode:e="system"}){const r=[],n=[];for(const{role:s,content:o}of t)switch(s){case"system":{switch(e){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=e;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((a,i)=>{var c,l,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const p=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${p};base64,${us(a.data)}`,detail:(l=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:l.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Rr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:us(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:us(a.data),format:"mp3"}};default:throw new Rr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Rr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${us(a.data)}`}}}else throw new Rr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const c of o)switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of o){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function ud({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r?new Date(r*1e3):void 0}}function B1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Yx=_t(()=>Le(C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({message:C({role:L("assistant").nullish(),content:m().nullish(),tool_calls:M(C({id:m().nullish(),type:L("function"),function:C({name:m(),arguments:m()})})).nullish(),annotations:M(C({type:L("url_citation"),url_citation:C({start_index:N(),end_index:N(),url:m(),title:m()})})).nullish()}),index:N(),logprobs:C({content:M(C({token:m(),logprob:N(),top_logprobs:M(C({token:m(),logprob:N()}))})).nullish()}).nullish(),finish_reason:m().nullish()})),usage:C({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:C({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}))),Qx=_t(()=>Le(ie([C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({delta:C({role:xe(["assistant"]).nullish(),content:m().nullish(),tool_calls:M(C({index:N(),id:m().nullish(),type:L("function").nullish(),function:C({name:m().nullish(),arguments:m().nullish()})})).nullish(),annotations:M(C({type:L("url_citation"),url_citation:C({start_index:N(),end_index:N(),url:m(),title:m()})})).nullish()}).nullish(),logprobs:C({content:M(C({token:m(),logprob:N(),top_logprobs:M(C({token:m(),logprob:N()}))})).nullish()}).nullish(),finish_reason:m().nullish(),index:N()})),usage:C({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:C({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}),ld]))),Xx=_t(()=>Le(C({logitBias:be(lh(),N()).optional(),logprobs:ie([me(),N()]).optional(),parallelToolCalls:me().optional(),user:m().optional(),reasoningEffort:xe(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:N().optional(),store:me().optional(),metadata:be(m().max(64),m().max(512)).optional(),prediction:be(m(),ht()).optional(),structuredOutputs:me().optional(),serviceTier:xe(["auto","flex","priority","default"]).optional(),strictJsonSchema:me().optional(),textVerbosity:xe(["low","medium","high"]).optional(),promptCacheKey:m().optional(),promptCacheRetention:xe(["in_memory","24h"]).optional(),safetyIdentifier:m().optional()})));function eI({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:n}){t=t?.length?t:void 0;const s=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const o=[];for(const i of t)switch(i.type){case"function":o.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:s.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:s};const a=e.type;switch(a){case"auto":case"none":case"required":return{tools:o,toolChoice:a,toolWarnings:s};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:s};default:{const i=a;throw new Rr({functionality:`tool choice type: ${i}`})}}}var tI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,seed:l,tools:u,toolChoice:p,providerOptions:h}){var d,f,v,g;const w=[],y=(d=await Xr({provider:"openai",providerOptions:h,schema:Xx}))!=null?d:{},_=(f=y.structuredOutputs)!=null?f:!0,b=H1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!_&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=Kx({prompt:t,systemMessageMode:b.systemMessageMode});w.push(...S);const T=(v=y.strictJsonSchema)!=null?v:!1,x={model:this.modelId,logit_bias:y.logitBias,logprobs:y.logprobs===!0||typeof y.logprobs=="number"?!0:void 0,top_logprobs:typeof y.logprobs=="number"?y.logprobs:typeof y.logprobs=="boolean"&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:c?.type==="json"?_&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:T,name:(g=c.name)!=null?g:"response",description:c.description}}:{type:"json_object"}:void 0,stop:i,seed:l,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,prompt_cache_retention:y.promptCacheRetention,safety_identifier:y.safetyIdentifier,messages:k};b.isReasoningModel?((y.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,w.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,w.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,w.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),y.serviceTier==="flex"&&!b.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),y.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:R,toolChoice:j,toolWarnings:O}=eI({tools:u,toolChoice:p,structuredOutputs:_,strictJsonSchema:T});return{args:{...x,tools:R,tool_choice:j},warnings:[...w,...O]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f;const{args:v,warnings:g}=await this.getArgs(t),{responseHeaders:w,value:y,rawValue:_}=await Pr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:v,failedResponseHandler:gr,successfulResponseHandler:ls(Yx),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=y.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const j of(e=b.message.tool_calls)!=null?e:[])k.push({type:"tool-call",toolCallId:(r=j.id)!=null?r:nr(),toolName:j.function.name,input:j.function.arguments});for(const j of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:nr(),url:j.url_citation.url,title:j.url_citation.title});const T=(s=y.usage)==null?void 0:s.completion_tokens_details,x=(o=y.usage)==null?void 0:o.prompt_tokens_details,R={openai:{}};return T?.accepted_prediction_tokens!=null&&(R.openai.acceptedPredictionTokens=T?.accepted_prediction_tokens),T?.rejected_prediction_tokens!=null&&(R.openai.rejectedPredictionTokens=T?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(R.openai.logprobs=b.logprobs.content),{content:k,finishReason:B1(b.finish_reason),usage:{inputTokens:(c=(i=y.usage)==null?void 0:i.prompt_tokens)!=null?c:void 0,outputTokens:(u=(l=y.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(h=(p=y.usage)==null?void 0:p.total_tokens)!=null?h:void 0,reasoningTokens:(d=T?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=x?.cached_tokens)!=null?f:void 0},request:{body:v},response:{...ud(y),headers:w,body:_},warnings:g,providerMetadata:R}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Pr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:od(Qx),abortSignal:t.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!1,u=!1;const p={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var f,v,g,w,y,_,b,k,S,T,x,R,j,O,D,U,V,ne,fe,de,te,ye,H,P;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const F=h.value;if("error"in F){i="error",d.enqueue({type:"error",error:F.error});return}if(!l){const I=ud(F);Object.values(I).some(Boolean)&&(l=!0,d.enqueue({type:"response-metadata",...ud(F)}))}F.usage!=null&&(c.inputTokens=(f=F.usage.prompt_tokens)!=null?f:void 0,c.outputTokens=(v=F.usage.completion_tokens)!=null?v:void 0,c.totalTokens=(g=F.usage.total_tokens)!=null?g:void 0,c.reasoningTokens=(y=(w=F.usage.completion_tokens_details)==null?void 0:w.reasoning_tokens)!=null?y:void 0,c.cachedInputTokens=(b=(_=F.usage.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?b:void 0,((k=F.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(p.openai.acceptedPredictionTokens=(S=F.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((T=F.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(p.openai.rejectedPredictionTokens=(x=F.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens));const q=F.choices[0];if(q?.finish_reason!=null&&(i=B1(q.finish_reason)),((R=q?.logprobs)==null?void 0:R.content)!=null&&(p.openai.logprobs=q.logprobs.content),q?.delta==null)return;const E=q.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const I of E.tool_calls){const $=I.index;if(a[$]==null){if(I.type!=="function")throw new td({data:I,message:"Expected 'function' type."});if(I.id==null)throw new td({data:I,message:"Expected 'id' to be a string."});if(((j=I.function)==null?void 0:j.name)==null)throw new td({data:I,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),a[$]={id:I.id,type:"function",function:{name:I.function.name,arguments:(O=I.function.arguments)!=null?O:""},hasFinished:!1};const W=a[$];((D=W.function)==null?void 0:D.name)!=null&&((U=W.function)==null?void 0:U.arguments)!=null&&(W.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:W.id,delta:W.function.arguments}),L1(W.function.arguments)&&(d.enqueue({type:"tool-input-end",id:W.id}),d.enqueue({type:"tool-call",toolCallId:(V=W.id)!=null?V:nr(),toolName:W.function.name,input:W.function.arguments}),W.hasFinished=!0));continue}const B=a[$];B.hasFinished||(((ne=I.function)==null?void 0:ne.arguments)!=null&&(B.function.arguments+=(de=(fe=I.function)==null?void 0:fe.arguments)!=null?de:""),d.enqueue({type:"tool-input-delta",id:B.id,delta:(te=I.function.arguments)!=null?te:""}),((ye=B.function)==null?void 0:ye.name)!=null&&((H=B.function)==null?void 0:H.arguments)!=null&&L1(B.function.arguments)&&(d.enqueue({type:"tool-input-end",id:B.id}),d.enqueue({type:"tool-call",toolCallId:(P=B.id)!=null?P:nr(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(E.annotations!=null)for(const I of E.annotations)d.enqueue({type:"source",sourceType:"url",id:nr(),url:I.url_citation.url,title:I.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:c,...p!=null?{providerMetadata:p}:{}})}})),request:{body:n},response:{headers:s}}}};function rI({prompt:t,user:e="user",assistant:r="assistant"}){let n="";t[0].role==="system"&&(n+=`${t[0].content}
573
+ To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
580
574
 
581
- `,t=t.slice(1));for(const{role:s,content:o}of t)switch(s){case"system":throw new T7({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const a=o.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${e}:
575
+ Alternatively, you can use a provider module instead of the AI Gateway.
576
+
577
+ Learn more: \x1B[34m${r}\x1B[0m
578
+
579
+ `),{name:"GatewayAuthenticationError"})}function Ks({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function _v({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=Nd(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var R8={startSpan(){return al},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(al);if(typeof r=="function")return r(al);if(typeof n=="function")return n(al)}},al={spanContext(){return P8},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},P8={traceId:"",spanId:"",traceFlags:0};function wv({isEnabled:e=!1,tracer:t}={}){return e?t||Ax.getTracer("ai"):R8}async function Ys({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=gy.active();try{const i=await gy.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{bv(s,i)}finally{s.end()}throw i}})}function bv(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ol.ERROR,message:t.message})):e.setStatus({code:ol.ERROR})}async function Dr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function kv(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?h8(r.data):r.data}:r)})))}function Tv(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Er(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function qd(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function Cv(e,t){var r,n,o,s,a,i,l,c,u,h;return{inputTokens:Er(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Er((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Er((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:Er((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:Er(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Er((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Er((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(h=t.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Er(e.totalTokens,t.totalTokens),reasoningTokens:Er(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Er(e.cachedInputTokens,t.cachedInputTokens)}}function Er(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function il(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?r[n]=il(s,o):r[n]=o}return r}function M8({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var O8=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Sv(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Sv(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(Kn(a)||t===0)throw a;const i=ld(a),l=[...s,a],c=l.length;if(c>t)throw new rv({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&ut.isInstance(a)&&a.isRetryable===!0&&c<=t)return await g5(M8({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),Sv(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new rv({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Iv({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new jr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new jr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:O8({maxRetries:r,abortSignal:t})}}function Ev({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new Ux({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Pd({toolCallId:c.toolCallId,approvalId:c.approvalId});const h={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(h):a.push(h)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function ll(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Ld({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:h}){const{toolName:p,toolCallId:f,input:g}=e,_=t?.[p];if(_?.execute==null)return;const y={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return Ys({name:"ai.toolCall",attributes:Dr({telemetry:n,attributes:{...Ks({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let v;try{await u?.(y)}catch{}const m=ll();try{const k=xI({execute:_.execute.bind(_),input:g,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:a}});for await(const T of k)T.type==="preliminary"?c?.({...e,type:"tool-result",output:T.output,preliminary:!0}):v=T.output}catch(k){const T=ll()-m;try{await h?.({...y,success:!1,error:k,durationMs:T})}catch{}return bv(w,k),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:k,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const S=ll()-m;try{await h?.({...y,success:!0,output:v,durationMs:S})}catch{}try{w.setAttributes(await Dr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(v)}}}))}catch{}return{type:"tool-result",toolCallId:f,toolName:p,input:g,output:v,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function xv(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
580
+ `)}function $v(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Rv=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Mo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Po(this.base64Data)),this.uint8ArrayData}},N8=class extends Rv{constructor(e){super(e),this.type="file"}};async function Pv({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var A8={};Lx(A8,{array:()=>j8,choice:()=>D8,json:()=>U8,object:()=>L8,text:()=>cl});function q8(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const h=e.substring(n,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function Qs(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await ur({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await ur({text:q8(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var cl=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),L8=({schema:e,name:t,description:r})=>{const n=Qn(e);return{name:"object",responseFormat:Wt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await ur({text:o});if(!a.success)throw new xn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await cr({value:a.value,schema:n});if(!i.success)throw new xn({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await Qs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},j8=({element:e,name:t,description:r})=>{const n=Qn(e);return{name:"array",responseFormat:Wt(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await ur({text:o});if(!a.success)throw new xn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new xn({message:"No object generated: response did not match schema.",cause:new Gn({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await cr({value:l,schema:n});if(!c.success)throw new xn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await Qs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await cr({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},D8=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await ur({text:n});if(!s.success)throw new xn({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new xn({message:"No object generated: response did not match schema.",cause:new Gn({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await Qs(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),U8=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await ur({text:r});if(!o.success)throw new xn({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await Qs(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function Mv({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Ov(e);throw new Md({toolName:e.toolName})}try{return await Nv({toolCall:e,tools:t})}catch(a){if(r==null||!(Md.isInstance(a)||Rd.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await Qn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new Wx({cause:l,originalError:a})}if(i==null)throw a;return await Nv({toolCall:i,tools:t})}}catch(a){const i=await ur({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function Ov(e){const t=e.input.trim()===""?{success:!0,value:{}}:await ur({text:e.input});if(t.success===!1)throw new Rd({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function Nv({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await Ov(e);throw new Md({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Qn(n.inputSchema),s=e.input.trim()===""?await cr({value:{},schema:o}):await ur({text:e.input,schema:o});if(s.success===!1)throw new Rd({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var Av=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:a,rawFinishReason:i,usage:l,warnings:c,request:u,response:h,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=a,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=h,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function jd(e){return({steps:t})=>t.length===e}async function qv({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Dd({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Ws({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Ws({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Ws({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function Lv(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var z8=Ds({prefix:"aitxt",size:24});async function jv({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=jd(1),experimental_output:h,output:p=h,experimental_telemetry:f,providerOptions:g,experimental_activeTools:_,activeTools:y=_,experimental_prepareStep:w,prepareStep:v=w,experimental_repairToolCall:m,experimental_download:S,experimental_context:k,experimental_include:T,_internal:{generateId:b=z8}={},experimental_onStart:x,experimental_onStepStart:I,experimental_onToolCallStart:L,experimental_onToolCallFinish:O,onStepFinish:A,onFinish:N,...U}){const G=sl(e),J=Js(u),ue=Nd(l),re=av(l),ge=re!=null?new AbortController:void 0,V=Lv(i,ue!=null?AbortSignal.timeout(ue):void 0,ge?.signal),{maxRetries:R,retry:H}=Iv({maxRetries:a,abortSignal:V}),Z=Ad(U),E=In(c??{},`ai/${iv}`),M=_v({model:G,telemetry:f,headers:E,settings:{...Z,maxRetries:R}}),D={provider:G.provider,modelId:G.modelId},K=await yv({system:n,prompt:o,messages:s});try{await x?.({model:D,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,topP:Z.topP,topK:Z.topK,presencePenalty:Z.presencePenalty,frequencyPenalty:Z.frequencyPenalty,stopSequences:Z.stopSequences,seed:Z.seed,maxRetries:R,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:i,include:T,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k})}catch{}const ne=wv(f);try{return await Ys({name:"ai.generateText",attributes:Dr({telemetry:f,attributes:{...Ks({operationId:"ai.generateText",telemetry:f}),...M,"ai.model.provider":G.provider,"ai.model.id":G.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ne,fn:async ae=>{var Ie,z,F,Y,ee,le,be,tt,P,te,Oe,je,Kt;const gt=K.messages,Xe=[],{approvedToolApprovals:sn,deniedToolApprovals:rt}=Ev({messages:gt}),nr=sn.filter(it=>!it.toolCall.providerExecuted);if(rt.length>0||nr.length>0){const it=await Dv({toolCalls:nr.map(Se=>Se.toolCall),tools:t,tracer:ne,telemetry:f,messages:gt,abortSignal:V,experimental_context:k,stepNumber:0,model:D,onToolCallStart:L,onToolCallFinish:O}),Ct=[];for(const Se of it){const At=await Ws({toolCallId:Se.toolCallId,input:Se.input,tool:t?.[Se.toolName],output:Se.type==="tool-result"?Se.output:Se.error,errorMode:Se.type==="tool-error"?"json":"none"});Ct.push({type:"tool-result",toolCallId:Se.toolCallId,toolName:Se.toolName,output:At})}for(const Se of rt)Ct.push({type:"tool-result",toolCallId:Se.toolCall.toolCallId,toolName:Se.toolCall.toolName,output:{type:"execution-denied",reason:Se.approvalResponse.reason,...Se.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Se.approvalResponse.approvalId}}}}});Xe.push({role:"tool",content:Ct})}const an=[...sn,...rt].filter(it=>it.toolCall.providerExecuted);an.length>0&&Xe.push({role:"tool",content:an.map(it=>({type:"tool-approval-response",approvalId:it.approvalResponse.approvalId,approved:it.approvalResponse.approved,reason:it.approvalResponse.reason,providerExecuted:!0}))});const nt=Ad(U);let Ee,at=[],xe=[];const Qe=[],$r=new Map;do{const it=re!=null?setTimeout(()=>ge.abort(),re):void 0;try{const Ct=[...gt,...Xe],Se=await v?.({model:G,steps:Qe,stepNumber:Qe.length,messages:Ct,experimental_context:k}),At=sl((Ie=Se?.model)!=null?Ie:G),ht={provider:At.provider,modelId:At.modelId},St=await uv({prompt:{system:(z=Se?.system)!=null?z:K.system,messages:(F=Se?.messages)!=null?F:Ct},supportedUrls:await At.supportedUrls,download:S});k=(Y=Se?.experimental_context)!=null?Y:k;const pt=(ee=Se?.activeTools)!=null?ee:y,{toolChoice:ln,tools:Do}=await fv({tools:t,toolChoice:(le=Se?.toolChoice)!=null?le:r,activeTools:pt}),Tl=(be=Se?.messages)!=null?be:Ct,Cl=(tt=Se?.system)!=null?tt:K.system,sa=il(g,Se?.providerOptions);try{await I?.({stepNumber:Qe.length,model:ht,system:Cl,messages:Tl,tools:t,toolChoice:ln,activeTools:pt,steps:[...Qe],providerOptions:sa,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:T,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k})}catch{}Ee=await H(()=>{var Ne;return Ys({name:"ai.generateText.doGenerate",attributes:Dr({telemetry:f,attributes:{...Ks({operationId:"ai.generateText.doGenerate",telemetry:f}),...M,"ai.model.provider":At.provider,"ai.model.id":At.modelId,"ai.prompt.messages":{input:()=>kv(St)},"ai.prompt.tools":{input:()=>Do?.map(qt=>JSON.stringify(qt))},"ai.prompt.toolChoice":{input:()=>ln!=null?JSON.stringify(ln):void 0},"gen_ai.system":At.provider,"gen_ai.request.model":At.modelId,"gen_ai.request.frequency_penalty":U.frequencyPenalty,"gen_ai.request.max_tokens":U.maxOutputTokens,"gen_ai.request.presence_penalty":U.presencePenalty,"gen_ai.request.stop_sequences":U.stopSequences,"gen_ai.request.temperature":(Ne=U.temperature)!=null?Ne:void 0,"gen_ai.request.top_k":U.topK,"gen_ai.request.top_p":U.topP}}),tracer:ne,fn:async qt=>{var Rn,cn,Il,El,ca,xl,ua,Uo;const ft=await At.doGenerate({...nt,tools:Do,toolChoice:ln,responseFormat:await p?.responseFormat,prompt:St,providerOptions:sa,abortSignal:V,headers:E}),un={id:(cn=(Rn=ft.response)==null?void 0:Rn.id)!=null?cn:b(),timestamp:(El=(Il=ft.response)==null?void 0:Il.timestamp)!=null?El:new Date,modelId:(xl=(ca=ft.response)==null?void 0:ca.modelId)!=null?xl:At.modelId,headers:(ua=ft.response)==null?void 0:ua.headers,body:(Uo=ft.response)==null?void 0:Uo.body};return qt.setAttributes(await Dr({telemetry:f,attributes:{"ai.response.finishReason":ft.finishReason.unified,"ai.response.text":{output:()=>$v(ft.content)},"ai.response.reasoning":{output:()=>xv(ft.content)},"ai.response.toolCalls":{output:()=>{const $l=Uv(ft.content);return $l==null?void 0:JSON.stringify($l)}},"ai.response.id":un.id,"ai.response.model":un.modelId,"ai.response.timestamp":un.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ft.providerMetadata),"ai.usage.promptTokens":ft.usage.inputTokens.total,"ai.usage.completionTokens":ft.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ft.finishReason.unified],"gen_ai.response.id":un.id,"gen_ai.response.model":un.modelId,"gen_ai.usage.input_tokens":ft.usage.inputTokens.total,"gen_ai.usage.output_tokens":ft.usage.outputTokens.total}})),{...ft,response:un}}})});const pr=await Promise.all(Ee.content.filter(Ne=>Ne.type==="tool-call").map(Ne=>Mv({toolCall:Ne,tools:t,repairToolCall:m,system:n,messages:Ct}))),aa={};for(const Ne of pr){if(Ne.invalid)continue;const qt=t?.[Ne.toolName];qt!=null&&(qt?.onInputAvailable!=null&&await qt.onInputAvailable({input:Ne.input,toolCallId:Ne.toolCallId,messages:Ct,abortSignal:V,experimental_context:k}),await Pv({tool:qt,toolCall:Ne,messages:Ct,experimental_context:k})&&(aa[Ne.toolCallId]={type:"tool-approval-request",approvalId:b(),toolCall:Ne}))}const Sl=pr.filter(Ne=>Ne.invalid&&Ne.dynamic);xe=[];for(const Ne of Sl)xe.push({type:"tool-error",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,error:ld(Ne.error),dynamic:!0});at=pr.filter(Ne=>!Ne.providerExecuted),t!=null&&xe.push(...await Dv({toolCalls:at.filter(Ne=>!Ne.invalid&&aa[Ne.toolCallId]==null),tools:t,tracer:ne,telemetry:f,messages:Ct,abortSignal:V,experimental_context:k,stepNumber:Qe.length,model:ht,onToolCallStart:L,onToolCallFinish:O}));for(const Ne of pr){if(!Ne.providerExecuted)continue;const qt=t?.[Ne.toolName];qt?.type==="provider"&&qt.supportsDeferredResults&&(Ee.content.some(cn=>cn.type==="tool-result"&&cn.toolCallId===Ne.toolCallId)||$r.set(Ne.toolCallId,{toolName:Ne.toolName}))}for(const Ne of Ee.content)Ne.type==="tool-result"&&$r.delete(Ne.toolCallId);const ia=F8({content:Ee.content,toolCalls:pr,toolOutputs:xe,toolApprovalRequests:Object.values(aa),tools:t});Xe.push(...await Dd({content:ia,tools:t}));const $n=(P=T?.requestBody)==null||P?(te=Ee.request)!=null?te:{}:{...Ee.request,body:void 0},vt={...Ee.response,messages:structuredClone(Xe),body:(Oe=T?.responseBody)==null||Oe?(je=Ee.response)==null?void 0:je.body:void 0},Ur=Qe.length,la=new Av({stepNumber:Ur,model:ht,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k,content:ia,finishReason:Ee.finishReason.unified,rawFinishReason:Ee.finishReason.raw,usage:Tv(Ee.usage),warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,request:$n,response:vt});Od({warnings:(Kt=Ee.warnings)!=null?Kt:[],provider:ht.provider,model:ht.modelId}),Qe.push(la),await A?.(la)}finally{it!=null&&clearTimeout(it)}}while((at.length>0&&xe.length===at.length||$r.size>0)&&!await qv({stopConditions:J,steps:Qe}));ae.setAttributes(await Dr({telemetry:f,attributes:{"ai.response.finishReason":Ee.finishReason.unified,"ai.response.text":{output:()=>$v(Ee.content)},"ai.response.reasoning":{output:()=>xv(Ee.content)},"ai.response.toolCalls":{output:()=>{const it=Uv(Ee.content);return it==null?void 0:JSON.stringify(it)}},"ai.response.providerMetadata":JSON.stringify(Ee.providerMetadata),"ai.usage.promptTokens":Ee.usage.inputTokens.total,"ai.usage.completionTokens":Ee.usage.outputTokens.total}}));const Q=Qe[Qe.length-1],Ge=Qe.reduce((it,Ct)=>Cv(it,Ct.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await N?.({stepNumber:Q.stepNumber,model:Q.model,functionId:Q.functionId,metadata:Q.metadata,experimental_context:Q.experimental_context,finishReason:Q.finishReason,rawFinishReason:Q.rawFinishReason,usage:Q.usage,content:Q.content,text:Q.text,reasoningText:Q.reasoningText,reasoning:Q.reasoning,files:Q.files,sources:Q.sources,toolCalls:Q.toolCalls,staticToolCalls:Q.staticToolCalls,dynamicToolCalls:Q.dynamicToolCalls,toolResults:Q.toolResults,staticToolResults:Q.staticToolResults,dynamicToolResults:Q.dynamicToolResults,request:Q.request,response:Q.response,warnings:Q.warnings,providerMetadata:Q.providerMetadata,steps:Qe,totalUsage:Ge});let Rr;return Q.finishReason==="stop"&&(Rr=await(p??cl()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})),new Z8({steps:Qe,totalUsage:Ge,output:Rr})}})}catch(ae){throw vv(ae)}}async function Dv({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>Ld({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var Z8=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Uy;return this._output}};function Uv(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function F8({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new Rv(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new Pd({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function ul(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function V8({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ul(r,{"content-type":"text/plain; charset=utf-8"})})}function zv({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(h=>{e.once("drain",h)})}}catch(l){throw l}finally{e.end()}})()}function H8({response:e,status:t,statusText:r,headers:n,textStream:o}){zv({response:e,status:t,statusText:r,headers:Object.fromEntries(ul(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var Zv=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
581
+
582
+ `)},flush(e){e.enqueue(`data: [DONE]
583
+
584
+ `)}})}},Fv={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function B8({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new Zv);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ul(r,Fv)})}function J8({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function W8(e){return e.type.startsWith("data-")}function Ud(e){return e.type.startsWith("tool-")}function G8(e){return e.type==="dynamic-tool"}function K8(e){return Ud(e)||G8(e)}function Vv(e){return e.type.split("-").slice(1).join("-")}function Y8({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Q8({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var h,p,f,g;function _(m){const k=c.message.parts.filter(K8).find(T=>T.toolCallId===m);if(k==null)throw new qo({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return k}function y(m){var S;const k=c.message.parts.find(x=>Ud(x)&&x.toolCallId===m.toolCallId),T=m,b=k;k!=null?(k.state=m.state,b.input=T.input,b.output=T.output,b.errorText=T.errorText,b.rawInput=T.rawInput,b.preliminary=T.preliminary,m.title!==void 0&&(b.title=m.title),b.providerExecuted=(S=T.providerExecuted)!=null?S:k.providerExecuted,T.providerMetadata!=null&&(k.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function w(m){var S,k;const T=c.message.parts.find(I=>I.type==="dynamic-tool"&&I.toolCallId===m.toolCallId),b=m,x=T;T!=null?(T.state=m.state,x.toolName=m.toolName,x.input=b.input,x.output=b.output,x.errorText=b.errorText,x.rawInput=(S=b.rawInput)!=null?S:x.rawInput,x.preliminary=b.preliminary,m.title!==void 0&&(x.title=m.title),x.providerExecuted=(k=b.providerExecuted)!=null?k:T.providerExecuted,b.providerMetadata!=null&&(T.callProviderMetadata=b.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:b.input,output:b.output,errorText:b.errorText,preliminary:b.preliminary,providerExecuted:b.providerExecuted,title:m.title,...b.providerMetadata!=null?{callProviderMetadata:b.providerMetadata}:{}})}async function v(m){if(m!=null){const S=c.message.metadata!=null?il(c.message.metadata,m):m;t!=null&&await Pt({value:S,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=S}}switch(i.type){case"text-start":{const m={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=m,c.message.parts.push(m),u();break}case"text-delta":{const m=c.activeTextParts[i.id];if(m==null)throw new qo({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});m.text+=i.delta,m.providerMetadata=(h=i.providerMetadata)!=null?h:m.providerMetadata,u();break}case"text-end":{const m=c.activeTextParts[i.id];if(m==null)throw new qo({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});m.state="done",m.providerMetadata=(p=i.providerMetadata)!=null?p:m.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const m={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=m,c.message.parts.push(m),u();break}case"reasoning-delta":{const m=c.activeReasoningParts[i.id];if(m==null)throw new qo({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});m.text+=i.delta,m.providerMetadata=(f=i.providerMetadata)!=null?f:m.providerMetadata,u();break}case"reasoning-end":{const m=c.activeReasoningParts[i.id];if(m==null)throw new qo({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});m.providerMetadata=(g=i.providerMetadata)!=null?g:m.providerMetadata,m.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const m=c.message.parts.filter(Ud);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:m.length,dynamic:i.dynamic,title:i.title},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const m=c.partialToolCalls[i.toolCallId];if(m==null)throw new qo({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});m.text+=i.inputTextDelta;const{value:S}=await Qs(m.text);m.dynamic?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:S,title:m.title}):y({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:S,title:m.title}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const m=_(i.toolCallId);m.state="approval-requested",m.approval={id:i.approvalId},u();break}case"tool-output-denied":{const m=_(i.toolCallId);m.state="output-denied",u();break}case"tool-output-available":{const m=_(i.toolCallId);m.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:m.title}):y({toolCallId:i.toolCallId,toolName:Vv(m),state:"output-available",input:m.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,title:m.title}),u();break}case"tool-output-error":{const m=_(i.toolCallId);m.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:m.title}):y({toolCallId:i.toolCallId,toolName:Vv(m),state:"output-error",input:m.input,rawInput:m.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,title:m.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await v(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(W8(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(b=>"id"in b&&"data"in b&&b.id===i.id&&b.type===i.type),T=k>=0?k:c.message.parts.length;await Pt({value:i.data,schema:r[i.type],context:{field:`message.parts[${T}].data`,entityName:i.type,entityId:i.id}})}const m=i;if(m.transient){a?.(m);break}const S=m.id!=null?c.message.parts.find(k=>m.type===k.type&&m.id===k.id):void 0;S!=null?S.data=m.data:c.message.parts.push(m),a?.(m),u()}}l.enqueue(i)})}}))}function X8({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(g,_){if(g.type==="start"){const y=g;y.messageId==null&&e!=null&&(y.messageId=e)}g.type==="abort"&&(i=!0),_.enqueue(g)}}));if(n==null&&r==null)return l;const c=Y8({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async g=>{await g({state:c,write:()=>{}})};let h=!1;const p=async()=>{if(h||!n)return;h=!0;const g=c.message.id===a?.id;await n({isAborted:i,isContinuation:g,responseMessage:c.message,messages:[...g?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},f=async()=>{if(!r)return;const g=c.message.id===a?.id;try{await r({isContinuation:g,responseMessage:structuredClone(c.message),messages:[...g?t.slice(0,-1):t,structuredClone(c.message)]})}catch(_){o(_)}};return Q8({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(g,_){g.type==="finish-step"&&await f(),_.enqueue(g)},async cancel(){await p()},async flush(){await p()}}))}function e$({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new Zv);if(s){const[i,l]=a.tee();a=i,s({stream:l})}zv({response:e,status:t,statusText:r,headers:Object.fromEntries(ul(n,Fv).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Xs(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function t$({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function Hv(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function r$(){let e=[],t=null,r=!1,n=Hv();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=Hv(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function n$({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c,stepNumber:u,model:h,onToolCallStart:p,onToolCallFinish:f}){let g=null;const _=new ReadableStream({start(b){g=b}}),y=new Set,w=new Map,v=new Map;let m=!1,S;function k(){m&&y.size===0&&(S!=null&&g.enqueue(S),g.close())}const T=new TransformStream({async transform(b,x){const I=b.type;switch(I){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{x.enqueue(b);break}case"file":{x.enqueue({type:"file",file:new N8({data:b.data,mediaType:b.mediaType})});break}case"finish":{S={type:"finish",finishReason:b.finishReason.unified,rawFinishReason:b.finishReason.raw,usage:Tv(b.usage),providerMetadata:b.providerMetadata};break}case"tool-approval-request":{const L=v.get(b.toolCallId);if(L==null){g.enqueue({type:"error",error:new Pd({toolCallId:b.toolCallId,approvalId:b.approvalId})});break}x.enqueue({type:"tool-approval-request",approvalId:b.approvalId,toolCall:L});break}case"tool-call":{try{const L=await Mv({toolCall:b,tools:e,repairToolCall:i,system:o,messages:s});if(v.set(L.toolCallId,L),x.enqueue(L),L.invalid){g.enqueue({type:"tool-error",toolCallId:L.toolCallId,toolName:L.toolName,input:L.input,error:ld(L.error),dynamic:!0,title:L.title});break}const O=e?.[L.toolName];if(O==null)break;if(O.onInputAvailable!=null&&await O.onInputAvailable({input:L.input,toolCallId:L.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await Pv({tool:O,toolCall:L,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:L});break}if(w.set(L.toolCallId,L.input),O.execute!=null&&L.providerExecuted!==!0){const A=c();y.add(A),Ld({toolCall:L,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:h,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:N=>{g.enqueue(N)}}).then(N=>{g.enqueue(N)}).catch(N=>{g.enqueue({type:"error",error:N})}).finally(()=>{y.delete(A),k()})}}catch(L){g.enqueue({type:"error",error:L})}break}case"tool-result":{const L=b.toolName;b.isError?g.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:L,input:w.get(b.toolCallId),providerExecuted:!0,error:b.result,dynamic:b.dynamic}):x.enqueue({type:"tool-result",toolCallId:b.toolCallId,toolName:L,input:w.get(b.toolCallId),output:b.result,providerExecuted:!0,dynamic:b.dynamic});break}default:{const L=I;throw new Error(`Unhandled chunk type: ${L}`)}}},flush(){m=!0,k()}});return new ReadableStream({async start(b){return Promise.all([t.pipeThrough(T).pipeTo(new WritableStream({write(x){b.enqueue(x)},close(){}})),_.pipeTo(new WritableStream({write(x){b.enqueue(x)},close(){b.close()}}))])}})}var o$=Ds({prefix:"aitxt",size:24});function zd({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=jd(1),experimental_output:h,output:p=h,experimental_telemetry:f,prepareStep:g,providerOptions:_,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:v,experimental_transform:m,experimental_download:S,includeRawChunks:k=!1,onChunk:T,onError:b=({error:V})=>{console.error(V)},onFinish:x,onAbort:I,onStepFinish:L,experimental_onStart:O,experimental_onStepStart:A,experimental_onToolCallStart:N,experimental_onToolCallFinish:U,experimental_context:G,experimental_include:J,_internal:{now:ue=ll,generateId:re=o$}={},...ge}){const V=Nd(l),R=av(l),H=a8(l),Z=R!=null?new AbortController:void 0,E=H!=null?new AbortController:void 0;return new a$({model:sl(e),telemetry:f,headers:c,settings:ge,maxRetries:a,abortSignal:Lv(i,V!=null?AbortSignal.timeout(V):void 0,Z?.signal,E?.signal),stepTimeoutMs:R,stepAbortController:Z,chunkTimeoutMs:H,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Js(m),activeTools:w,repairToolCall:v,stopConditions:Js(u),output:p,providerOptions:_,prepareStep:g,includeRawChunks:k,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:T,onError:b,onFinish:x,onAbort:I,onStepFinish:L,onStart:O,onStepStart:A,onToolCallStart:N,onToolCallFinish:U,now:ue,generateId:re,experimental_context:G,download:S,include:J})}function s$(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const h=JSON.stringify(u.partial);h!==s&&(a({controller:l,partialOutput:u.partial}),s=h)}}})}var a$=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:h,messages:p,tools:f,toolChoice:g,transforms:_,activeTools:y,repairToolCall:w,stopConditions:v,output:m,providerOptions:S,prepareStep:k,includeRawChunks:T,now:b,generateId:x,timeout:I,stopWhen:L,originalAbortSignal:O,onChunk:A,onError:N,onFinish:U,onAbort:G,onStepFinish:J,onStart:ue,onStepStart:re,onToolCallStart:ge,onToolCallFinish:V,experimental_context:R,download:H,include:Z}){this._totalUsage=new js,this._finishReason=new js,this._rawFinishReason=new js,this._steps=new js,this.outputSpecification=m,this.includeRawChunks=T,this.tools=f;let E,M=[];const D=[];let K,ne,ae,Ie={},z=[];const F=[],Y=new Map;let ee,le={},be={};const tt=new TransformStream({async transform(nt,Ee){var at,xe,Qe,$r;Ee.enqueue(nt);const{part:Q}=nt;if((Q.type==="text-delta"||Q.type==="reasoning-delta"||Q.type==="source"||Q.type==="tool-call"||Q.type==="tool-result"||Q.type==="tool-input-start"||Q.type==="tool-input-delta"||Q.type==="raw")&&await A?.({chunk:Q}),Q.type==="error"&&await N({error:vv(Q.error)}),Q.type==="text-start"&&(le[Q.id]={type:"text",text:"",providerMetadata:Q.providerMetadata},M.push(le[Q.id])),Q.type==="text-delta"){const Ge=le[Q.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${Q.id} not found`},partialOutput:void 0});return}Ge.text+=Q.text,Ge.providerMetadata=(at=Q.providerMetadata)!=null?at:Ge.providerMetadata}if(Q.type==="text-end"){const Ge=le[Q.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${Q.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=(xe=Q.providerMetadata)!=null?xe:Ge.providerMetadata,delete le[Q.id]}if(Q.type==="reasoning-start"&&(be[Q.id]={type:"reasoning",text:"",providerMetadata:Q.providerMetadata},M.push(be[Q.id])),Q.type==="reasoning-delta"){const Ge=be[Q.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${Q.id} not found`},partialOutput:void 0});return}Ge.text+=Q.text,Ge.providerMetadata=(Qe=Q.providerMetadata)!=null?Qe:Ge.providerMetadata}if(Q.type==="reasoning-end"){const Ge=be[Q.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${Q.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=($r=Q.providerMetadata)!=null?$r:Ge.providerMetadata,delete be[Q.id]}if(Q.type==="file"&&M.push({type:"file",file:Q.file}),Q.type==="source"&&M.push(Q),Q.type==="tool-call"&&M.push(Q),Q.type==="tool-result"&&!Q.preliminary&&M.push(Q),Q.type==="tool-approval-request"&&M.push(Q),Q.type==="tool-error"&&M.push(Q),Q.type==="start-step"&&(M=[],be={},le={},Ie=Q.request,z=Q.warnings),Q.type==="finish-step"){const Ge=await Dd({content:M,tools:f}),Rr=new Av({stepNumber:F.length,model:nr,...an,experimental_context:R,content:M,finishReason:Q.finishReason,rawFinishReason:Q.rawFinishReason,usage:Q.usage,warnings:z,request:Ie,response:{...Q.response,messages:[...D,...Ge]},providerMetadata:Q.providerMetadata});await J?.(Rr),Od({warnings:z,provider:nr.provider,model:nr.modelId}),F.push(Rr),D.push(...Ge),E.resolve()}Q.type==="finish"&&(ae=Q.totalUsage,K=Q.finishReason,ne=Q.rawFinishReason)},async flush(nt){try{if(F.length===0){const Qe=s?.aborted?s.reason:new Uy({message:"No output generated. Check the stream for errors."});rt._finishReason.reject(Qe),rt._rawFinishReason.reject(Qe),rt._totalUsage.reject(Qe),rt._steps.reject(Qe);return}const Ee=K??"other",at=ae??qd();rt._finishReason.resolve(Ee),rt._rawFinishReason.resolve(ne),rt._totalUsage.resolve(at),rt._steps.resolve(F);const xe=F[F.length-1];await U?.({stepNumber:xe.stepNumber,model:xe.model,functionId:xe.functionId,metadata:xe.metadata,experimental_context:xe.experimental_context,finishReason:xe.finishReason,rawFinishReason:xe.rawFinishReason,totalUsage:at,usage:xe.usage,content:xe.content,text:xe.text,reasoningText:xe.reasoningText,reasoning:xe.reasoning,files:xe.files,sources:xe.sources,toolCalls:xe.toolCalls,staticToolCalls:xe.staticToolCalls,dynamicToolCalls:xe.dynamicToolCalls,toolResults:xe.toolResults,staticToolResults:xe.staticToolResults,dynamicToolResults:xe.dynamicToolResults,request:xe.request,response:xe.response,warnings:xe.warnings,providerMetadata:xe.providerMetadata,steps:F}),ee.setAttributes(await Dr({telemetry:t,attributes:{"ai.response.finishReason":Ee,"ai.response.text":{output:()=>xe.text},"ai.response.reasoning":{output:()=>xe.reasoningText},"ai.response.toolCalls":{output:()=>{var Qe;return(Qe=xe.toolCalls)!=null&&Qe.length?JSON.stringify(xe.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(xe.providerMetadata),"ai.usage.inputTokens":at.inputTokens,"ai.usage.outputTokens":at.outputTokens,"ai.usage.totalTokens":at.totalTokens,"ai.usage.reasoningTokens":at.reasoningTokens,"ai.usage.cachedInputTokens":at.cachedInputTokens}}))}catch(Ee){nt.error(Ee)}finally{ee.end()}}}),P=r$();this.addStream=P.addStream,this.closeStream=P.close;const te=P.stream.getReader();let Oe=new ReadableStream({async start(nt){nt.enqueue({type:"start"})},async pull(nt){function Ee(){G?.({steps:F}),nt.enqueue({type:"abort",...s?.reason!==void 0?{reason:Jn(s.reason)}:{}}),nt.close()}try{const{done:at,value:xe}=await te.read();if(at){nt.close();return}if(s?.aborted){Ee();return}nt.enqueue(xe)}catch(at){Kn(at)&&s?.aborted?Ee():nt.error(at)}},cancel(nt){return P.stream.cancel(nt)}});for(const nt of _)Oe=Oe.pipeThrough(nt({tools:f,stopStream(){P.terminate()}}));this.baseStream=Oe.pipeThrough(s$(m??cl())).pipeThrough(tt);const{maxRetries:je,retry:Kt}=Iv({maxRetries:o,abortSignal:s}),gt=wv(t),Xe=Ad(n),sn=_v({model:e,telemetry:t,headers:r,settings:{...Xe,maxRetries:je}}),rt=this,nr={provider:e.provider,modelId:e.modelId},an={functionId:t?.functionId,metadata:t?.metadata};Ys({name:"ai.streamText",attributes:Dr({telemetry:t,attributes:{...Ks({operationId:"ai.streamText",telemetry:t}),...sn,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:gt,endWhenDone:!1,fn:async nt=>{ee=nt;const Ee=await yv({system:u,prompt:h,messages:p});try{await ue?.({model:nr,system:u,prompt:h,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:Xe.maxOutputTokens,temperature:Xe.temperature,topP:Xe.topP,topK:Xe.topK,presencePenalty:Xe.presencePenalty,frequencyPenalty:Xe.frequencyPenalty,stopSequences:Xe.stopSequences,seed:Xe.seed,maxRetries:je,timeout:I,headers:r,providerOptions:S,stopWhen:L,output:m,abortSignal:O,include:Z,...an,experimental_context:R})}catch{}const at=Ee.messages,xe=[],{approvedToolApprovals:Qe,deniedToolApprovals:$r}=Ev({messages:at});if($r.length>0||Qe.length>0){const Ge=[...Qe,...$r].filter(ht=>ht.toolCall.providerExecuted),Rr=Qe.filter(ht=>!ht.toolCall.providerExecuted),it=$r.filter(ht=>!ht.toolCall.providerExecuted),Ct=$r.filter(ht=>ht.toolCall.providerExecuted);let Se;const At=new ReadableStream({start(ht){Se=ht}});rt.addStream(At);try{for(const St of[...it,...Ct])Se?.enqueue({type:"tool-output-denied",toolCallId:St.toolCall.toolCallId,toolName:St.toolCall.toolName});const ht=[];if(await Promise.all(Rr.map(async St=>{const pt=await Ld({toolCall:St.toolCall,tools:f,tracer:gt,telemetry:t,messages:at,abortSignal:s,experimental_context:R,stepNumber:F.length,model:nr,onToolCallStart:ge,onToolCallFinish:V,onPreliminaryToolResult:ln=>{Se?.enqueue(ln)}});pt!=null&&(Se?.enqueue(pt),ht.push(pt))})),Ge.length>0&&xe.push({role:"tool",content:Ge.map(St=>({type:"tool-approval-response",approvalId:St.approvalResponse.approvalId,approved:St.approvalResponse.approved,reason:St.approvalResponse.reason,providerExecuted:!0}))}),ht.length>0||it.length>0){const St=[];for(const pt of ht)St.push({type:"tool-result",toolCallId:pt.toolCallId,toolName:pt.toolName,output:await Ws({toolCallId:pt.toolCallId,input:pt.input,tool:f?.[pt.toolName],output:pt.type==="tool-result"?pt.output:pt.error,errorMode:pt.type==="tool-error"?"json":"none"})});for(const pt of it)St.push({type:"tool-result",toolCallId:pt.toolCall.toolCallId,toolName:pt.toolCall.toolName,output:{type:"execution-denied",reason:pt.approvalResponse.reason}});xe.push({role:"tool",content:St})}}finally{Se?.close()}}D.push(...xe);async function Q({currentStep:Ge,responseMessages:Rr,usage:it}){var Ct,Se,At,ht,St,pt,ln,Do,Tl;const Cl=rt.includeRawChunks,sa=a!=null?setTimeout(()=>i.abort(),a):void 0;let pr;function aa(){l!=null&&(pr!=null&&clearTimeout(pr),pr=setTimeout(()=>c.abort(),l))}function Sl(){pr!=null&&(clearTimeout(pr),pr=void 0)}function ia(){sa!=null&&clearTimeout(sa)}try{E=new js;const $n=[...at,...Rr],vt=await k?.({model:e,steps:F,stepNumber:F.length,messages:$n,experimental_context:R}),Ur=sl((Ct=vt?.model)!=null?Ct:e),la={provider:Ur.provider,modelId:Ur.modelId},Ne=await uv({prompt:{system:(Se=vt?.system)!=null?Se:Ee.system,messages:(At=vt?.messages)!=null?At:$n},supportedUrls:await Ur.supportedUrls,download:H}),qt=(ht=vt?.activeTools)!=null?ht:y,{toolChoice:Rn,tools:cn}=await fv({tools:f,toolChoice:(St=vt?.toolChoice)!=null?St:g,activeTools:qt});R=(pt=vt?.experimental_context)!=null?pt:R;const Il=(ln=vt?.messages)!=null?ln:$n,El=(Do=vt?.system)!=null?Do:Ee.system,ca=il(S,vt?.providerOptions);try{await re?.({stepNumber:F.length,model:la,system:El,messages:Il,tools:f,toolChoice:Rn,activeTools:qt,steps:[...F],providerOptions:ca,timeout:I,headers:r,stopWhen:L,output:m,abortSignal:O,include:Z,...an,experimental_context:R})}catch{}const{result:{stream:xl,response:ua,request:Uo},doStreamSpan:ft,startTimestampMs:un}=await Kt(()=>Ys({name:"ai.streamText.doStream",attributes:Dr({telemetry:t,attributes:{...Ks({operationId:"ai.streamText.doStream",telemetry:t}),...sn,"ai.model.provider":Ur.provider,"ai.model.id":Ur.modelId,"ai.prompt.messages":{input:()=>kv(Ne)},"ai.prompt.tools":{input:()=>cn?.map(_e=>JSON.stringify(_e))},"ai.prompt.toolChoice":{input:()=>Rn!=null?JSON.stringify(Rn):void 0},"gen_ai.system":Ur.provider,"gen_ai.request.model":Ur.modelId,"gen_ai.request.frequency_penalty":Xe.frequencyPenalty,"gen_ai.request.max_tokens":Xe.maxOutputTokens,"gen_ai.request.presence_penalty":Xe.presencePenalty,"gen_ai.request.stop_sequences":Xe.stopSequences,"gen_ai.request.temperature":Xe.temperature,"gen_ai.request.top_k":Xe.topK,"gen_ai.request.top_p":Xe.topP}}),tracer:gt,endWhenDone:!1,fn:async _e=>({startTimestampMs:b(),doStreamSpan:_e,result:await Ur.doStream({...Xe,tools:cn,toolChoice:Rn,responseFormat:await m?.responseFormat,prompt:Ne,providerOptions:ca,abortSignal:s,headers:r,includeRawChunks:Cl})})})),$l=n$({tools:f,generatorStream:xl,tracer:gt,telemetry:t,system:u,messages:$n,repairToolCall:w,abortSignal:s,experimental_context:R,generateId:x,stepNumber:F.length,model:la,onToolCallStart:ge,onToolCallFinish:V}),ZP=(Tl=Z?.requestBody)==null||Tl?Uo??{}:{...Uo,body:void 0},da=[],pa=[];let np;const op={};let zo="other",sp,Pr=qd(),ap,q1=!0,zr={id:x(),timestamp:new Date,modelId:nr.modelId},L1="";rt.addStream($l.pipeThrough(new TransformStream({async transform(_e,Mt){var fa,ha,Rl,mt,Zr;if(aa(),_e.type==="stream-start"){np=_e.warnings;return}if(q1){const yt=b()-un;q1=!1,ft.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":yt}),ft.setAttributes({"ai.response.msToFirstChunk":yt}),Mt.enqueue({type:"start-step",request:ZP,warnings:np??[]})}const ip=_e.type;switch(ip){case"tool-approval-request":case"text-start":case"text-end":{Mt.enqueue(_e);break}case"text-delta":{_e.delta.length>0&&(Mt.enqueue({type:"text-delta",id:_e.id,text:_e.delta,providerMetadata:_e.providerMetadata}),L1+=_e.delta);break}case"reasoning-start":case"reasoning-end":{Mt.enqueue(_e);break}case"reasoning-delta":{Mt.enqueue({type:"reasoning-delta",id:_e.id,text:_e.delta,providerMetadata:_e.providerMetadata});break}case"tool-call":{Mt.enqueue(_e),da.push(_e);break}case"tool-result":{Mt.enqueue(_e),_e.preliminary||pa.push(_e);break}case"tool-error":{Mt.enqueue(_e),pa.push(_e);break}case"response-metadata":{zr={id:(fa=_e.id)!=null?fa:zr.id,timestamp:(ha=_e.timestamp)!=null?ha:zr.timestamp,modelId:(Rl=_e.modelId)!=null?Rl:zr.modelId};break}case"finish":{Pr=_e.usage,zo=_e.finishReason,sp=_e.rawFinishReason,ap=_e.providerMetadata;const yt=b()-un;ft.addEvent("ai.stream.finish"),ft.setAttributes({"ai.response.msToFinish":yt,"ai.response.avgOutputTokensPerSecond":1e3*((mt=Pr.outputTokens)!=null?mt:0)/yt});break}case"file":{Mt.enqueue(_e);break}case"source":{Mt.enqueue(_e);break}case"tool-input-start":{op[_e.id]=_e.toolName;const yt=f?.[_e.toolName];yt?.onInputStart!=null&&await yt.onInputStart({toolCallId:_e.id,messages:$n,abortSignal:s,experimental_context:R}),Mt.enqueue({..._e,dynamic:(Zr=_e.dynamic)!=null?Zr:yt?.type==="dynamic",title:yt?.title});break}case"tool-input-end":{delete op[_e.id],Mt.enqueue(_e);break}case"tool-input-delta":{const yt=op[_e.id],lp=f?.[yt];lp?.onInputDelta!=null&&await lp.onInputDelta({inputTextDelta:_e.delta,toolCallId:_e.id,messages:$n,abortSignal:s,experimental_context:R}),Mt.enqueue(_e);break}case"error":{Mt.enqueue(_e),zo="error";break}case"raw":{Cl&&Mt.enqueue(_e);break}default:{const yt=ip;throw new Error(`Unknown chunk type: ${yt}`)}}},async flush(_e){const Mt=da.length>0?JSON.stringify(da):void 0;try{ft.setAttributes(await Dr({telemetry:t,attributes:{"ai.response.finishReason":zo,"ai.response.text":{output:()=>L1},"ai.response.reasoning":{output:()=>{const mt=M.filter(Zr=>Zr.type==="reasoning");return mt.length>0?mt.map(Zr=>Zr.text).join(`
585
+ `):void 0}},"ai.response.toolCalls":{output:()=>Mt},"ai.response.id":zr.id,"ai.response.model":zr.modelId,"ai.response.timestamp":zr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ap),"ai.usage.inputTokens":Pr.inputTokens,"ai.usage.outputTokens":Pr.outputTokens,"ai.usage.totalTokens":Pr.totalTokens,"ai.usage.reasoningTokens":Pr.reasoningTokens,"ai.usage.cachedInputTokens":Pr.cachedInputTokens,"gen_ai.response.finish_reasons":[zo],"gen_ai.response.id":zr.id,"gen_ai.response.model":zr.modelId,"gen_ai.usage.input_tokens":Pr.inputTokens,"gen_ai.usage.output_tokens":Pr.outputTokens}}))}catch{}finally{ft.end()}_e.enqueue({type:"finish-step",finishReason:zo,rawFinishReason:sp,usage:Pr,providerMetadata:ap,response:{...zr,headers:ua?.headers}});const fa=Cv(it,Pr);await E.promise;const ha=da.filter(mt=>mt.providerExecuted!==!0),Rl=pa.filter(mt=>mt.providerExecuted!==!0);for(const mt of da){if(mt.providerExecuted!==!0)continue;const Zr=f?.[mt.toolName];Zr?.type==="provider"&&Zr.supportsDeferredResults&&(pa.some(yt=>(yt.type==="tool-result"||yt.type==="tool-error")&&yt.toolCallId===mt.toolCallId)||Y.set(mt.toolCallId,{toolName:mt.toolName}))}for(const mt of pa)(mt.type==="tool-result"||mt.type==="tool-error")&&Y.delete(mt.toolCallId);if(ia(),Sl(),(ha.length>0&&Rl.length===ha.length||Y.size>0)&&!await qv({stopConditions:v,steps:F})){Rr.push(...await Dd({content:F[F.length-1].content,tools:f}));try{await Q({currentStep:Ge+1,responseMessages:Rr,usage:fa})}catch(mt){_e.enqueue({type:"error",error:mt}),rt.closeStream()}}else _e.enqueue({type:"finish",finishReason:zo,rawFinishReason:sp,totalUsage:fa}),rt.closeStream()}})))}finally{ia(),Sl()}}await Q({currentStep:0,responseMessages:xe,usage:qd()})}}).catch(nt=>{rt.addStream(new ReadableStream({start(Ee){Ee.enqueue({type:"error",error:nt}),Ee.close()}})),rt.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Xs(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Xs(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await t$({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Xs(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new qr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Xs(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:cl()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=Jn}={}){const c=t!=null?J8({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var f;const g=(f=this.tools)==null?void 0:f[p.toolName];return g==null?p.dynamic:g?.type==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const g=n?.({part:p}),_=p.type;switch(_){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{s&&p.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const y=u(p);f.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const y=u(p);p.invalid?f.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):f.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{f.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const y=u(p);f.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=u(p);f.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-output-denied":{f.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{f.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:p.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=_;throw new Error(`Unknown chunk type: ${y}`)}}g!=null&&_!=="start"&&_!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:g})}}));return Xs(X8({stream:h,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){e$({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){H8({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return B8({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return V8({textStream:this.textStream,...e})}};Ds({prefix:"aiobj",size:24}),Ds({prefix:"aiobj",size:24});var i$="AI_MCPClientError",Bv=`vercel.ai.error.${i$}`,l$=Symbol.for(Bv),Jv,Wv,Ze=class extends(Wv=ve,Jv=l$,Wv){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Jv]=!0,this.data=n,this.code=o}static isInstance(e){return ve.hasMarker(e,Bv)}},Lo="2025-06-18",c$=[Lo,"2025-03-26","2024-11-05"],u$=pe(ye(d(),Me())),d$=ct({name:d(),version:d()}),dl=ct({_meta:pe(C({}).loose())}),nn=dl,Gv=C({method:d(),params:pe(dl)}),Kv=C({applyDefaults:pe(me())}).loose(),p$=ct({experimental:pe(C({}).loose()),logging:pe(C({}).loose()),prompts:pe(ct({listChanged:pe(me())})),resources:pe(ct({subscribe:pe(me()),listChanged:pe(me())})),tools:pe(ct({listChanged:pe(me())})),elicitation:pe(Kv)});C({elicitation:pe(Kv)}).loose();var f$=nn.extend({protocolVersion:d(),capabilities:p$,serverInfo:d$,instructions:pe(d())}),Zd=nn.extend({nextCursor:pe(d())}),h$=C({name:d(),title:pe(d()),description:pe(d()),inputSchema:C({type:$("object"),properties:pe(C({}).loose())}).loose(),outputSchema:pe(C({}).loose()),annotations:pe(C({title:pe(d())}).loose()),_meta:u$}).loose(),m$=Zd.extend({tools:q(h$)}),Yv=C({type:$("text"),text:d()}).loose(),Qv=C({type:$("image"),data:Zh(),mimeType:d()}).loose(),g$=C({uri:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d()),size:pe(j())}).loose(),y$=Zd.extend({resources:q(g$)}),Xv=C({uri:d(),name:pe(d()),title:pe(d()),mimeType:pe(d())}).loose(),e_=Xv.extend({text:d()}),t_=Xv.extend({blob:Zh()}),r_=C({type:$("resource"),resource:oe([e_,t_])}).loose(),v$=nn.extend({content:q(oe([Yv,Qv,r_])),structuredContent:pe(Me()),isError:me().default(!1).optional()}).or(nn.extend({toolResult:Me()})),_$=C({uriTemplate:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d())}).loose(),w$=nn.extend({resourceTemplates:q(_$)}),b$=nn.extend({contents:q(oe([e_,t_]))}),k$=C({name:d(),description:pe(d()),required:pe(me())}).loose(),T$=C({name:d(),title:pe(d()),description:pe(d()),arguments:pe(q(k$))}).loose(),C$=Zd.extend({prompts:q(T$)}),S$=C({role:oe([$("user"),$("assistant")]),content:oe([Yv,Qv,r_])}).loose(),I$=nn.extend({description:pe(d()),messages:q(S$)}),E$=dl.extend({message:d(),requestedSchema:Me()}),n_=Gv.extend({method:$("elicitation/create"),params:E$}),x$=nn.extend({action:oe([$("accept"),$("decline"),$("cancel")]),content:pe(ye(d(),Me()))}),pl="2.0",$$=C({jsonrpc:$(pl),id:oe([d(),j().int()])}).merge(Gv).strict(),R$=C({jsonrpc:$(pl),id:oe([d(),j().int()]),result:nn}).strict(),P$=C({jsonrpc:$(pl),id:oe([d(),j().int()]),error:C({code:j().int(),message:d(),data:pe(Me())})}).strict(),M$=C({jsonrpc:$(pl)}).merge(C({method:d(),params:pe(dl)})).strict(),ea=oe([$$,M$,R$,P$]),o_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",s_=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Gt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Qh.custom,message:"URL must be parseable",fatal:!0}),Gf}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),O$=C({resource:d().url(),authorization_servers:q(Gt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:me().optional()}).passthrough(),a_=C({issuer:d(),authorization_endpoint:Gt,token_endpoint:Gt,registration_endpoint:Gt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),N$=C({issuer:d(),authorization_endpoint:Gt,token_endpoint:Gt,userinfo_endpoint:Gt.optional(),jwks_uri:Gt,registration_endpoint:Gt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),A$=N$.merge(a_.pick({code_challenge_methods_supported:!0})),q$=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),L$=C({redirect_uris:q(Gt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Gt.optional(),logo_uri:Gt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Gt.optional(),policy_uri:d().optional(),jwks_uri:Gt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),j$=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),D$=L$.merge(q$),U$="AI_MCPClientOAuthError",i_=`vercel.ai.error.${U$}`,z$=Symbol.for(i_),l_,c_,ta=class extends(c_=ve,l_=z$,c_){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[l_]=!0}static isInstance(e){return ve.hasMarker(e,i_)}},jo=class extends ta{};jo.errorCode="server_error";var fl=class extends ta{};fl.errorCode="invalid_client";var hl=class extends ta{};hl.errorCode="invalid_grant";var ml=class extends ta{};ml.errorCode="unauthorized_client";var Z$={[jo.errorCode]:jo,[fl.errorCode]:fl,[hl.errorCode]:hl,[ml.errorCode]:ml};function F$(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function V$({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var gl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function yl(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function H$(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Fd(e,void 0,r):void 0;throw n}}async function u_(e,t,r=fetch){return await Fd(e,{"MCP-Protocol-Version":t},r)}function B$(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function J$(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Lo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=H$(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await u_(l,i,r);if(!n?.metadataUrl&&B$(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await u_(u,i,r)}return c}async function W$(e,t,r=fetch){const n=await J$(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return O$.parse(await n.json())}function G$(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function K$(e,{fetchFn:t=fetch,protocolVersion:r=Lo}={}){var n;const o={"MCP-Protocol-Version":r},s=G$(e);for(const{url:a,type:i}of s){const l=await Fd(a,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return a_.parse(await l.json());{const c=A$.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function Y$(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await r0(),h=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:h}}function d_(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function p_(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":Q$(o,s,r);return;case"client_secret_post":X$(o,s,n);return;case"none":e7(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Q$(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function X$(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function e7(e,t){t.set("client_id",e)}async function Vd(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=j$.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=Z$[o]||jo;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new jo({message:o})}}async function t7(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",h=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,f,e,t);else{const _=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=d_(r,_);p_(y,r,p,f)}a&&f.set("resource",a.href);const g=await(l??fetch)(h,{method:"POST",headers:p,body:f});if(!g.ok)throw await Vd(g);return s_.parse(await g.json())}async function r7(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,h,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],g=d_(r,f);p_(g,r,u,h)}o&&h.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:h});if(!p.ok)throw await Vd(p);return s_.parse({refresh_token:n,...await p.json()})}async function n7(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Vd(s);return D$.parse(await s.json())}async function vl(e,t){var r,n;try{return await Hd(e,t)}catch(o){if(o instanceof fl||o instanceof ml)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Hd(e,t);if(o instanceof hl)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Hd(e,t);throw o}}async function o7(e,t,r){const n=F$(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!V$({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Hd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await W$(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await o7(t,e,a),c=await K$(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const _=await n7(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(_),u=_}if(r!==void 0){const _=await e.codeVerifier(),y=await t7(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:_,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const _=await r7(i,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof ta)||_ instanceof jo))throw _}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await Y$(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(f),"REDIRECT"}var s7=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Lo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return In(t,`ai-sdk/${o_}`,Us())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=yl(u);try{if(await vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new gl;return(s=this.onerror)==null||s.call(this,_),t(_)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return r(!0)}if(!u.ok||!u.body){let g=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const _=new Ze({message:g});return(i=this.onerror)==null||i.call(this,_),t(_)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Io).getReader(),f=async()=>{var g,_,y;try{for(;;){const{done:w,value:v}=await p.read();if(w){if(this.connected)throw this.connected=!1,new Ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:S}=v;if(m==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new Ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(m==="message")try{const k=ea.parse(JSON.parse(S));(g=this.onmessage)==null||g.call(this,k)}catch(k){const T=new Ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(_=this.onerror)==null||_.call(this,T)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(y=this.onerror)==null||y.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},f()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},h=await fetch(t,u);if(h.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=yl(h);try{if(await vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new gl;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!h.ok){const p=await h.text().catch(()=>null),f=new Ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${h.status}): ${p}`});(i=this.onerror)==null||i.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},a7=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Lo};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return In(t,`ai-sdk/${o_}`,Us())}async start(){if(this.abortController)throw new Ze({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const h={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},p=await fetch(this.url,h),f=p.headers.get("mcp-session-id");if(f&&(this.sessionId=f),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=yl(p);try{if(await vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new gl}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const m=new Ze({message:v});throw(s=this.onerror)==null||s.call(this,m),m}if(!("id"in e))return;const _=p.headers.get("content-type")||"";if(_.includes("application/json")){const w=await p.json(),v=Array.isArray(w)?w.map(m=>ea.parse(m)):[ea.parse(w)];for(const m of v)(a=this.onmessage)==null||a.call(this,m);return}if(_.includes("text/event-stream")){if(!p.body){const S=new Ze({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,S),S}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Io).getReader();(async()=>{var S,k,T;try{for(;;){const{done:b,value:x}=await v.read();if(b)return;const{event:I,data:L}=x;if(I==="message")try{const O=ea.parse(JSON.parse(L));(S=this.onmessage)==null||S.call(this,O)}catch(O){const A=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:O});(k=this.onerror)==null||k.call(this,A)}}}catch(b){if(b instanceof Error&&b.name==="AbortError")return;(T=this.onerror)==null||T.call(this,b)}})();return}const y=new Ze({message:`MCP HTTP Transport Error: Unexpected content type: ${_}`});throw(l=this.onerror)==null||l.call(this,y),y}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Ze({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=yl(c);try{if(await vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new gl;(n=this.onerror)==null||n.call(this,_);return}}catch(g){(o=this.onerror)==null||o.call(this,g);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const g=new Ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,g);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Io).getReader(),f=async()=>{var g,_,y,w;try{for(;;){const{done:v,value:m}=await p.read();if(v)return;const{event:S,data:k,id:T}=m;if(T&&(this.lastInboundEventId=T),S==="message")try{const b=ea.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,b)}catch(b){const x=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:b});(_=this.onerror)==null||_.call(this,x)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(y=this.onerror)==null||y.call(this,v),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,f()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function i7(e){switch(e.type){case"sse":return new s7(e);case"http":return new a7(e);default:throw new Ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function l7(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var c7="1.0.0";function f_({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function u7(e){const t=new d7(e);return await t.init(),t}var d7=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=c7,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},l7(e)?this.transport=e:this.transport=i7(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new Ze({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Lo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:f$});if(e===void 0)throw new Ze({message:"Server sent invalid initialize result"});if(!c$.includes(e.protocolVersion))throw new Ze({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ze({message:"Server does not support prompts"});break;default:throw new Ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new Ze({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const h=new Ze({message:"Failed to parse server response",cause:u});o(h)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:m$,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:v$,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:y$,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:b$,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:w$,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:C$,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:I$,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const h=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,f=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,g=async(y,w)=>{var v;(v=w?.abortSignal)==null||v.throwIfAborted();const m=await p.callTool({name:s,args:y,options:w});return f!=null?p.extractStructuredContent(m,f,s):m},_=t==="automatic"?wg({description:i,title:h,inputSchema:Ao({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:f_}):{description:i,title:h,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:f_};o[s]={..._,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await cr({value:e.structuredContent,schema:Qn(t)});if(!n.success)throw new Ze({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await ur({text:n.text,schema:t});if(!o.success)throw new Ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new Ze({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==n_)throw new Ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=n_.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=x$.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Ze({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new Ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Bd=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:oe([d(),j()]).nullish()})}),xr=En({errorSchema:Bd,errorToMessage:e=>e.error.message});function h_(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function m_(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function p7({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,h;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${Oo(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new qr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Oo(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Oo(i.data),format:"mp3"}};default:throw new qr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new qr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(h=i.filename)!=null?h:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Oo(i.data)}`}}}else throw new qr({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function Jd({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function g_(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var f7=Ce(()=>Te(C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({message:C({role:$("assistant").nullish(),content:d().nullish(),tool_calls:q(C({id:d().nullish(),type:$("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:q(C({type:$("url_citation"),url_citation:C({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}),index:j(),logprobs:C({content:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),h7=Ce(()=>Te(oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:we(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(C({index:j(),id:d().nullish(),type:$("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(C({type:$("url_citation"),url_citation:C({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:j()})),usage:C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Bd]))),m7=Ce(()=>Te(C({logitBias:ye(Xh(),j()).optional(),logprobs:oe([me(),j()]).optional(),parallelToolCalls:me().optional(),user:d().optional(),reasoningEffort:we(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:me().optional(),metadata:ye(d().max(64),d().max(512)).optional(),prediction:ye(d(),bt()).optional(),serviceTier:we(["auto","flex","priority","default"]).optional(),strictJsonSchema:me().optional(),textVerbosity:we(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:we(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:we(["system","developer","remove"]).optional(),forceReasoning:me().optional()})));function g7({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new qr({functionality:`tool choice type: ${s}`})}}}var y7=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:p}){var f,g,_,y,w;const v=[],m=(f=await tn({provider:"openai",providerOptions:p,schema:m7}))!=null?f:{},S=h_(this.modelId),k=(g=m.forceReasoning)!=null?g:S.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:T,warnings:b}=p7({prompt:e,systemMessageMode:(_=m.systemMessageMode)!=null?_:k?"developer":S.systemMessageMode});v.push(...b);const x=(y=m.strictJsonSchema)!=null?y:!0,I={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs=="number"?!0:void 0,top_logprobs:typeof m.logprobs=="number"?m.logprobs:typeof m.logprobs=="boolean"&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:x,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,prompt_cache_retention:m.promptCacheRetention,safety_identifier:m.safetyIdentifier,messages:T};k?((m.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),m.serviceTier==="flex"&&!S.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),m.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:L,toolChoice:O,toolWarnings:A}=g7({tools:u,toolChoice:h});return{args:{...I,tools:L,tool_choice:O},warnings:[...v,...A]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:h,rawValue:p}=await Jt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:l,failedResponseHandler:xr,successfulResponseHandler:dr(f7),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=h.choices[0],g=[],_=f.message.content;_!=null&&_.length>0&&g.push({type:"text",text:_});for(const v of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:Ut(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:Ut(),url:v.url_citation.url,title:v.url_citation.title});const y=(o=h.usage)==null?void 0:o.completion_tokens_details;(s=h.usage)==null||s.prompt_tokens_details;const w={openai:{}};return y?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),((a=f.logprobs)==null?void 0:a.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:g_(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:m_(h.usage),request:{body:l},response:{...Jd(h),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Jt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:n,failedResponseHandler:xr,successfulResponseHandler:tl(h7),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var g,_,y,w,v,m,S,k,T,b,x,I,L,O,A,N,U;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const G=p.value;if("error"in G){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:G.error});return}if(!c){const re=Jd(G);Object.values(re).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Jd(G)}))}G.usage!=null&&(l=G.usage,((g=G.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(_=G.usage.completion_tokens_details)==null?void 0:_.accepted_prediction_tokens),((y=G.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=G.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const J=G.choices[0];if(J?.finish_reason!=null&&(i={unified:g_(J.finish_reason),raw:J.finish_reason}),((v=J?.logprobs)==null?void 0:v.content)!=null&&(h.openai.logprobs=J.logprobs.content),J?.delta==null)return;const ue=J.delta;if(ue.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:ue.content})),ue.tool_calls!=null)for(const re of ue.tool_calls){const ge=re.index;if(a[ge]==null){if(re.type!=="function")throw new ad({data:re,message:"Expected 'function' type."});if(re.id==null)throw new ad({data:re,message:"Expected 'id' to be a string."});if(((m=re.function)==null?void 0:m.name)==null)throw new ad({data:re,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),a[ge]={id:re.id,type:"function",function:{name:re.function.name,arguments:(S=re.function.arguments)!=null?S:""},hasFinished:!1};const R=a[ge];((k=R.function)==null?void 0:k.name)!=null&&((T=R.function)==null?void 0:T.arguments)!=null&&(R.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),gg(R.function.arguments)&&(f.enqueue({type:"tool-input-end",id:R.id}),f.enqueue({type:"tool-call",toolCallId:(b=R.id)!=null?b:Ut(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const V=a[ge];V.hasFinished||(((x=re.function)==null?void 0:x.arguments)!=null&&(V.function.arguments+=(L=(I=re.function)==null?void 0:I.arguments)!=null?L:""),f.enqueue({type:"tool-input-delta",id:V.id,delta:(O=re.function.arguments)!=null?O:""}),((A=V.function)==null?void 0:A.name)!=null&&((N=V.function)==null?void 0:N.arguments)!=null&&gg(V.function.arguments)&&(f.enqueue({type:"tool-input-end",id:V.id}),f.enqueue({type:"tool-call",toolCallId:(U=V.id)!=null?U:Ut(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}if(ue.annotations!=null)for(const re of ue.annotations)f.enqueue({type:"source",sourceType:"url",id:Ut(),url:re.url_citation.url,title:re.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:m_(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function y_(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function v7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
586
+
587
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Wn({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
582
588
  ${a}
583
589
 
584
- `;break}case"assistant":{const a=o.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Rr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
590
+ `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new qr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
585
591
  ${a}
586
592
 
587
- `;break}case"tool":throw new Rr({functionality:"tool messages"});default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
593
+ `;break}case"tool":throw new qr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
588
594
  `,{prompt:n,stopSequences:[`
589
- ${e}:`]}}function J1({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function G1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var nI=_t(()=>Le(C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({text:m(),finish_reason:m(),logprobs:C({tokens:M(m()),token_logprobs:M(N()),top_logprobs:M(be(m(),N())).nullish()}).nullish()})),usage:C({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}))),sI=_t(()=>Le(ie([C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({text:m(),finish_reason:m().nullish(),index:N(),logprobs:C({tokens:M(m()),token_logprobs:M(N()),top_logprobs:M(be(m(),N())).nullish()}).nullish()})),usage:C({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}),ld]))),W1=_t(()=>Le(C({echo:me().optional(),logitBias:be(m(),N()).optional(),suffix:m().optional(),user:m().optional(),logprobs:ie([me(),N()]).optional()}))),oI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,tools:l,toolChoice:u,seed:p,providerOptions:h}){const d=[],f={...await Xr({provider:"openai",providerOptions:h,schema:W1}),...await Xr({provider:this.providerOptionsName,providerOptions:h,schema:W1})};s!=null&&d.push({type:"unsupported-setting",setting:"topK"}),l?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),c!=null&&c.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:g}=rI({prompt:t}),w=[...g??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,seed:p,prompt:v,stop:w.length>0?w:void 0},warnings:d}}async doGenerate(t){var e,r,n;const{args:s,warnings:o}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:c}=await Pr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:s,failedResponseHandler:gr,successfulResponseHandler:ls(nI),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=i.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:G1(l.finish_reason),request:{body:s},response:{...J1(i),headers:a,body:c},providerMetadata:u,warnings:o}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Pr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:od(sI),abortSignal:t.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:o.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,p){if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",p.enqueue({type:"error",error:h.error});return}l&&(l=!1,p.enqueue({type:"response-metadata",...J1(h)}),p.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(c.inputTokens=h.usage.prompt_tokens,c.outputTokens=h.usage.completion_tokens,c.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=G1(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&p.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){l||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:c})}})),request:{body:n},response:{headers:s}}}},aI=_t(()=>Le(C({dimensions:N().optional(),user:m().optional()}))),iI=_t(()=>Le(C({data:M(C({embedding:M(N())})),usage:C({prompt_tokens:N()}).nullish()}))),cI=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new I7({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Xr({provider:"openai",providerOptions:n,schema:aI}))!=null?s:{},{responseHeaders:a,value:i,rawValue:c}=await Pr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:mr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:gr,successfulResponseHandler:ls(iI),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(l=>l.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:c}}}},lI=_t(()=>Le(C({created:N().nullish(),data:M(C({b64_json:m(),revised_prompt:m().nullish()})),background:m().nullish(),output_format:m().nullish(),size:m().nullish(),quality:m().nullish(),usage:C({input_tokens:N().nullish(),output_tokens:N().nullish(),total_tokens:N().nullish(),input_tokens_details:C({image_tokens:N().nullish(),text_tokens:N().nullish()}).nullish()}).nullish()}))),uI={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},dI=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),pI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=uI[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c,l,u,p;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(l=(c=this.config._internal)==null?void 0:c.currentDate)==null?void 0:l.call(c))!=null?u:new Date,{value:f,responseHeaders:v}=await Pr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:mr(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=o.openai)!=null?p:{},...dI.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:gr,successfulResponseHandler:ls(lI),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(g=>g.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:f.data.map(g=>({...g.revised_prompt?{revisedPrompt:g.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},fI=dt(()=>Le(C({code:m().nullish(),containerId:m()}))),hI=dt(()=>Le(C({outputs:M(Xe("type",[C({type:L("logs"),logs:m()}),C({type:L("image"),url:m()})])).nullish()}))),mI=dt(()=>Le(C({container:ie([m(),C({fileIds:M(m()).optional()})]).optional()}))),gI=cs({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:fI,outputSchema:hI}),yI=(t={})=>gI(t),K1=C({key:m(),type:xe(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ie([m(),N(),me(),M(m())])}),Y1=C({type:xe(["and","or"]),filters:M(ie([K1,oh(()=>Y1)]))}),_I=dt(()=>Le(C({vectorStoreIds:M(m()),maxNumResults:N().optional(),ranking:C({ranker:m().optional(),scoreThreshold:N().optional()}).optional(),filters:ie([K1,Y1]).optional()}))),vI=dt(()=>Le(C({queries:M(m()),results:M(C({attributes:be(m(),Pe()),fileId:m(),filename:m(),score:N(),text:m()})).nullable()}))),wI=cs({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:vI}),bI=dt(()=>Le(C({background:xe(["auto","opaque","transparent"]).optional(),inputFidelity:xe(["low","high"]).optional(),inputImageMask:C({fileId:m().optional(),imageUrl:m().optional()}).optional(),model:m().optional(),moderation:xe(["auto"]).optional(),outputCompression:N().int().min(0).max(100).optional(),outputFormat:xe(["png","jpeg","webp"]).optional(),partialImages:N().int().min(0).max(3).optional(),quality:xe(["auto","low","medium","high"]).optional(),size:xe(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),kI=dt(()=>Le(C({}))),SI=dt(()=>Le(C({result:m()}))),TI=cs({id:"openai.image_generation",name:"image_generation",inputSchema:kI,outputSchema:SI}),CI=(t={})=>TI(t),Q1=dt(()=>Le(C({action:C({type:L("exec"),command:M(m()),timeoutMs:N().optional(),user:m().optional(),workingDirectory:m().optional(),env:be(m(),m()).optional()})}))),X1=dt(()=>Le(C({output:m()}))),$I=cs({id:"openai.local_shell",name:"local_shell",inputSchema:Q1,outputSchema:X1}),EI=dt(()=>Le(C({externalWebAccess:me().optional(),filters:C({allowedDomains:M(m()).optional()}).optional(),searchContextSize:xe(["low","medium","high"]).optional(),userLocation:C({type:L("approximate"),country:m().optional(),city:m().optional(),region:m().optional(),timezone:m().optional()}).optional()}))),xI=dt(()=>Le(C({}))),II=dt(()=>Le(C({action:Xe("type",[C({type:L("search"),query:m().optional()}),C({type:L("openPage"),url:m().nullish()}),C({type:L("findInPage"),url:m().nullish(),pattern:m().nullish()})]),sources:M(Xe("type",[C({type:L("url"),url:m()}),C({type:L("api"),name:m()})])).optional()}))),RI=cs({id:"openai.web_search",name:"web_search",inputSchema:xI,outputSchema:II}),PI=(t={})=>RI(t),OI=dt(()=>Le(C({searchContextSize:xe(["low","medium","high"]).optional(),userLocation:C({type:L("approximate"),country:m().optional(),city:m().optional(),region:m().optional(),timezone:m().optional()}).optional()}))),AI=dt(()=>Le(C({}))),MI=dt(()=>Le(C({action:Xe("type",[C({type:L("search"),query:m().optional()}),C({type:L("openPage"),url:m().nullish()}),C({type:L("findInPage"),url:m().nullish(),pattern:m().nullish()})])}))),NI=cs({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:AI,outputSchema:MI}),LI={codeInterpreter:yI,fileSearch:wI,imageGeneration:CI,localShell:$I,webSearchPreview:NI,webSearch:PI};function e_(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function jI({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:s=!1}){var o,a,i,c;const l=[],u=[];for(const{role:p,content:h}of t)switch(p){case"system":{switch(e){case"system":{l.push({role:"system",content:h});break}case"developer":{l.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{l.push({role:"user",content:h.map((d,f)=>{var v,g,w;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const y=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{image_url:`data:${y};base64,${us(d.data)}`},detail:(g=(v=d.providerOptions)==null?void 0:v.openai)==null?void 0:g.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{filename:(w=d.filename)!=null?w:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${us(d.data)}`}};throw new Rr({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},f={};for(const v of h)switch(v.type){case"text":{const g=(a=(o=v.providerOptions)==null?void 0:o.openai)==null?void 0:a.itemId;if(n&&g!=null){l.push({type:"item_reference",id:g});break}l.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:g});break}case"tool-call":{if(f[v.toolCallId]=v,v.providerExecuted)break;const g=(c=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:c.itemId;if(n&&g!=null){l.push({type:"item_reference",id:g});break}if(s&&v.toolName==="local_shell"){const w=await Qr({value:v.input,schema:Q1});l.push({type:"local_shell_call",call_id:v.toolCallId,id:g,action:{type:"exec",command:w.action.command,timeout_ms:w.action.timeoutMs,user:w.action.user,working_directory:w.action.workingDirectory,env:w.action.env}});break}l.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:g});break}case"tool-result":{n?l.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const g=await Xr({provider:"openai",providerOptions:v.providerOptions,schema:qI}),w=g?.itemId;if(w!=null){const y=d[w];if(n)y===void 0&&(l.push({type:"item_reference",id:w}),d[w]={type:"reasoning",id:w,summary:[]});else{const _=[];v.text.length>0?_.push({type:"summary_text",text:v.text}):y!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),y===void 0?(d[w]={type:"reasoning",id:w,encrypted_content:g?.reasoningEncryptedContent,summary:_},l.push(d[w])):(y.summary.push(..._),g?.reasoningEncryptedContent!=null&&(y.encrypted_content=g.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const d of h){const f=d.output;if(s&&d.toolName==="local_shell"&&f.type==="json"){const g=await Qr({value:f.value,schema:X1});l.push({type:"local_shell_call_output",call_id:d.toolCallId,output:g.output});break}let v;switch(f.type){case"text":case"error-text":v=f.value;break;case"json":case"error-json":v=JSON.stringify(f.value);break;case"content":v=f.value.map(g=>{switch(g.type){case"text":return{type:"input_text",text:g.text};case"media":return g.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${g.mediaType};base64,${g.data}`}:{type:"input_file",filename:"data",file_data:`data:${g.mediaType};base64,${g.data}`}}});break}l.push({type:"function_call_output",call_id:d.toolCallId,output:v})}break}default:{const d=p;throw new Error(`Unsupported role: ${d}`)}}return{input:l,warnings:u}}var qI=C({itemId:m().nullish(),reasoningEncryptedContent:m().nullish()});function t_({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var zI=_t(()=>Le(ie([C({type:L("response.output_text.delta"),item_id:m(),delta:m(),logprobs:M(C({token:m(),logprob:N(),top_logprobs:M(C({token:m(),logprob:N()}))})).nullish()}),C({type:xe(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:m()}).nullish(),usage:C({input_tokens:N(),input_tokens_details:C({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:C({reasoning_tokens:N().nullish()}).nullish()}),service_tier:m().nullish()})}),C({type:L("response.created"),response:C({id:m(),created_at:N(),model:m(),service_tier:m().nullish()})}),C({type:L("response.output_item.added"),output_index:N(),item:Xe("type",[C({type:L("message"),id:m()}),C({type:L("reasoning"),id:m(),encrypted_content:m().nullish()}),C({type:L("function_call"),id:m(),call_id:m(),name:m(),arguments:m()}),C({type:L("web_search_call"),id:m(),status:m()}),C({type:L("computer_call"),id:m(),status:m()}),C({type:L("file_search_call"),id:m()}),C({type:L("image_generation_call"),id:m()}),C({type:L("code_interpreter_call"),id:m(),container_id:m(),code:m().nullable(),outputs:M(Xe("type",[C({type:L("logs"),logs:m()}),C({type:L("image"),url:m()})])).nullable(),status:m()})])}),C({type:L("response.output_item.done"),output_index:N(),item:Xe("type",[C({type:L("message"),id:m()}),C({type:L("reasoning"),id:m(),encrypted_content:m().nullish()}),C({type:L("function_call"),id:m(),call_id:m(),name:m(),arguments:m(),status:L("completed")}),C({type:L("code_interpreter_call"),id:m(),code:m().nullable(),container_id:m(),outputs:M(Xe("type",[C({type:L("logs"),logs:m()}),C({type:L("image"),url:m()})])).nullable()}),C({type:L("image_generation_call"),id:m(),result:m()}),C({type:L("web_search_call"),id:m(),status:m(),action:Xe("type",[C({type:L("search"),query:m().nullish(),sources:M(Xe("type",[C({type:L("url"),url:m()}),C({type:L("api"),name:m()})])).nullish()}),C({type:L("open_page"),url:m().nullish()}),C({type:L("find_in_page"),url:m().nullish(),pattern:m().nullish()})])}),C({type:L("file_search_call"),id:m(),queries:M(m()),results:M(C({attributes:be(m(),Pe()),file_id:m(),filename:m(),score:N(),text:m()})).nullish()}),C({type:L("local_shell_call"),id:m(),call_id:m(),action:C({type:L("exec"),command:M(m()),timeout_ms:N().optional(),user:m().optional(),working_directory:m().optional(),env:be(m(),m()).optional()})}),C({type:L("computer_call"),id:m(),status:L("completed")})])}),C({type:L("response.function_call_arguments.delta"),item_id:m(),output_index:N(),delta:m()}),C({type:L("response.image_generation_call.partial_image"),item_id:m(),output_index:N(),partial_image_b64:m()}),C({type:L("response.code_interpreter_call_code.delta"),item_id:m(),output_index:N(),delta:m()}),C({type:L("response.code_interpreter_call_code.done"),item_id:m(),output_index:N(),code:m()}),C({type:L("response.output_text.annotation.added"),annotation:Xe("type",[C({type:L("url_citation"),start_index:N(),end_index:N(),url:m(),title:m()}),C({type:L("file_citation"),file_id:m(),filename:m().nullish(),index:N().nullish(),start_index:N().nullish(),end_index:N().nullish(),quote:m().nullish()})])}),C({type:L("response.reasoning_summary_part.added"),item_id:m(),summary_index:N()}),C({type:L("response.reasoning_summary_text.delta"),item_id:m(),summary_index:N(),delta:m()}),C({type:L("response.reasoning_summary_part.done"),item_id:m(),summary_index:N()}),C({type:L("error"),sequence_number:N(),error:C({type:m(),code:m(),message:m(),param:m().nullish()})}),C({type:m()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),DI=_t(()=>Le(C({id:m().optional(),created_at:N().optional(),error:C({message:m(),type:m(),param:m().nullish(),code:m()}).nullish(),model:m().optional(),output:M(Xe("type",[C({type:L("message"),role:L("assistant"),id:m(),content:M(C({type:L("output_text"),text:m(),logprobs:M(C({token:m(),logprob:N(),top_logprobs:M(C({token:m(),logprob:N()}))})).nullish(),annotations:M(Xe("type",[C({type:L("url_citation"),start_index:N(),end_index:N(),url:m(),title:m()}),C({type:L("file_citation"),file_id:m(),filename:m().nullish(),index:N().nullish(),start_index:N().nullish(),end_index:N().nullish(),quote:m().nullish()}),C({type:L("container_file_citation"),container_id:m(),file_id:m(),filename:m().nullish(),start_index:N().nullish(),end_index:N().nullish(),index:N().nullish()}),C({type:L("file_path"),file_id:m(),index:N().nullish()})]))}))}),C({type:L("web_search_call"),id:m(),status:m(),action:Xe("type",[C({type:L("search"),query:m().nullish(),sources:M(Xe("type",[C({type:L("url"),url:m()}),C({type:L("api"),name:m()})])).nullish()}),C({type:L("open_page"),url:m().nullish()}),C({type:L("find_in_page"),url:m().nullish(),pattern:m().nullish()})])}),C({type:L("file_search_call"),id:m(),queries:M(m()),results:M(C({attributes:be(m(),ie([m(),N(),me()])),file_id:m(),filename:m(),score:N(),text:m()})).nullish()}),C({type:L("code_interpreter_call"),id:m(),code:m().nullable(),container_id:m(),outputs:M(Xe("type",[C({type:L("logs"),logs:m()}),C({type:L("image"),url:m()})])).nullable()}),C({type:L("image_generation_call"),id:m(),result:m()}),C({type:L("local_shell_call"),id:m(),call_id:m(),action:C({type:L("exec"),command:M(m()),timeout_ms:N().optional(),user:m().optional(),working_directory:m().optional(),env:be(m(),m()).optional()})}),C({type:L("function_call"),call_id:m(),name:m(),arguments:m(),id:m()}),C({type:L("computer_call"),id:m(),status:m().optional()}),C({type:L("reasoning"),id:m(),encrypted_content:m().nullish(),summary:M(C({type:L("summary_text"),text:m()}))})])).optional(),service_tier:m().nullish(),incomplete_details:C({reason:m()}).nullish(),usage:C({input_tokens:N(),input_tokens_details:C({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:C({reasoning_tokens:N().nullish()}).nullish()}).optional()}))),r_=20,UI=_t(()=>Le(C({conversation:m().nullish(),include:M(xe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:m().nullish(),logprobs:ie([me(),N().min(1).max(r_)]).optional(),maxToolCalls:N().nullish(),metadata:ht().nullish(),parallelToolCalls:me().nullish(),previousResponseId:m().nullish(),promptCacheKey:m().nullish(),promptCacheRetention:xe(["in_memory","24h"]).nullish(),reasoningEffort:m().nullish(),reasoningSummary:m().nullish(),safetyIdentifier:m().nullish(),serviceTier:xe(["auto","flex","priority","default"]).nullish(),store:me().nullish(),strictJsonSchema:me().nullish(),textVerbosity:xe(["low","medium","high"]).nullish(),truncation:xe(["auto","disabled"]).nullish(),user:m().nullish()})));async function ZI({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const a of t)switch(a.type){case"function":s.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await Qr({value:a.args,schema:_I});s.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{s.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await Qr({value:a.args,schema:OI});s.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await Qr({value:a.args,schema:EI});s.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await Qr({value:a.args,schema:mI});s.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await Qr({value:a.args,schema:bI});s.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{const a=o;throw new Rr({functionality:`tool choice type: ${a}`})}}}var FI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:s,presencePenalty:o,frequencyPenalty:a,seed:i,prompt:c,providerOptions:l,tools:u,toolChoice:p,responseFormat:h}){var d,f,v,g;const w=[],y=H1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),i!=null&&w.push({type:"unsupported-setting",setting:"seed"}),o!=null&&w.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&w.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported-setting",setting:"stopSequences"});const _=await Xr({provider:"openai",providerOptions:l,schema:UI});_?.conversation&&_?.previousResponseId&&w.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await jI({prompt:c,systemMessageMode:y.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=_?.store)!=null?d:!0,hasLocalShellTool:R("openai.local_shell")});w.push(...k);const S=(f=_?.strictJsonSchema)!=null?f:!1;let T=_?.include;function x(de){T==null?T=[de]:T.includes(de)||(T=[...T,de])}function R(de){return u?.find(te=>te.type==="provider-defined"&&te.id===de)!=null}const j=typeof _?.logprobs=="number"?_?.logprobs:_?.logprobs===!0?r_:void 0;j&&x("message.output_text.logprobs");const O=(v=u?.find(de=>de.type==="provider-defined"&&(de.id==="openai.web_search"||de.id==="openai.web_search_preview")))==null?void 0:v.name;O&&x("web_search_call.action.sources"),R("openai.code_interpreter")&&x("code_interpreter_call.outputs");const D=_?.store;D===!1&&y.isReasoningModel&&x("reasoning.encrypted_content");const U={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(h?.type==="json"||_?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(g=h.name)!=null?g:"response",description:h.description,schema:h.schema}:{type:"json_object"}},..._?.textVerbosity&&{verbosity:_.textVerbosity}}},conversation:_?.conversation,max_tool_calls:_?.maxToolCalls,metadata:_?.metadata,parallel_tool_calls:_?.parallelToolCalls,previous_response_id:_?.previousResponseId,store:D,user:_?.user,instructions:_?.instructions,service_tier:_?.serviceTier,include:T,prompt_cache_key:_?.promptCacheKey,prompt_cache_retention:_?.promptCacheRetention,safety_identifier:_?.safetyIdentifier,top_logprobs:j,truncation:_?.truncation,...y.isReasoningModel&&(_?.reasoningEffort!=null||_?.reasoningSummary!=null)&&{reasoning:{..._?.reasoningEffort!=null&&{effort:_.reasoningEffort},..._?.reasoningSummary!=null&&{summary:_.reasoningSummary}}}};y.isReasoningModel?_?.reasoningEffort==="none"&&y.supportsNonReasoningParameters||(U.temperature!=null&&(U.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),U.top_p!=null&&(U.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(_?.reasoningEffort!=null&&w.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),_?.reasoningSummary!=null&&w.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),_?.serviceTier==="flex"&&!y.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U.service_tier),_?.serviceTier==="priority"&&!y.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete U.service_tier);const{tools:V,toolChoice:ne,toolWarnings:fe}=await ZI({tools:u,toolChoice:p,strictJsonSchema:S});return{webSearchToolName:O,args:{...U,tools:V,tool_choice:ne},warnings:[...w,...fe],store:D}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f,v,g,w,y,_,b,k,S,T,x,R,j,O,D;const{args:U,warnings:V,webSearchToolName:ne}=await this.getArgs(t),fe=this.config.url({path:"/responses",modelId:this.modelId}),de=this.config.provider.replace(".responses",""),{responseHeaders:te,value:ye,rawValue:H}=await Pr({url:fe,headers:mr(this.config.headers(),t.headers),body:U,failedResponseHandler:gr,successfulResponseHandler:ls(DI),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ye.error)throw new Ut({message:ye.error.message,url:fe,requestBodyValues:U,statusCode:400,responseHeaders:te,responseBody:H,isRetryable:!1});const P=[],F=[];let q=!1;for(const $ of ye.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const B of $.summary)P.push({type:"reasoning",text:B.text,providerMetadata:{[de]:{itemId:$.id,reasoningEncryptedContent:(e=$.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[de]:{itemId:$.id}}});break}case"message":{for(const B of $.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&F.push(B.logprobs),P.push({type:"text",text:B.text,providerMetadata:{[de]:{itemId:$.id}}});for(const W of B.annotations)W.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?a:nr(),url:W.url,title:W.title}):W.type==="file_citation"?P.push({type:"source",sourceType:"document",id:(l=(c=(i=this.config).generateId)==null?void 0:c.call(i))!=null?l:nr(),mediaType:"text/plain",title:(p=(u=W.quote)!=null?u:W.filename)!=null?p:"Document",filename:(h=W.filename)!=null?h:W.file_id,...W.file_id?{providerMetadata:{[de]:{fileId:W.file_id}}}:{}}):W.type==="container_file_citation"?P.push({type:"source",sourceType:"document",id:(v=(f=(d=this.config).generateId)==null?void 0:f.call(d))!=null?v:nr(),mediaType:"text/plain",title:(w=(g=W.filename)!=null?g:W.file_id)!=null?w:"Document",filename:(y=W.filename)!=null?y:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,containerId:W.container_id,...W.index!=null?{index:W.index}:{}}}}):W.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(k=(b=(_=this.config).generateId)==null?void 0:b.call(_))!=null?k:nr(),mediaType:"application/octet-stream",title:W.file_id,filename:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,...W.index!=null?{index:W.index}:{}}}})}break}case"function_call":{q=!0,P.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[de]:{itemId:$.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:ne??"web_search",input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:ne??"web_search",result:s_($.action),providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(T=(S=$.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?T:null},providerExecuted:!0});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[de]:{...ye.id!=null?{responseId:ye.id}:{}}};F.length>0&&(E[de].logprobs=F),typeof ye.service_tier=="string"&&(E[de].serviceTier=ye.service_tier);const I=ye.usage;return{content:P,finishReason:t_({finishReason:(x=ye.incomplete_details)==null?void 0:x.reason,hasFunctionCall:q}),usage:{inputTokens:I.input_tokens,outputTokens:I.output_tokens,totalTokens:I.input_tokens+I.output_tokens,reasoningTokens:(j=(R=I.output_tokens_details)==null?void 0:R.reasoning_tokens)!=null?j:void 0,cachedInputTokens:(D=(O=I.input_tokens_details)==null?void 0:O.cached_tokens)!=null?D:void 0},request:{body:U},response:{id:ye.id,timestamp:new Date(ye.created_at*1e3),modelId:ye.model,headers:te,body:H},providerMetadata:E,warnings:V}}async doStream(t){const{args:e,warnings:r,webSearchToolName:n,store:s}=await this.getArgs(t),{responseHeaders:o,value:a}=await Pr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:gr,successfulResponseHandler:od(zI),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this,c=this.config.provider.replace(".responses","");let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},p=[];let h=null;const d={},f=[];let v=!1;const g={};let w;return{stream:a.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,_){var b,k,S,T,x,R,j,O,D,U,V,ne,fe,de,te,ye,H,P,F,q,E,I;if(t.includeRawChunks&&_.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){l="error",_.enqueue({type:"error",error:y.error});return}const $=y.value;if(n_($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},_.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),_.enqueue({type:"tool-input-end",id:$.item.id}),_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),_.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(f.splice(0,f.length),_.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id}}})):n_($)&&$.item.type==="reasoning"&&(g[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},_.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(HI($)){if($.item.type==="message")_.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id,...f.length>0&&{annotations:f}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,v=!0,_.enqueue({type:"tool-input-end",id:$.item.call_id}),_.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:s_($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,_.enqueue({type:"tool-input-end",id:$.item.id}),_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,_.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const B=g[$.item.id],W=Object.entries(B.summaryParts).filter(([_e,pe])=>pe==="active"||pe==="can-conclude").map(([_e])=>_e);for(const _e of W)_.enqueue({type:"reasoning-end",id:`${$.item.id}:${_e}`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(T=$.item.encrypted_content)!=null?T:null}}});delete g[$.item.id]}}else if(GI($)){const B=d[$.output_index];B!=null&&_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:$.delta})}else if(WI($)){const B=d[$.output_index];B!=null&&_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(KI($)){const B=d[$.output_index];B!=null&&(_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),_.enqueue({type:"tool-input-end",id:B.toolCallId}),_.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(JI($))h=$.response.id,_.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(VI($))_.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(R=(x=t.providerOptions)==null?void 0:x.openai)!=null&&R.logprobs&&$.logprobs&&p.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const B=g[$.item_id];B.summaryParts[$.summary_index]="active";for(const W of Object.keys(B.summaryParts))B.summaryParts[W]==="can-conclude"&&(_.enqueue({type:"reasoning-end",id:`${$.item_id}:${W}`,providerMetadata:{[c]:{itemId:$.item_id}}}),B.summaryParts[W]="concluded");_.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id,reasoningEncryptedContent:(O=(j=g[$.item_id])==null?void 0:j.encryptedContent)!=null?O:null}}})}}else $.type==="response.reasoning_summary_text.delta"?_.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[c]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(_.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id}}}),g[$.item_id].summaryParts[$.summary_index]="concluded"):g[$.item_id].summaryParts[$.summary_index]="can-conclude":BI($)?(l=t_({finishReason:(D=$.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:v}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(V=(U=$.response.usage.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?V:void 0,u.cachedInputTokens=(fe=(ne=$.response.usage.input_tokens_details)==null?void 0:ne.cached_tokens)!=null?fe:void 0,typeof $.response.service_tier=="string"&&(w=$.response.service_tier)):YI($)?(f.push($.annotation),$.annotation.type==="url_citation"?_.enqueue({type:"source",sourceType:"url",id:(ye=(te=(de=i.config).generateId)==null?void 0:te.call(de))!=null?ye:nr(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&_.enqueue({type:"source",sourceType:"document",id:(F=(P=(H=i.config).generateId)==null?void 0:P.call(H))!=null?F:nr(),mediaType:"text/plain",title:(E=(q=$.annotation.quote)!=null?q:$.annotation.filename)!=null?E:"Document",filename:(I=$.annotation.filename)!=null?I:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[c]:{fileId:$.annotation.file_id}}}:{}})):QI($)&&_.enqueue({type:"error",error:$})},flush(y){const _={[c]:{responseId:h}};p.length>0&&(_[c].logprobs=p),w!==void 0&&(_[c].serviceTier=w),y.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:_})}})),request:{body:e},response:{headers:o}}}};function VI(t){return t.type==="response.output_text.delta"}function HI(t){return t.type==="response.output_item.done"}function BI(t){return t.type==="response.completed"||t.type==="response.incomplete"}function JI(t){return t.type==="response.created"}function GI(t){return t.type==="response.function_call_arguments.delta"}function WI(t){return t.type==="response.code_interpreter_call_code.delta"}function KI(t){return t.type==="response.code_interpreter_call_code.done"}function n_(t){return t.type==="response.output_item.added"}function YI(t){return t.type==="response.output_text.annotation.added"}function QI(t){return t.type==="error"}function s_(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var XI=_t(()=>Le(C({instructions:m().nullish(),speed:N().min(.25).max(4).default(1).nullish()}))),eR=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:s,language:o,providerOptions:a}){const i=[],c=await Xr({provider:"openai",providerOptions:a,schema:XI}),l={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?l.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const u={};for(const p in u){const h=u[p];h!==void 0&&(l[p]=h)}}return o&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:l,warnings:i}}async doGenerate(t){var e,r,n;const s=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:o,warnings:a}=await this.getArgs(t),{value:i,responseHeaders:c,rawValue:l}=await Pr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:o,failedResponseHandler:gr,successfulResponseHandler:X7(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:c,body:l}}}},tR=_t(()=>Le(C({text:m(),language:m().nullish(),duration:N().nullish(),words:M(C({word:m(),start:N(),end:N()})).nullish(),segments:M(C({id:N(),seek:N(),start:N(),end:N(),text:m(),tokens:M(N()),temperature:N(),avg_logprob:N(),compression_ratio:N(),no_speech_prob:N()})).nullish()}))),rR=_t(()=>Le(C({include:M(m()).optional(),language:m().optional(),prompt:m().optional(),temperature:N().min(0).max(1).default(0).optional(),timestampGranularities:M(xe(["word","segment"])).default(["segment"]).optional()}))),o_={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},nR=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const n=[],s=await Xr({provider:"openai",providerOptions:r,schema:rR}),o=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([Jx(t)]);o.append("model",this.modelId);const i=D7(e);if(o.append("file",new File([a],"audio",{type:e}),`audio.${i}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[l,u]of Object.entries(c))if(u!=null)if(Array.isArray(u))for(const p of u)o.append(`${l}[]`,String(p));else o.append(l,String(u))}return{formData:o,warnings:n}}async doGenerate(t){var e,r,n,s,o,a,i,c;const l=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:p}=await this.getArgs(t),{value:h,responseHeaders:d,rawValue:f}=await Y7({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),formData:u,failedResponseHandler:gr,successfulResponseHandler:ls(tR),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=h.language!=null&&h.language in o_?o_[h.language]:void 0;return{text:h.text,segments:(i=(a=(s=h.segments)==null?void 0:s.map(g=>({text:g.text,startSecond:g.start,endSecond:g.end})))!=null?a:(o=h.words)==null?void 0:o.map(g=>({text:g.word,startSecond:g.start,endSecond:g.end})))!=null?i:[],language:v,durationInSeconds:(c=h.duration)!=null?c:void 0,warnings:p,response:{timestamp:l,modelId:this.modelId,headers:d,body:f}}}},sR="2.0.89";function a_(t={}){var e,r;const n=(e=Wx(z7({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",s=(r=t.name)!=null?r:"openai",o=()=>A1({Authorization:`Bearer ${q7({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${sR}`),a=v=>new tI(v,{provider:`${s}.chat`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),i=v=>new oI(v,{provider:`${s}.completion`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),c=v=>new cI(v,{provider:`${s}.embedding`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),l=v=>new pI(v,{provider:`${s}.image`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),u=v=>new nR(v,{provider:`${s}.transcription`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),p=v=>new eR(v,{provider:`${s}.speech`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch}),h=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(v)},d=v=>new FI(v,{provider:`${s}.responses`,url:({path:g})=>`${n}${g}`,headers:o,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(v){return h(v)};return f.languageModel=h,f.chat=a,f.completion=i,f.responses=d,f.embedding=c,f.textEmbedding=c,f.textEmbeddingModel=c,f.image=l,f.imageModel=l,f.transcription=u,f.transcriptionModel=u,f.speech=p,f.speechModel=p,f.tools=LI,f}a_();function Eo(t){var e,r;return(r=(e=t?.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function oR(t){const e=[];for(const{role:r,content:n,...s}of t){const o=Eo({...s});switch(r){case"system":{e.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){e.push({role:"user",content:n[0].text,...Eo(n[0])});break}e.push({role:"user",content:n.map(a=>{const i=Eo(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const c=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${c};base64,${lC(a.data)}`},...i}}else throw new e2({functionality:`file part media type ${a.mediaType}`})}}),...o});break}case"assistant":{let a="";const i=[];for(const c of n){const l=Eo(c);switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)},...l});break}}}e.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...o});break}case"tool":{for(const a of n){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}const l=Eo(a);e.push({role:"tool",tool_call_id:a.toolCallId,content:c,...l})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return e}function i_({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function c_(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var dd=C({user:m().optional(),reasoningEffort:m().optional(),textVerbosity:m().optional()}),aR=C({error:C({message:m(),type:m().nullish(),param:ht().nullish(),code:ie([m(),N()]).nullish()})}),iR={errorSchema:aR,errorToMessage:t=>t.error.message};function cR({tools:t,toolChoice:e}){t=t?.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of t)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const o=s;throw new e2({functionality:`tool choice type: ${o}`})}}}var lR=class{constructor(t,e){this.specificationVersion="v2";var r,n;this.modelId=t,this.config=e;const s=(r=e.errorStructure)!=null?r:iR;this.chunkSchema=dR(s.errorSchema),this.failedResponseHandler=bn(s),this.supportsStructuredOutputs=(n=e.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,providerOptions:i,stopSequences:c,responseFormat:l,seed:u,toolChoice:p,tools:h}){var d,f,v,g;const w=[],y=Object.assign((d=await i2({provider:"openai-compatible",providerOptions:i,schema:dd}))!=null?d:{},(f=await i2({provider:this.providerOptionsName,providerOptions:i,schema:dd}))!=null?f:{});s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:_,toolChoice:b,toolWarnings:k}=cR({tools:h,toolChoice:p});return{args:{model:this.modelId,user:y.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:l?.type==="json"?this.supportsStructuredOutputs===!0&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,name:(v=l.name)!=null?v:"response",description:l.description}}:{type:"json_object"}:void 0,stop:c,seed:u,...Object.fromEntries(Object.entries((g=i?.[this.providerOptionsName])!=null?g:{}).filter(([S])=>!Object.keys(dd.shape).includes(S))),reasoning_effort:y.reasoningEffort,verbosity:y.textVerbosity,messages:oR(t),tools:_,tool_choice:b},warnings:[...w,...k]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f,v,g,w;const{args:y,warnings:_}=await this.getArgs({...t}),b=JSON.stringify(y),{responseHeaders:k,value:S,rawValue:T}=await ts({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Xn(this.config.headers(),t.headers),body:y,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rs(uR),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=S.choices[0],R=[],j=x.message.content;j!=null&&j.length>0&&R.push({type:"text",text:j});const O=(e=x.message.reasoning_content)!=null?e:x.message.reasoning;if(O!=null&&O.length>0&&R.push({type:"reasoning",text:O}),x.message.tool_calls!=null)for(const V of x.message.tool_calls)R.push({type:"tool-call",toolCallId:(r=V.id)!=null?r:po(),toolName:V.function.name,input:V.function.arguments});const D={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:T}))},U=(o=S.usage)==null?void 0:o.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:R,finishReason:c_(x.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(l=(c=S.usage)==null?void 0:c.completion_tokens)!=null?l:void 0,totalTokens:(p=(u=S.usage)==null?void 0:u.total_tokens)!=null?p:void 0,reasoningTokens:(f=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(w=(g=(v=S.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?w:void 0},providerMetadata:D,request:{body:b},response:{...i_(S),headers:k,body:T},warnings:_}}async doStream(t){var e;const{args:r,warnings:n}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:a,value:i}=await ts({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Xn(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:l2(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let l="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let p=!0;const h=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,g){var w,y,_,b,k,S,T,x,R,j,O,D,U;if(t.includeRawChunks&&g.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){l="error",g.enqueue({type:"error",error:v.error});return}const V=v.value;if(o?.processChunk(v.rawValue),"error"in V){l="error",g.enqueue({type:"error",error:V.error.message});return}if(p&&(p=!1,g.enqueue({type:"response-metadata",...i_(V)})),V.usage!=null){const{prompt_tokens:te,completion_tokens:ye,total_tokens:H,prompt_tokens_details:P,completion_tokens_details:F}=V.usage;u.promptTokens=te??void 0,u.completionTokens=ye??void 0,u.totalTokens=H??void 0,F?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=F?.reasoning_tokens),F?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=F?.rejected_prediction_tokens),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const ne=V.choices[0];if(ne?.finish_reason!=null&&(l=c_(ne.finish_reason)),ne?.delta==null)return;const fe=ne.delta,de=(w=fe.reasoning_content)!=null?w:fe.reasoning;if(de&&(d||(g.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),g.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),fe.content&&(f||(g.enqueue({type:"text-start",id:"txt-0"}),f=!0),g.enqueue({type:"text-delta",id:"txt-0",delta:fe.content})),fe.tool_calls!=null)for(const te of fe.tool_calls){const ye=te.index;if(c[ye]==null){if(te.id==null)throw new jm({data:te,message:"Expected 'id' to be a string."});if(((y=te.function)==null?void 0:y.name)==null)throw new jm({data:te,message:"Expected 'function.name' to be a string."});g.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),c[ye]={id:te.id,type:"function",function:{name:te.function.name,arguments:(_=te.function.arguments)!=null?_:""},hasFinished:!1};const P=c[ye];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&g.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),a2(P.function.arguments)&&(g.enqueue({type:"tool-input-end",id:P.id}),g.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:po(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const H=c[ye];H.hasFinished||(((T=te.function)==null?void 0:T.arguments)!=null&&(H.function.arguments+=(R=(x=te.function)==null?void 0:x.arguments)!=null?R:""),g.enqueue({type:"tool-input-delta",id:H.id,delta:(j=te.function.arguments)!=null?j:""}),((O=H.function)==null?void 0:O.name)!=null&&((D=H.function)==null?void 0:D.arguments)!=null&&a2(H.function.arguments)&&(g.enqueue({type:"tool-input-end",id:H.id}),g.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:po(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(v){var g,w,y,_,b,k;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&v.enqueue({type:"text-end",id:"txt-0"});for(const T of c.filter(x=>!x.hasFinished))v.enqueue({type:"tool-input-end",id:T.id}),v.enqueue({type:"tool-call",toolCallId:(g=T.id)!=null?g:po(),toolName:T.function.name,input:T.function.arguments});const S={[h]:{},...o?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:l,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(y=u.completionTokens)!=null?y:void 0,totalTokens:(_=u.totalTokens)!=null?_:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:s},response:{headers:a}}}},l_=C({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:C({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish(),uR=C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({message:C({role:L("assistant").nullish(),content:m().nullish(),reasoning_content:m().nullish(),reasoning:m().nullish(),tool_calls:M(C({id:m().nullish(),function:C({name:m(),arguments:m()})})).nullish()}),finish_reason:m().nullish()})),usage:l_}),dR=t=>ie([C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({delta:C({role:xe(["assistant"]).nullish(),content:m().nullish(),reasoning_content:m().nullish(),reasoning:m().nullish(),tool_calls:M(C({index:N(),id:m().nullish(),function:C({name:m().nullish(),arguments:m().nullish()})})).nullish()}).nullish(),finish_reason:m().nullish()})),usage:l_}),t]);C({echo:me().optional(),logitBias:be(m(),N()).optional(),suffix:m().optional(),user:m().optional()});var pR=C({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()});C({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(C({text:m(),finish_reason:m()})),usage:pR.nullish()}),C({dimensions:N().optional(),user:m().optional()}),C({data:M(C({embedding:M(N())})),usage:C({prompt_tokens:N()}).nullish(),providerMetadata:be(m(),be(m(),ht())).optional()}),C({data:M(C({b64_json:m()}))});var u_=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},fR={extractMetadata:async({parsedBody:t})=>{const e=await er({value:t,schema:hR});return!e.success||e.value.usage==null?void 0:u_(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,n;const s=await er({value:e,schema:mR});s.success&&((n=(r=s.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&s.value.usage&&(t=s.value.usage)},buildMetadata:()=>u_(t)}}},d_=C({prompt_cache_hit_tokens:N().nullish(),prompt_cache_miss_tokens:N().nullish()}),hR=C({usage:d_.nullish()}),mR=C({choices:M(C({finish_reason:m().nullish()})).nullish(),usage:d_.nullish()}),gR="1.0.30";function p_(t={}){var e;const r=g2((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),n=()=>Kr({Authorization:`Bearer ${sT({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${gR}`);class s extends lR{addJsonInstruction(c){var l;if(((l=c.responseFormat)==null?void 0:l.type)!=="json")return c;const h=[...Array.isArray(c.prompt)?c.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...c,prompt:h}}async doGenerate(c){return super.doGenerate(this.addJsonInstruction(c))}async doStream(c){return super.doStream(this.addJsonInstruction(c))}}const o=i=>new s(i,{provider:"deepseek.chat",url:({path:c})=>`${r}${c}`,headers:n,fetch:t.fetch,metadataExtractor:fR}),a=i=>o(i);return a.languageModel=o,a.chat=o,a.textEmbeddingModel=i=>{throw new Jm({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Jm({modelId:i,modelType:"imageModel"})},a}p_();const f_=async t=>{const e={};try{const r=await t.listTools();for(const{name:n,description:s,inputSchema:o}of r.tools){const a=async(i,c)=>t.callTool({name:n,arguments:i},{signal:c?.abortSignal});e[n]=c2({description:s,inputSchema:ho({...o,properties:o.properties??{},additionalProperties:!1}),execute:a})}return e}catch(r){throw r}};function yR(t){const e=Object.entries(t);if(e.length===0)return"";let r=`
595
+ ${t}:`]}}function v_({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function __(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var _7=Ce(()=>Te(C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d(),logprobs:C({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ye(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),w7=Ce(()=>Te(oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d().nullish(),index:j(),logprobs:C({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ye(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Bd]))),w_=Ce(()=>Te(C({echo:me().optional(),logitBias:ye(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([me(),j()]).optional()}))),b7=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:p}){const f=[],g={...await tn({provider:"openai",providerOptions:p,schema:w_}),...await tn({provider:this.providerOptionsName,providerOptions:p,schema:w_})};o!=null&&f.push({type:"unsupported",feature:"topK"}),c?.length&&f.push({type:"unsupported",feature:"tools"}),u!=null&&f.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:_,stopSequences:y}=v7({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:g?.logprobs===!0?0:g?.logprobs===!1?void 0:g?.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:h,prompt:_,stop:w.length>0?w:void 0},warnings:f}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await Jt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:r,failedResponseHandler:xr,successfulResponseHandler:dr(_7),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:y_(s.usage),finishReason:{unified:__(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...v_(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Jt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:n,failedResponseHandler:xr,successfulResponseHandler:tl(w7),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...v_(p)}),h.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(a={unified:__(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(i.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:y_(l)})}})),request:{body:n},response:{headers:o}}}},k7=Ce(()=>Te(C({dimensions:j().optional(),user:d().optional()}))),T7=Ce(()=>Te(C({data:q(C({embedding:q(j())})),usage:C({prompt_tokens:j()}).nullish()}))),C7=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new p5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await tn({provider:"openai",providerOptions:n,schema:k7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Jt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Nt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:xr,successfulResponseHandler:dr(T7),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},b_=Ce(()=>Te(C({created:j().nullish(),data:q(C({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:C({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:C({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),S7={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},I7=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function E7(e){return I7.some(t=>e.startsWith(t))}var x7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=S7[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,h,p,f,g,_,y,w,v,m,S;const k=[];s!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&k.push({type:"unsupported",feature:"seed"});const T=(p=(h=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:h.call(u))!=null?p:new Date;if(t!=null){const{value:I,responseHeaders:L}=await vg({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Nt(this.config.headers(),l),formData:_5({model:this.modelId,prompt:e,image:await Promise.all(t.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([Po(O.data)],{type:O.mediaType})],{type:O.mediaType}):sg(O.url))),mask:r!=null?await $7(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:xr,successfulResponseHandler:dr(b_),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map(O=>O.b64_json),warnings:k,usage:I.usage!=null?{inputTokens:(g=I.usage.input_tokens)!=null?g:void 0,outputTokens:(_=I.usage.output_tokens)!=null?_:void 0,totalTokens:(y=I.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:I.data.map((O,A)=>{var N,U,G,J,ue,re;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(N=I.created)!=null?N:void 0,size:(U=I.size)!=null?U:void 0,quality:(G=I.quality)!=null?G:void 0,background:(J=I.background)!=null?J:void 0,outputFormat:(ue=I.output_format)!=null?ue:void 0,...k_((re=I.usage)==null?void 0:re.input_tokens_details,A,I.data.length)}})}}}}const{value:b,responseHeaders:x}=await Jt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Nt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...E7(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:xr,successfulResponseHandler:dr(b_),abortSignal:c,fetch:this.config.fetch});return{images:b.data.map(I=>I.b64_json),warnings:k,usage:b.usage!=null?{inputTokens:(v=b.usage.input_tokens)!=null?v:void 0,outputTokens:(m=b.usage.output_tokens)!=null?m:void 0,totalTokens:(S=b.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:x},providerMetadata:{openai:{images:b.data.map((I,L)=>{var O,A,N,U,G,J;return{...I.revised_prompt?{revisedPrompt:I.revised_prompt}:{},created:(O=b.created)!=null?O:void 0,size:(A=b.size)!=null?A:void 0,quality:(N=b.quality)!=null?N:void 0,background:(U=b.background)!=null?U:void 0,outputFormat:(G=b.output_format)!=null?G:void 0,...k_((J=b.usage)==null?void 0:J.input_tokens_details,L,b.data.length)}})}}}}};function k_(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function $7(e){if(!e)return;if(e.type==="url")return sg(e.url);const t=e.data instanceof Uint8Array?e.data:Po(e.data);return new Blob([t],{type:e.mediaType})}var T_=Ce(()=>Te(C({callId:d(),operation:ze("type",[C({type:$("create_file"),path:d(),diff:d()}),C({type:$("delete_file"),path:d()}),C({type:$("update_file"),path:d(),diff:d()})])}))),C_=Ce(()=>Te(C({status:we(["completed","failed"]),output:d().optional()}))),R7=Ir({id:"openai.apply_patch",inputSchema:T_,outputSchema:C_}),P7=R7,M7=Ce(()=>Te(C({code:d().nullish(),containerId:d()}))),O7=Ce(()=>Te(C({outputs:q(ze("type",[C({type:$("logs"),logs:d()}),C({type:$("image"),url:d()})])).nullish()}))),N7=Ce(()=>Te(C({container:oe([d(),C({fileIds:q(d()).optional()})]).optional()}))),A7=Ir({id:"openai.code_interpreter",inputSchema:M7,outputSchema:O7}),q7=(e={})=>A7(e),S_=C({key:d(),type:we(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),me(),q(d())])}),I_=C({type:we(["and","or"]),filters:q(oe([S_,dc(()=>I_)]))}),L7=Ce(()=>Te(C({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:C({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([S_,I_]).optional()}))),j7=Ce(()=>Te(C({queries:q(d()),results:q(C({attributes:ye(d(),Me()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),D7=Ir({id:"openai.file_search",inputSchema:C({}),outputSchema:j7}),U7=Ce(()=>Te(C({background:we(["auto","opaque","transparent"]).optional(),inputFidelity:we(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:we(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:we(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:we(["auto","low","medium","high"]).optional(),size:we(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),z7=Ce(()=>Te(C({}))),Z7=Ce(()=>Te(C({result:d()}))),F7=Ir({id:"openai.image_generation",inputSchema:z7,outputSchema:Z7}),V7=(e={})=>F7(e),E_=Ce(()=>Te(C({action:C({type:$("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:ye(d(),d()).optional()})}))),x_=Ce(()=>Te(C({output:d()}))),H7=Ir({id:"openai.local_shell",inputSchema:E_,outputSchema:x_}),$_=Ce(()=>Te(C({action:C({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),Wd=Ce(()=>Te(C({output:q(C({stdout:d(),stderr:d(),outcome:ze("type",[C({type:$("timeout")}),C({type:$("exit"),exitCode:j()})])}))}))),B7=q(ze("type",[C({type:$("skillReference"),skillId:d(),version:d().optional()}),C({type:$("inline"),name:d(),description:d(),source:C({type:$("base64"),mediaType:$("application/zip"),data:d()})})])).optional(),J7=Ce(()=>Te(C({environment:oe([C({type:$("containerAuto"),fileIds:q(d()).optional(),memoryLimit:we(["1g","4g","16g","64g"]).optional(),networkPolicy:ze("type",[C({type:$("disabled")}),C({type:$("allowlist"),allowedDomains:q(d()),domainSecrets:q(C({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:B7}),C({type:$("containerReference"),containerId:d()}),C({type:$("local").optional(),skills:q(C({name:d(),description:d(),path:d()})).optional()})]).optional()}))),W7=Ir({id:"openai.shell",inputSchema:$_,outputSchema:Wd}),G7=Ce(()=>Te(C({externalWebAccess:me().optional(),filters:C({allowedDomains:q(d()).optional()}).optional(),searchContextSize:we(["low","medium","high"]).optional(),userLocation:C({type:$("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),K7=Ce(()=>Te(C({}))),Y7=Ce(()=>Te(C({action:ze("type",[C({type:$("search"),query:d().optional()}),C({type:$("openPage"),url:d().nullish()}),C({type:$("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(ze("type",[C({type:$("url"),url:d()}),C({type:$("api"),name:d()})])).optional()}))),Q7=Ir({id:"openai.web_search",inputSchema:K7,outputSchema:Y7}),X7=(e={})=>Q7(e),eR=Ce(()=>Te(C({searchContextSize:we(["low","medium","high"]).optional(),userLocation:C({type:$("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),tR=Ce(()=>Te(C({}))),rR=Ce(()=>Te(C({action:ze("type",[C({type:$("search"),query:d().optional()}),C({type:$("openPage"),url:d().nullish()}),C({type:$("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),nR=Ir({id:"openai.web_search_preview",inputSchema:tR,outputSchema:rR}),Gd=dc(()=>oe([d(),j(),me(),ki(),q(Gd),ye(d(),Gd)])),oR=Ce(()=>Te(C({serverLabel:d(),allowedTools:oe([q(d()),C({readOnly:me().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ye(d(),d()).optional(),requireApproval:oe([we(["always","never"]),C({never:C({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),sR=Ce(()=>Te(C({}))),aR=Ce(()=>Te(C({type:$("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),Gd]).optional()}))),iR=Ir({id:"openai.mcp",inputSchema:sR,outputSchema:aR}),lR=e=>iR(e),cR={applyPatch:P7,codeInterpreter:q7,fileSearch:D7,imageGeneration:V7,localShell:H7,shell:W7,webSearchPreview:nR,webSearch:X7,mcp:lR};function R_(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function P_(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function uR({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var u,h,p,f,g,_,y,w,v,m,S,k,T;const b=[],x=[],I=new Set;for(const{role:L,content:O}of e)switch(L){case"system":{switch(r){case"system":{b.push({role:"system",content:O});break}case"developer":{b.push({role:"developer",content:O});break}case"remove":{x.push({type:"other",message:"system messages are removed for this model"});break}default:{const A=r;throw new Error(`Unsupported system message mode: ${A}`)}}break}case"user":{b.push({role:"user",content:O.map((A,N)=>{var U,G,J;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const ue=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&P_(A.data,o)?{file_id:A.data}:{image_url:`data:${ue};base64,${Oo(A.data)}`},detail:(G=(U=A.providerOptions)==null?void 0:U[n])==null?void 0:G.imageDetail}}else{if(A.mediaType==="application/pdf")return A.data instanceof URL?{type:"input_file",file_url:A.data.toString()}:{type:"input_file",...typeof A.data=="string"&&P_(A.data,o)?{file_id:A.data}:{filename:(J=A.filename)!=null?J:`part-${N}.pdf`,file_data:`data:application/pdf;base64,${Oo(A.data)}`}};throw new qr({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const N of O)switch(N.type){case"text":{const U=(h=(u=N.providerOptions)==null?void 0:u[n])==null?void 0:h.itemId;if(a&&U!=null)break;if(s&&U!=null){b.push({type:"item_reference",id:U});break}b.push({role:"assistant",content:[{type:"output_text",text:N.text}],id:U});break}case"tool-call":{const U=(y=(f=(p=N.providerOptions)==null?void 0:p[n])==null?void 0:f.itemId)!=null?y:(_=(g=N.providerMetadata)==null?void 0:g[n])==null?void 0:_.itemId;if(a&&U!=null)break;if(N.providerExecuted){s&&U!=null&&b.push({type:"item_reference",id:U});break}if(s&&U!=null){b.push({type:"item_reference",id:U});break}const G=t.toProviderToolName(N.toolName);if(i&&G==="local_shell"){const J=await Pt({value:N.input,schema:E_});b.push({type:"local_shell_call",call_id:N.toolCallId,id:U,action:{type:"exec",command:J.action.command,timeout_ms:J.action.timeoutMs,user:J.action.user,working_directory:J.action.workingDirectory,env:J.action.env}});break}if(l&&G==="shell"){const J=await Pt({value:N.input,schema:$_});b.push({type:"shell_call",call_id:N.toolCallId,id:U,status:"completed",action:{commands:J.action.commands,timeout_ms:J.action.timeoutMs,max_output_length:J.action.maxOutputLength}});break}if(c&&G==="apply_patch"){const J=await Pt({value:N.input,schema:T_});b.push({type:"apply_patch_call",call_id:J.callId,id:U,status:"completed",operation:J.operation});break}b.push({type:"function_call",call_id:N.toolCallId,name:G,arguments:JSON.stringify(N.input),id:U});break}case"tool-result":{if(N.output.type==="execution-denied"||N.output.type==="json"&&typeof N.output.value=="object"&&N.output.value!=null&&"type"in N.output.value&&N.output.value.type==="execution-denied"||a)break;const U=t.toProviderToolName(N.toolName);if(l&&U==="shell"){if(N.output.type==="json"){const G=await Pt({value:N.output.value,schema:Wd});b.push({type:"shell_call_output",call_id:N.toolCallId,output:G.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))})}break}if(s){const G=(m=(v=(w=N.providerOptions)==null?void 0:w[n])==null?void 0:v.itemId)!=null?m:N.toolCallId;b.push({type:"item_reference",id:G})}else x.push({type:"other",message:`Results for OpenAI tool ${N.toolName} are not sent to the API when store is false`});break}case"reasoning":{const U=await tn({provider:n,providerOptions:N.providerOptions,schema:dR}),G=U?.itemId;if(a&&G!=null)break;if(G!=null){const J=A[G];if(s)J===void 0&&(b.push({type:"item_reference",id:G}),A[G]={type:"reasoning",id:G,summary:[]});else{const ue=[];N.text.length>0?ue.push({type:"summary_text",text:N.text}):J!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(N)}.`}),J===void 0?(A[G]={type:"reasoning",id:G,encrypted_content:U?.reasoningEncryptedContent,summary:ue},b.push(A[G])):(J.summary.push(...ue),U?.reasoningEncryptedContent!=null&&(J.encrypted_content=U.reasoningEncryptedContent))}}else x.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(N)}.`});break}}break}case"tool":{for(const A of O){if(A.type==="tool-approval-response"){const J=A;if(I.has(J.approvalId))continue;I.add(J.approvalId),s&&b.push({type:"item_reference",id:J.approvalId}),b.push({type:"mcp_approval_response",approval_request_id:J.approvalId,approve:J.approved});continue}const N=A.output;if(N.type==="execution-denied"&&((k=(S=N.providerOptions)==null?void 0:S.openai)==null?void 0:k.approvalId))continue;const U=t.toProviderToolName(A.toolName);if(i&&U==="local_shell"&&N.type==="json"){const J=await Pt({value:N.value,schema:x_});b.push({type:"local_shell_call_output",call_id:A.toolCallId,output:J.output});continue}if(l&&U==="shell"&&N.type==="json"){const J=await Pt({value:N.value,schema:Wd});b.push({type:"shell_call_output",call_id:A.toolCallId,output:J.output.map(ue=>({stdout:ue.stdout,stderr:ue.stderr,outcome:ue.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ue.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&N.type==="json"){const J=await Pt({value:N.value,schema:C_});b.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:J.status,output:J.output});continue}let G;switch(N.type){case"text":case"error-text":G=N.value;break;case"execution-denied":G=(T=N.reason)!=null?T:"Tool execution denied.";break;case"json":case"error-json":G=JSON.stringify(N.value);break;case"content":G=N.value.map(J=>{var ue;switch(J.type){case"text":return{type:"input_text",text:J.text};case"image-data":return{type:"input_image",image_url:`data:${J.mediaType};base64,${J.data}`};case"image-url":return{type:"input_image",image_url:J.url};case"file-data":return{type:"input_file",filename:(ue=J.filename)!=null?ue:"data",file_data:`data:${J.mediaType};base64,${J.data}`};default:{x.push({type:"other",message:`unsupported tool content part type: ${J.type}`});return}}}).filter(I5);break}b.push({type:"function_call_output",call_id:A.toolCallId,output:G})}break}default:{const A=L;throw new Error(`Unsupported role: ${A}`)}}return{input:b,warnings:x}}var dR=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function M_({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var pR=Ce(()=>Te(oe([C({type:$("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}),C({type:we(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:j(),input_tokens_details:C({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:C({reasoning_tokens:j().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:$("response.created"),response:C({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),C({type:$("response.output_item.added"),output_index:j(),item:ze("type",[C({type:$("message"),id:d()}),C({type:$("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:$("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:$("web_search_call"),id:d(),status:d()}),C({type:$("computer_call"),id:d(),status:d()}),C({type:$("file_search_call"),id:d()}),C({type:$("image_generation_call"),id:d()}),C({type:$("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(ze("type",[C({type:$("logs"),logs:d()}),C({type:$("image"),url:d()})])).nullable(),status:d()}),C({type:$("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),C({type:$("mcp_list_tools"),id:d()}),C({type:$("mcp_approval_request"),id:d()}),C({type:$("apply_patch_call"),id:d(),call_id:d(),status:we(["in_progress","completed"]),operation:ze("type",[C({type:$("create_file"),path:d(),diff:d()}),C({type:$("delete_file"),path:d()}),C({type:$("update_file"),path:d(),diff:d()})])}),C({type:$("shell_call"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:$("shell_call_output"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:ze("type",[C({type:$("timeout")}),C({type:$("exit"),exit_code:j()})])}))})])}),C({type:$("response.output_item.done"),output_index:j(),item:ze("type",[C({type:$("message"),id:d()}),C({type:$("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:$("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:$("completed")}),C({type:$("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(ze("type",[C({type:$("logs"),logs:d()}),C({type:$("image"),url:d()})])).nullable()}),C({type:$("image_generation_call"),id:d(),result:d()}),C({type:$("web_search_call"),id:d(),status:d(),action:ze("type",[C({type:$("search"),query:d().nullish(),sources:q(ze("type",[C({type:$("url"),url:d()}),C({type:$("api"),name:d()})])).nullish()}),C({type:$("open_page"),url:d().nullish()}),C({type:$("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:$("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),oe([d(),j(),me()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:$("local_shell_call"),id:d(),call_id:d(),action:C({type:$("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:$("computer_call"),id:d(),status:$("completed")}),C({type:$("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:$("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),Me()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:$("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:$("apply_patch_call"),id:d(),call_id:d(),status:we(["in_progress","completed"]),operation:ze("type",[C({type:$("create_file"),path:d(),diff:d()}),C({type:$("delete_file"),path:d()}),C({type:$("update_file"),path:d(),diff:d()})])}),C({type:$("shell_call"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:$("shell_call_output"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:ze("type",[C({type:$("timeout")}),C({type:$("exit"),exit_code:j()})])}))})])}),C({type:$("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:$("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),C({type:$("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:$("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),C({type:$("response.output_text.annotation.added"),annotation:ze("type",[C({type:$("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:$("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:$("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:$("file_path"),file_id:d(),index:j()})])}),C({type:$("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),C({type:$("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),C({type:$("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),C({type:$("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),C({type:$("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),C({type:$("error"),sequence_number:j(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),fR=Ce(()=>Te(C({id:d().optional(),created_at:j().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(ze("type",[C({type:$("message"),role:$("assistant"),id:d(),content:q(C({type:$("output_text"),text:d(),logprobs:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish(),annotations:q(ze("type",[C({type:$("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:$("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:$("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:$("file_path"),file_id:d(),index:j()})]))}))}),C({type:$("web_search_call"),id:d(),status:d(),action:ze("type",[C({type:$("search"),query:d().nullish(),sources:q(ze("type",[C({type:$("url"),url:d()}),C({type:$("api"),name:d()})])).nullish()}),C({type:$("open_page"),url:d().nullish()}),C({type:$("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:$("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),oe([d(),j(),me()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:$("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(ze("type",[C({type:$("logs"),logs:d()}),C({type:$("image"),url:d()})])).nullable()}),C({type:$("image_generation_call"),id:d(),result:d()}),C({type:$("local_shell_call"),id:d(),call_id:d(),action:C({type:$("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:$("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:$("computer_call"),id:d(),status:d().optional()}),C({type:$("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(C({type:$("summary_text"),text:d()}))}),C({type:$("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:$("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),Me()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:$("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:$("apply_patch_call"),id:d(),call_id:d(),status:we(["in_progress","completed"]),operation:ze("type",[C({type:$("create_file"),path:d(),diff:d()}),C({type:$("delete_file"),path:d()}),C({type:$("update_file"),path:d(),diff:d()})])}),C({type:$("shell_call"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:$("shell_call_output"),id:d(),call_id:d(),status:we(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:ze("type",[C({type:$("timeout")}),C({type:$("exit"),exit_code:j()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:j(),input_tokens_details:C({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:C({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),O_=20,N_=Ce(()=>Te(C({conversation:d().nullish(),include:q(we(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([me(),j().min(1).max(O_)]).optional(),maxToolCalls:j().nullish(),metadata:bt().nullish(),parallelToolCalls:me().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:we(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:we(["auto","flex","priority","default"]).nullish(),store:me().nullish(),strictJsonSchema:me().nullish(),textVerbosity:we(["low","medium","high"]).nullish(),truncation:we(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:we(["system","developer","remove"]).optional(),forceReasoning:me().optional()})));async function hR({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await Pt({value:s.args,schema:L7});n.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.shell":{const a=await Pt({value:s.args,schema:J7});n.push({type:"shell",...a.environment&&{environment:mR(a.environment)}});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await Pt({value:s.args,schema:eR});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await Pt({value:s.args,schema:G7});n.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await Pt({value:s.args,schema:N7});n.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await Pt({value:s.args,schema:U7});n.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await Pt({value:s.args,schema:oR}),i=u=>({tool_names:u.toolNames}),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:i(l.never)}:void 0;n.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:r.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const s=o;throw new qr({functionality:`tool choice type: ${s}`})}}}function mR(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:gR(r.skills)}}return{type:"local",skills:e.skills}}function gR(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function A_(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var yR=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:p}){var f,g,_,y,w,v,m,S,k;const T=[],b=h_(this.modelId);o!=null&&T.push({type:"unsupported",feature:"topK"}),i!=null&&T.push({type:"unsupported",feature:"seed"}),s!=null&&T.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&T.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&T.push({type:"unsupported",feature:"stopSequences"});const x=this.config.provider.includes("azure")?"azure":"openai";let I=await tn({provider:x,providerOptions:c,schema:N_});I==null&&x!=="openai"&&(I=await tn({provider:"openai",providerOptions:c,schema:N_}));const L=(f=I?.forceReasoning)!=null?f:b.isReasoningModel;I?.conversation&&I?.previousResponseId&&T.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const O=m5({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:A,warnings:N}=await uR({prompt:l,toolNameMapping:O,systemMessageMode:(g=I?.systemMessageMode)!=null?g:L?"developer":b.systemMessageMode,providerOptionsName:x,fileIdPrefixes:this.config.fileIdPrefixes,store:(_=I?.store)!=null?_:!0,hasConversation:I?.conversation!=null,hasLocalShellTool:ue("openai.local_shell"),hasShellTool:ue("openai.shell"),hasApplyPatchTool:ue("openai.apply_patch")});T.push(...N);const U=(y=I?.strictJsonSchema)!=null?y:!0;let G=I?.include;function J(K){G==null?G=[K]:G.includes(K)||(G=[...G,K])}function ue(K){return u?.find(ne=>ne.type==="provider"&&ne.id===K)!=null}const re=typeof I?.logprobs=="number"?I?.logprobs:I?.logprobs===!0?O_:void 0;re&&J("message.output_text.logprobs");const ge=(w=u?.find(K=>K.type==="provider"&&(K.id==="openai.web_search"||K.id==="openai.web_search_preview")))==null?void 0:w.name;ge&&J("web_search_call.action.sources"),ue("openai.code_interpreter")&&J("code_interpreter_call.outputs");const V=I?.store;V===!1&&L&&J("reasoning.encrypted_content");const R={model:this.modelId,input:A,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||I?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:U,name:(v=p.name)!=null?v:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...I?.textVerbosity&&{verbosity:I.textVerbosity}}},conversation:I?.conversation,max_tool_calls:I?.maxToolCalls,metadata:I?.metadata,parallel_tool_calls:I?.parallelToolCalls,previous_response_id:I?.previousResponseId,store:V,user:I?.user,instructions:I?.instructions,service_tier:I?.serviceTier,include:G,prompt_cache_key:I?.promptCacheKey,prompt_cache_retention:I?.promptCacheRetention,safety_identifier:I?.safetyIdentifier,top_logprobs:re,truncation:I?.truncation,...L&&(I?.reasoningEffort!=null||I?.reasoningSummary!=null)&&{reasoning:{...I?.reasoningEffort!=null&&{effort:I.reasoningEffort},...I?.reasoningSummary!=null&&{summary:I.reasoningSummary}}}};L?I?.reasoningEffort==="none"&&b.supportsNonReasoningParameters||(R.temperature!=null&&(R.temperature=void 0,T.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),R.top_p!=null&&(R.top_p=void 0,T.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(I?.reasoningEffort!=null&&T.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),I?.reasoningSummary!=null&&T.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),I?.serviceTier==="flex"&&!b.supportsFlexProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete R.service_tier),I?.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete R.service_tier);const{tools:H,toolChoice:Z,toolWarnings:E}=await hR({tools:u,toolChoice:h}),M=(k=(S=(m=u?.find(K=>K.type==="provider"&&K.id==="openai.shell"))==null?void 0:m.args)==null?void 0:S.environment)==null?void 0:k.type,D=M==="containerAuto"||M==="containerReference";return{webSearchToolName:ge,args:{...R,tools:H,tool_choice:Z},warnings:[...T,...E],store:V,toolNameMapping:O,providerOptionsName:x,isShellProviderExecuted:D}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,g,_,y,w,v,m,S,k,T,b,x,I;const{args:L,warnings:O,webSearchToolName:A,toolNameMapping:N,providerOptionsName:U,isShellProviderExecuted:G}=await this.getArgs(e),J=this.config.url({path:"/responses",modelId:this.modelId}),ue=A_(e.prompt),{responseHeaders:re,value:ge,rawValue:V}=await Jt({url:J,headers:Nt(this.config.headers(),e.headers),body:L,failedResponseHandler:xr,successfulResponseHandler:dr(fR),abortSignal:e.abortSignal,fetch:this.config.fetch});if(ge.error)throw new ut({message:ge.error.message,url:J,requestBodyValues:L,statusCode:400,responseHeaders:re,responseBody:V,isRetryable:!1});const R=[],H=[];let Z=!1;for(const D of ge.output)switch(D.type){case"reasoning":{D.summary.length===0&&D.summary.push({type:"summary_text",text:""});for(const K of D.summary)R.push({type:"reasoning",text:K.text,providerMetadata:{[U]:{itemId:D.id,reasoningEncryptedContent:(t=D.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:N.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:N.toCustomToolName("image_generation"),result:{result:D.result}});break}case"local_shell_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:N.toCustomToolName("local_shell"),input:JSON.stringify({action:D.action}),providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:N.toCustomToolName("shell"),input:JSON.stringify({action:{commands:D.action.commands}}),...G&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call_output":{R.push({type:"tool-result",toolCallId:D.call_id,toolName:N.toCustomToolName("shell"),result:{output:D.output.map(K=>({stdout:K.stdout,stderr:K.stderr,outcome:K.outcome.type==="exit"?{type:"exit",exitCode:K.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const K of D.content){(n=(r=e.providerOptions)==null?void 0:r[U])!=null&&n.logprobs&&K.logprobs&&H.push(K.logprobs);const ne={itemId:D.id,...K.annotations.length>0&&{annotations:K.annotations}};R.push({type:"text",text:K.text,providerMetadata:{[U]:ne}});for(const ae of K.annotations)ae.type==="url_citation"?R.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:Ut(),url:ae.url,title:ae.title}):ae.type==="file_citation"?R.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Ut(),mediaType:"text/plain",title:ae.filename,filename:ae.filename,providerMetadata:{[U]:{type:ae.type,fileId:ae.file_id,index:ae.index}}}):ae.type==="container_file_citation"?R.push({type:"source",sourceType:"document",id:(p=(h=(u=this.config).generateId)==null?void 0:h.call(u))!=null?p:Ut(),mediaType:"text/plain",title:ae.filename,filename:ae.filename,providerMetadata:{[U]:{type:ae.type,fileId:ae.file_id,containerId:ae.container_id}}}):ae.type==="file_path"&&R.push({type:"source",sourceType:"document",id:(_=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?_:Ut(),mediaType:"application/octet-stream",title:ae.file_id,filename:ae.file_id,providerMetadata:{[U]:{type:ae.type,fileId:ae.file_id,index:ae.index}}})}break}case"function_call":{Z=!0,R.push({type:"tool-call",toolCallId:D.call_id,toolName:D.name,input:D.arguments,providerMetadata:{[U]:{itemId:D.id}}});break}case"web_search_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:N.toCustomToolName(A??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:N.toCustomToolName(A??"web_search"),result:L_(D.action)});break}case"mcp_call":{const K=D.approval_request_id!=null&&(y=ue[D.approval_request_id])!=null?y:D.id,ne=`mcp.${D.name}`;R.push({type:"tool-call",toolCallId:K,toolName:ne,input:D.arguments,providerExecuted:!0,dynamic:!0}),R.push({type:"tool-result",toolCallId:K,toolName:ne,result:{type:"call",serverLabel:D.server_label,name:D.name,arguments:D.arguments,...D.output!=null?{output:D.output}:{},...D.error!=null?{error:D.error}:{}},providerMetadata:{[U]:{itemId:D.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const K=(w=D.approval_request_id)!=null?w:D.id,ne=(S=(m=(v=this.config).generateId)==null?void 0:m.call(v))!=null?S:Ut(),ae=`mcp.${D.name}`;R.push({type:"tool-call",toolCallId:ne,toolName:ae,input:D.arguments,providerExecuted:!0,dynamic:!0}),R.push({type:"tool-approval-request",approvalId:K,toolCallId:ne});break}case"computer_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:N.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:N.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:D.status||"completed"}});break}case"file_search_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:N.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:N.toCustomToolName("file_search"),result:{queries:D.queries,results:(T=(k=D.results)==null?void 0:k.map(K=>({attributes:K.attributes,fileId:K.file_id,filename:K.filename,score:K.score,text:K.text})))!=null?T:null}});break}case"code_interpreter_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:N.toCustomToolName("code_interpreter"),input:JSON.stringify({code:D.code,containerId:D.container_id}),providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:N.toCustomToolName("code_interpreter"),result:{outputs:D.outputs}});break}case"apply_patch_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:N.toCustomToolName("apply_patch"),input:JSON.stringify({callId:D.call_id,operation:D.operation}),providerMetadata:{[U]:{itemId:D.id}}});break}}const E={[U]:{responseId:ge.id,...H.length>0?{logprobs:H}:{},...typeof ge.service_tier=="string"?{serviceTier:ge.service_tier}:{}}},M=ge.usage;return{content:R,finishReason:{unified:M_({finishReason:(b=ge.incomplete_details)==null?void 0:b.reason,hasFunctionCall:Z}),raw:(I=(x=ge.incomplete_details)==null?void 0:x.reason)!=null?I:void 0},usage:R_(M),request:{body:L},response:{id:ge.id,timestamp:new Date(ge.created_at*1e3),modelId:ge.model,headers:re,body:V},providerMetadata:E,warnings:O}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await Jt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:xr,successfulResponseHandler:tl(pR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,h=A_(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const _=[];let y=null;const w={},v=[];let m=!1;const S={};let k;return{stream:c.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:r})},transform(T,b){var x,I,L,O,A,N,U,G,J,ue,re,ge,V,R,H,Z,E,M,D,K,ne,ae,Ie,z,F,Y,ee,le,be,tt;if(e.includeRawChunks&&b.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){f={unified:"error",raw:void 0},b.enqueue({type:"error",error:T.error});return}const P=T.value;if(q_(P)){if(P.item.type==="function_call")w[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},b.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="web_search_call")w[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),b.enqueue({type:"tool-input-end",id:P.item.id}),b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(P.item.type==="computer_call")w[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")w[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),b.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(P.item.type==="mcp_call"||P.item.type==="mcp_list_tools"||P.item.type==="mcp_approval_request"))if(P.item.type==="apply_patch_call"){const{call_id:te,operation:Oe}=P.item;if(w[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:te,applyPatch:{hasDiff:Oe.type==="delete_file",endEmitted:Oe.type==="delete_file"}},b.enqueue({type:"tool-input-start",id:te,toolName:o.toCustomToolName("apply_patch")}),Oe.type==="delete_file"){const je=JSON.stringify({callId:te,operation:Oe});b.enqueue({type:"tool-input-delta",id:te,delta:je}),b.enqueue({type:"tool-input-end",id:te})}else b.enqueue({type:"tool-input-delta",id:te,delta:`{"callId":"${no(te)}","operation":{"type":"${no(Oe.type)}","path":"${no(Oe.path)}","diff":"`})}else P.item.type==="shell_call"?w[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(v.splice(0,v.length),b.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id}}})):q_(P)&&P.item.type==="reasoning"&&(S[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},b.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(x=P.item.encrypted_content)!=null?x:null}}})))}else if(_R(P)){if(P.item.type==="message")b.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,...v.length>0&&{annotations:v}}}});else if(P.item.type==="function_call")w[P.output_index]=void 0,m=!0,b.enqueue({type:"tool-input-end",id:P.item.call_id}),b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="web_search_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:L_(P.item.action)});else if(P.item.type==="computer_call")w[P.output_index]=void 0,b.enqueue({type:"tool-input-end",id:P.item.id}),b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:P.item.status||"completed"}});else if(P.item.type==="file_search_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(L=(I=P.item.results)==null?void 0:I.map(te=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?L:null}});else if(P.item.type==="code_interpreter_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:P.item.outputs}});else if(P.item.type==="image_generation_call")b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:P.item.result}});else if(P.item.type==="mcp_call"){w[P.output_index]=void 0;const te=(O=P.item.approval_request_id)!=null?O:void 0,Oe=te!=null&&(N=(A=p.get(te))!=null?A:h[te])!=null?N:P.item.id,je=`mcp.${P.item.name}`;b.enqueue({type:"tool-call",toolCallId:Oe,toolName:je,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),b.enqueue({type:"tool-result",toolCallId:Oe,toolName:je,result:{type:"call",serverLabel:P.item.server_label,name:P.item.name,arguments:P.item.arguments,...P.item.output!=null?{output:P.item.output}:{},...P.item.error!=null?{error:P.item.error}:{}},providerMetadata:{[a]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")w[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const te=w[P.output_index];te?.applyPatch&&!te.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(te.applyPatch.hasDiff||b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:no(P.item.operation.diff)}),b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),b.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0),te&&P.item.status==="completed"&&b.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[a]:{itemId:P.item.id}}}),w[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){w[P.output_index]=void 0;const te=(J=(G=(U=u.config).generateId)==null?void 0:G.call(U))!=null?J:Ut(),Oe=(ue=P.item.approval_request_id)!=null?ue:P.item.id;p.set(Oe,te);const je=`mcp.${P.item.name}`;b.enqueue({type:"tool-call",toolCallId:te,toolName:je,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),b.enqueue({type:"tool-approval-request",approvalId:Oe,toolCallId:te})}else if(P.item.type==="local_shell_call")w[P.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")w[P.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")b.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const te=S[P.item.id],Oe=Object.entries(te.summaryParts).filter(([je,Kt])=>Kt==="active"||Kt==="can-conclude").map(([je])=>je);for(const je of Oe)b.enqueue({type:"reasoning-end",id:`${P.item.id}:${je}`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(re=P.item.encrypted_content)!=null?re:null}}});delete S[P.item.id]}}else if(kR(P)){const te=w[P.output_index];te!=null&&b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:P.delta})}else if(IR(P)){const te=w[P.output_index];te?.applyPatch&&(b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:no(P.delta)}),te.applyPatch.hasDiff=!0)}else if(ER(P)){const te=w[P.output_index];te?.applyPatch&&!te.applyPatch.endEmitted&&(te.applyPatch.hasDiff||(b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:no(P.diff)}),te.applyPatch.hasDiff=!0),b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),b.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0)}else if(TR(P))b.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(CR(P)){const te=w[P.output_index];te!=null&&b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:no(P.delta)})}else if(SR(P)){const te=w[P.output_index];te!=null&&(b.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}'}),b.enqueue({type:"tool-input-end",id:te.toolCallId}),b.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:te.codeInterpreter.containerId}),providerExecuted:!0}))}else if(bR(P))y=P.response.id,b.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(vR(P))b.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(V=(ge=e.providerOptions)==null?void 0:ge[a])!=null&&V.logprobs&&P.logprobs&&_.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const te=S[P.item_id];te.summaryParts[P.summary_index]="active";for(const Oe of Object.keys(te.summaryParts))te.summaryParts[Oe]==="can-conclude"&&(b.enqueue({type:"reasoning-end",id:`${P.item_id}:${Oe}`,providerMetadata:{[a]:{itemId:P.item_id}}}),te.summaryParts[Oe]="concluded");b.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id,reasoningEncryptedContent:(H=(R=S[P.item_id])==null?void 0:R.encryptedContent)!=null?H:null}}})}}else P.type==="response.reasoning_summary_text.delta"?b.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[a]:{itemId:P.item_id}}}):P.type==="response.reasoning_summary_part.done"?s?(b.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id}}}),S[P.item_id].summaryParts[P.summary_index]="concluded"):S[P.item_id].summaryParts[P.summary_index]="can-conclude":wR(P)?(f={unified:M_({finishReason:(Z=P.response.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:m}),raw:(M=(E=P.response.incomplete_details)==null?void 0:E.reason)!=null?M:void 0},g=P.response.usage,typeof P.response.service_tier=="string"&&(k=P.response.service_tier)):xR(P)?(v.push(P.annotation),P.annotation.type==="url_citation"?b.enqueue({type:"source",sourceType:"url",id:(ne=(K=(D=u.config).generateId)==null?void 0:K.call(D))!=null?ne:Ut(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?b.enqueue({type:"source",sourceType:"document",id:(z=(Ie=(ae=u.config).generateId)==null?void 0:Ie.call(ae))!=null?z:Ut(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?b.enqueue({type:"source",sourceType:"document",id:(ee=(Y=(F=u.config).generateId)==null?void 0:Y.call(F))!=null?ee:Ut(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&b.enqueue({type:"source",sourceType:"document",id:(tt=(be=(le=u.config).generateId)==null?void 0:be.call(le))!=null?tt:Ut(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):$R(P)&&b.enqueue({type:"error",error:P})},flush(T){const b={[a]:{responseId:y,..._.length>0?{logprobs:_}:{},...k!==void 0?{serviceTier:k}:{}}};T.enqueue({type:"finish",finishReason:f,usage:R_(g),providerMetadata:b})}})),request:{body:t},response:{headers:l}}}};function vR(e){return e.type==="response.output_text.delta"}function _R(e){return e.type==="response.output_item.done"}function wR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function bR(e){return e.type==="response.created"}function kR(e){return e.type==="response.function_call_arguments.delta"}function TR(e){return e.type==="response.image_generation_call.partial_image"}function CR(e){return e.type==="response.code_interpreter_call_code.delta"}function SR(e){return e.type==="response.code_interpreter_call_code.done"}function IR(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function ER(e){return e.type==="response.apply_patch_call_operation_diff.done"}function q_(e){return e.type==="response.output_item.added"}function xR(e){return e.type==="response.output_text.annotation.added"}function $R(e){return e.type==="error"}function L_(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function no(e){return JSON.stringify(e).slice(1,-1)}var RR=Ce(()=>Te(C({instructions:d().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),PR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await tn({provider:"openai",providerOptions:a,schema:RR}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const h in u){const p=u[h];p!==void 0&&(c[h]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await Jt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:s,failedResponseHandler:xr,successfulResponseHandler:II(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},MR=Ce(()=>Te(C({text:d(),language:d().nullish(),duration:j().nullish(),words:q(C({word:d(),start:j(),end:j()})).nullish(),segments:q(C({id:j(),seek:j(),start:j(),end:j(),text:d(),tokens:q(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),OR=Ce(()=>Te(C({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(we(["word","segment"])).default(["segment"]).optional()}))),j_={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},NR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await tn({provider:"openai",providerOptions:r,schema:OR}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Po(e)]);s.append("model",this.modelId);const i=$5(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const h of u)s.append(`${c}[]`,String(h));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:h}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await vg({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),formData:u,failedResponseHandler:xr,successfulResponseHandler:dr(MR),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=p.language!=null&&p.language in j_?j_[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?a:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:_,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},AR="3.0.33";function D_(e={}){var t,r;const n=(t=bg(No({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>In({Authorization:`Bearer ${x5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${AR}`),a=_=>new y7(_,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=_=>new b7(_,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=_=>new C7(_,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=_=>new x7(_,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=_=>new NR(_,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),h=_=>new PR(_,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=_=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(_)},f=_=>new yR(_,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(_){return p(_)};return g.specificationVersion="v3",g.languageModel=p,g.chat=a,g.completion=i,g.responses=f,g.embedding=l,g.embeddingModel=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=h,g.speechModel=h,g.tools=cR,g}D_();var U_="vercel.ai.error",qR=Symbol.for(U_),z_,LR=class F1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[z_]=!0,this.name=t,this.cause=n}static isInstance(t){return F1.hasMarker(t,U_)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};z_=qR;var Tt=LR,Z_="AI_APICallError",F_=`vercel.ai.error.${Z_}`,jR=Symbol.for(F_),V_,on=class extends Tt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:Z_,message:e,cause:a}),this[V_]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return Tt.hasMarker(e,F_)}};V_=jR;var H_="AI_EmptyResponseBodyError",B_=`vercel.ai.error.${H_}`,DR=Symbol.for(B_),J_,UR=class extends Tt{constructor({message:e="Empty response body"}={}){super({name:H_,message:e}),this[J_]=!0}static isInstance(e){return Tt.hasMarker(e,B_)}};J_=DR;function W_(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var G_="AI_InvalidArgumentError",K_=`vercel.ai.error.${G_}`,zR=Symbol.for(K_),Y_,Q_=class extends Tt{constructor({message:e,cause:t,argument:r}){super({name:G_,message:e,cause:t}),this[Y_]=!0,this.argument=r}static isInstance(e){return Tt.hasMarker(e,K_)}};Y_=zR;var X_="AI_InvalidResponseDataError",e1=`vercel.ai.error.${X_}`,ZR=Symbol.for(e1),t1,r1=class extends Tt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:X_,message:t}),this[t1]=!0,this.data=e}static isInstance(e){return Tt.hasMarker(e,e1)}};t1=ZR;var n1="AI_JSONParseError",o1=`vercel.ai.error.${n1}`,FR=Symbol.for(o1),s1,_l=class extends Tt{constructor({text:e,cause:t}){super({name:n1,message:`JSON parsing failed: Text: ${e}.
596
+ Error message: ${W_(t)}`,cause:t}),this[s1]=!0,this.text=e}static isInstance(e){return Tt.hasMarker(e,o1)}};s1=FR;var a1="AI_LoadAPIKeyError",i1=`vercel.ai.error.${a1}`,VR=Symbol.for(i1),l1,wl=class extends Tt{constructor({message:e}){super({name:a1,message:e}),this[l1]=!0}static isInstance(e){return Tt.hasMarker(e,i1)}};l1=VR;var c1="AI_NoSuchModelError",u1=`vercel.ai.error.${c1}`,HR=Symbol.for(u1),d1,p1=class extends Tt{constructor({errorName:e=c1,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[d1]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Tt.hasMarker(e,u1)}};d1=HR;var f1="AI_TypeValidationError",h1=`vercel.ai.error.${f1}`,BR=Symbol.for(h1),m1,JR=class fp extends Tt{constructor({value:t,cause:r}){super({name:f1,message:`Type validation failed: Value: ${JSON.stringify(t)}.
597
+ Error message: ${W_(r)}`,cause:r}),this[m1]=!0,this.value=t}static isInstance(t){return Tt.hasMarker(t,h1)}static wrap({value:t,cause:r}){return fp.isInstance(r)&&r.value===t?r:new fp({value:t,cause:r})}};m1=BR;var ra=JR,g1="AI_UnsupportedFunctionalityError",y1=`vercel.ai.error.${g1}`,WR=Symbol.for(y1),v1,_1=class extends Tt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:g1,message:t}),this[v1]=!0,this.functionality=e}static isInstance(e){return Tt.hasMarker(e,y1)}};v1=WR;function w1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function bl(e){return Object.fromEntries([...e.headers])}var GR=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new Q_({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},kl=GR();function Kd(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var KR=["fetch failed","failed to fetch"];function YR({error:e,url:t,requestBodyValues:r}){if(Kd(e))return e;if(e instanceof TypeError&&KR.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new on({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function QR(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function XR(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function b1(e,...t){const r=new Headers(XR(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var eP="3.0.18";function tP({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new wl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new wl({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new wl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new wl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var rP=/"__proto__"\s*:/,nP=/"constructor"\s*:/;function k1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||rP.test(e)===!1&&nP.test(e)===!1?t:oP(t)}function oP(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Yd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return k1(e)}try{return k1(e)}finally{Error.stackTraceLimit=t}}var Qd=Symbol.for("vercel.ai.validator");function sP(e){return{[Qd]:!0,validate:e}}function aP(e){return typeof e=="object"&&e!==null&&Qd in e&&e[Qd]===!0&&"validate"in e}function iP(e){return aP(e)?e:typeof e=="function"?e():lP(e)}function lP(e){return sP(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ra({value:t,cause:r.issues})}})}async function cP({value:e,schema:t}){const r=await na({value:e,schema:t});if(!r.success)throw ra.wrap({value:e,cause:r.error});return r.value}async function na({value:e,schema:t}){const r=iP(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:ra.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ra.wrap({value:e,cause:n}),rawValue:e}}}async function uP({text:e,schema:t}){try{const r=Yd(e);return t==null?r:cP({value:r,schema:t})}catch(r){throw _l.isInstance(r)||ra.isInstance(r)?r:new _l({text:e,cause:r})}}async function T1({text:e,schema:t}){try{const r=Yd(e);return t==null?{success:!0,value:r,rawValue:r}:await na({value:r,schema:t})}catch(r){return{success:!1,error:_l.isInstance(r)?r:new _l({text:e,cause:r}),rawValue:void 0}}}function C1(e){try{return Yd(e),!0}catch{return!1}}function dP({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Io).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await T1({text:r,schema:t}))}}))}async function S1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await na({value:t[e],schema:r});if(!n.success)throw new Q_({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var pP=()=>globalThis.fetch,I1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>fP({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),fP=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=pP()})=>{try{const i=await a(e,{method:"POST",headers:b1(t,`ai-sdk/provider-utils/${eP}`,QR()),body:r.content,signal:s}),l=bl(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Kd(u)||on.isInstance(u)?u:new on({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Kd(c)||on.isInstance(c))?c:new on({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw YR({error:i,url:e,requestBodyValues:r.values})}},hP=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=bl(n);if(a.trim()==="")return{responseHeaders:i,value:new on({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await uP({text:a,schema:e});return{responseHeaders:i,value:new on({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new on({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},mP=e=>async({response:t})=>{const r=bl(t);if(t.body==null)throw new UR({});return{responseHeaders:r,value:dP({stream:t.body,schema:e})}},gP=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await T1({text:o,schema:e}),a=bl(t);if(!s.success)throw new on({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:yP}=globalThis;function vP(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return yP(t)}function _P(e){return e instanceof Uint8Array?vP(e):e}function wP(e){return e?.replace(/\/$/,"")}function oa(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function bP(e){const t=[];for(const{role:r,content:n,...o}of e){const s=oa({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...oa(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=oa(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${_P(a.data)}`},...i}}else throw new _1({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=oa(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=oa(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function E1({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function x1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Xd=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),kP=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:oe([d(),j()]).nullish()})}),TP={errorSchema:kP,errorToMessage:e=>e.error.message};function CP({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new _1({functionality:`tool choice type: ${s}`})}}}var SP=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:TP;this.chunkSchema=EP(o.errorSchema),this.failedResponseHandler=hP(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:p}){var f,g,_,y;const w=[],v=Object.assign((f=await S1({provider:"openai-compatible",providerOptions:i,schema:Xd}))!=null?f:{},(g=await S1({provider:this.providerOptionsName,providerOptions:i,schema:Xd}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:m,toolChoice:S,toolWarnings:k}=CP({tools:p,toolChoice:h});return{args:{model:this.modelId,user:v.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(_=c.name)!=null?_:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([T])=>!Object.keys(Xd.shape).includes(T))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:bP(e),tools:m,tool_choice:S},warnings:[...w,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,g,_,y,w;const{args:v,warnings:m}=await this.getArgs({...e}),S=JSON.stringify(v),{responseHeaders:k,value:T,rawValue:b}=await I1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:w1(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:gP(IP),abortSignal:e.abortSignal,fetch:this.config.fetch}),x=T.choices[0],I=[],L=x.message.content;L!=null&&L.length>0&&I.push({type:"text",text:L});const O=(t=x.message.reasoning_content)!=null?t:x.message.reasoning;if(O!=null&&O.length>0&&I.push({type:"reasoning",text:O}),x.message.tool_calls!=null)for(const U of x.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:kl(),toolName:U.function.name,input:U.function.arguments});const A={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:b}))},N=(s=T.usage)==null?void 0:s.completion_tokens_details;return N?.accepted_prediction_tokens!=null&&(A[this.providerOptionsName].acceptedPredictionTokens=N?.accepted_prediction_tokens),N?.rejected_prediction_tokens!=null&&(A[this.providerOptionsName].rejectedPredictionTokens=N?.rejected_prediction_tokens),{content:I,finishReason:x1(x.finish_reason),usage:{inputTokens:(i=(a=T.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=T.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=T.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(g=(f=(p=T.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(_=T.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:A,request:{body:S},response:{...E1(T),headers:k,body:b},warnings:m}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await I1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:w1(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:mP(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const p=this.providerOptionsName;let f=!1,g=!1;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,y){var w,v,m,S,k,T,b,x,I,L,O,A,N;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",y.enqueue({type:"error",error:_.error});return}const U=_.value;if(s?.processChunk(_.rawValue),"error"in U){c="error",y.enqueue({type:"error",error:U.error.message});return}if(h&&(h=!1,y.enqueue({type:"response-metadata",...E1(U)})),U.usage!=null){const{prompt_tokens:re,completion_tokens:ge,total_tokens:V,prompt_tokens_details:R,completion_tokens_details:H}=U.usage;u.promptTokens=re??void 0,u.completionTokens=ge??void 0,u.totalTokens=V??void 0,H?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=H?.reasoning_tokens),H?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=H?.accepted_prediction_tokens),H?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=H?.rejected_prediction_tokens),R?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=R?.cached_tokens)}const G=U.choices[0];if(G?.finish_reason!=null&&(c=x1(G.finish_reason)),G?.delta==null)return;const J=G.delta,ue=(w=J.reasoning_content)!=null?w:J.reasoning;if(ue&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ue})),J.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:J.content})),J.tool_calls!=null)for(const re of J.tool_calls){const ge=re.index;if(l[ge]==null){if(re.id==null)throw new r1({data:re,message:"Expected 'id' to be a string."});if(((v=re.function)==null?void 0:v.name)==null)throw new r1({data:re,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[ge]={id:re.id,type:"function",function:{name:re.function.name,arguments:(m=re.function.arguments)!=null?m:""},hasFinished:!1};const R=l[ge];((S=R.function)==null?void 0:S.name)!=null&&((k=R.function)==null?void 0:k.arguments)!=null&&(R.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),C1(R.function.arguments)&&(y.enqueue({type:"tool-input-end",id:R.id}),y.enqueue({type:"tool-call",toolCallId:(T=R.id)!=null?T:kl(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const V=l[ge];V.hasFinished||(((b=re.function)==null?void 0:b.arguments)!=null&&(V.function.arguments+=(I=(x=re.function)==null?void 0:x.arguments)!=null?I:""),y.enqueue({type:"tool-input-delta",id:V.id,delta:(L=re.function.arguments)!=null?L:""}),((O=V.function)==null?void 0:O.name)!=null&&((A=V.function)==null?void 0:A.arguments)!=null&&C1(V.function.arguments)&&(y.enqueue({type:"tool-input-end",id:V.id}),y.enqueue({type:"tool-call",toolCallId:(N=V.id)!=null?N:kl(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(_){var y,w,v,m,S,k;f&&_.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&_.enqueue({type:"text-end",id:"txt-0"});for(const b of l.filter(x=>!x.hasFinished))_.enqueue({type:"tool-input-end",id:b.id}),_.enqueue({type:"tool-call",toolCallId:(y=b.id)!=null?y:kl(),toolName:b.function.name,input:b.function.arguments});const T={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(T[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(T[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),_.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(m=u.totalTokens)!=null?m:void 0,reasoningTokens:(S=u.completionTokensDetails.reasoningTokens)!=null?S:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:T})}})),request:{body:o},response:{headers:a}}}},$1=C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),IP=C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({message:C({role:$("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:$1}),EP=e=>oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:we(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({index:j(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:$1}),e]);C({echo:me().optional(),logitBias:ye(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var xP=C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d()})),usage:xP.nullish()}),C({dimensions:j().optional(),user:d().optional()}),C({data:q(C({embedding:q(j())})),usage:C({prompt_tokens:j()}).nullish(),providerMetadata:ye(d(),ye(d(),bt())).optional()}),C({data:q(C({b64_json:d()}))});var R1=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},$P={extractMetadata:async({parsedBody:e})=>{const t=await na({value:e,schema:RP});return!t.success||t.value.usage==null?void 0:R1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await na({value:t,schema:PP});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>R1(e)}}},P1=C({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),RP=C({usage:P1.nullish()}),PP=C({choices:q(C({finish_reason:d().nullish()})).nullish(),usage:P1.nullish()}),MP="1.0.30";function M1(e={}){var t;const r=wP((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>b1({Authorization:`Bearer ${tP({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${MP}`);class o extends SP{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:$P}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new p1({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new p1({modelId:i,modelType:"imageModel"})},a}M1();const O1=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=wg({description:o,inputSchema:Ao({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function OP(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
590
598
 
591
599
  # 工具调用
592
600
 
593
601
  `;return r+=`你可以根据需要调用以下工具:
594
602
 
595
603
  `,r+=`<tools>
596
- `,e.forEach(([n,s])=>{const o=s,a=o.description||"无描述",i=o.parameters||o.inputSchema||{};r+=`${JSON.stringify({name:n,description:a,parameters:i},null,2)}
604
+ `,t.forEach(([n,o])=>{const s=o,a=s.description||"无描述",i=s.parameters||s.inputSchema||{};r+=`${JSON.stringify({name:n,description:a,parameters:i},null,2)}
597
605
  `}),r+=`</tools>
598
606
 
599
607
  `,r+=`## 工具调用格式
@@ -620,10 +628,15 @@ ${e}:`]}}function J1({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??vo
620
628
  `,r+=`- 必须严格按照 XML 格式调用工具
621
629
  `,r+=`- arguments 必须是有效的 JSON 格式
622
630
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
623
- `,r}function h_(t,e){if(!t||typeof t!="string")return null;const r=t.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),s=JSON.parse(n),o=s.name||s.action||s.tool,a=s.arguments||s.args||s.input||{};if(o&&e[o])return{toolName:o,arguments:a}}catch{}return null}const _R={openai:a_,deepseek:p_};class vR{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const n=e.providerType;let s;typeof n=="string"?s=_R[n]:s=n,this.llm=s({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=e.useReActMode??!1}async _createOneClient(e){try{let r;if("type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new to(new URL(e.url)):"type"in e&&e.type==="extension"?r=new N0(e.sessionId):"transport"in e?r=e.transport:r=e,e.useAISdkClient??!1){const s=await g7({transport:r});return s.__transport__=r,s}else{const s=new O0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await s.connect(r),s.__transport__=r,s}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){try{const r=e.__transport__;if(r&&r instanceof ao||r&&r instanceof ro)return;await r?.terminateSession?.(),await r?.close?.(),await e?.close?.()}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([n,s])=>{const o=await this._createOneClient(s);return{serverName:n,client:o}}));this.mcpClients={},r.forEach(({serverName:n,client:s})=>{this.mcpClients[n]=s})}async _getClientTools(e,r){if(!e)return null;try{return typeof e.tools=="function"?await e.tools():await f_(e)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([n,s])=>{const o=await this._getClientTools(s,n);return{serverName:n,tools:o}}));this.mcpTools={},r.forEach(({serverName:n,tools:s})=>{const o=s&&typeof s=="object"?s:{};this.mcpTools[n]=o})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){if(this.mcpServers[e])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=n;const s=await this._getClientTools(n,e);return this.mcpTools[e]=s&&typeof s=="object"?s:{},this.mcpServers[e]=r,this.onUpdatedTools?.(),n}async removeMcpServer(e){if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[e];delete this.mcpTools[e],n&&Object.keys(n).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),this.onUpdatedTools?.()}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((n,s)=>({...n,...s}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(e,r,n){const s=yR(e);return n?`${n}${s}`:`你是一个智能助手,可以通过调用工具来完成任务。
624
- ${s}`}async _executeReActToolCall(e,r,n){const s=n[e];if(!s)return{success:!1,error:`工具 ${e} 不存在`};try{const o=s,a=o.execute||o.call;return typeof a!="function"?{success:!1,error:`工具 ${e} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(o){return{success:!1,error:o?.message||String(o)||"工具执行失败"}}}async _chatReAct(e,{model:r,maxSteps:n=5,...s}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o=this._tempMergeTools(s.tools);if(Object.keys(o).length===0)return this._chat(e,{model:r,maxSteps:n,...s});let i=[];s.message&&!s.messages?i.push({role:"user",content:s.message}):s.messages?i=[...s.messages]:i=[...this.responseMessages];const c=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(o,c,s.system)},p=i[0]?.role==="system"?i:[u,...i];return e===Ku?this._chatReActStream(p,o,c,n,s):this._chatReActNonStream(p,o,c,n,s)}_messageHasImage(e){return e&&Array.isArray(e)?e.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(e){if(!e||!e.content)return null;if(!Array.isArray(e.content))return e;const r=e.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...e,content:r}}_buildMessagesForModel(e,r,n=3){const s=[];e&&s.push(e);let o=0;const a=[];for(let i=r.length-1;i>=0;i--){const c=r[i];if(this._messageHasImage(c.content))if(o<n)a.unshift(c),o++;else{const u=this._removeImageFromMessage(c);u&&a.unshift(u)}else a.unshift(c)}return s.push(...a),s}async _chatReActNonStream(e,r,n,s,o){let a=[...e];const i=e[0]?.role==="system"?e[0]:null,c=i?e.slice(1):e;let l=0;const u=o.maxImages??3;for(;l<s;){l++;const h=this._buildMessagesForModel(i,c,u),{tools:d,...f}=o,g=(await py({model:this.llm(n),messages:h,...f})).text,w={role:"assistant",content:g};c.push(w),a.push(w);const y=h_(g,r);if(!y)return this.responseMessages=a,{text:g,response:{messages:a}};const _=await this._executeReActToolCall(y.toolName,y.arguments,r),S={role:"user",content:`<tool_response>
625
- ${_.success?JSON.stringify(_.result):`工具执行失败 - ${_.error}`}
626
- </tool_response>`};c.push(S),a.push(S)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(e,r,n,s,o){const a=this,i=this.llm(n);let c,l;const u=new Promise((h,d)=>{c=h,l=d});return{fullStream:new ReadableStream({async start(h){let d=[...e];const f=e[0]?.role==="system"?e[0]:null,v=f?e.slice(1):[...e];let g=0,w="";const y=o.maxImages??3;try{for(;g<s;){g++;const _=a._buildMessagesForModel(f,v,y),{tools:b,...k}=o;delete k.system,delete k.onFinish;const S=await Ku({...k,model:i,messages:_});let T="";for await(const te of S.fullStream)te.type==="text-delta"?(T+=te.text||"",h.enqueue({type:"text-delta",text:te.text})):te.type==="text-start"?h.enqueue({type:"text-start"}):te.type==="text-end"||h.enqueue(te);w+=T;const x={role:"assistant",content:w};v.push(x),d.push(x);const R=h_(w,r);if(!R){h.enqueue({type:"text-end"}),h.close(),a.responseMessages=d,c({messages:d});return}if(R.toolName==="computer"&&R.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.responseMessages=d,c({messages:d});return}const j=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:j,toolName:R.toolName});const O=JSON.stringify(R.arguments,null,2);h.enqueue({type:"tool-input-delta",id:j,delta:O});const D=await a._executeReActToolCall(R.toolName,R.arguments,r);let U,V=D.result;if(D.success&&D.result&&typeof D.result=="object"&&D.result.screenshot){U=D.result.screenshot;const{screenshot:te,...ye}=D.result;V=ye}let ne="";D.success?V&&Array.isArray(V.content)&&V.content.length>0&&V.content[0].text?ne=V.content[0].text:ne=JSON.stringify(V):ne=`工具执行失败 - ${D.error}`;let fe=`<tool_response>
627
- ${ne}
628
- </tool_response>`;U&&(fe+=`
629
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:j,result:fe});const de=U?{role:"user",content:[{type:"text",text:fe},{type:"image",image:U}]}:{role:"user",content:fe};v.push(de),d.push(de),w=""}h.enqueue({type:"text-end"}),h.close(),a.responseMessages=d,c({messages:d})}catch(_){h.error(_),l(_)}}}),response:u}}async _chat(e,{model:r,maxSteps:n=5,...s}){if(this.useReActMode)return this._chatReAct(e,{model:r,maxSteps:n,...s});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o={model:this.llm(r),stopWhen:Bu(n),...s,tools:this._tempMergeTools(s.tools)};let a=null;if(s.message&&!s.messages)a={role:"user",content:s.message},this.responseMessages.push(a),o.messages=[...this.responseMessages];else if(s.messages&&s.messages.length>0){const c=s.messages[s.messages.length-1];c.role==="user"&&(a=c)}const i=e(o);return i?.response?.then(c=>{const l=c.messages?.[0];a&&l?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...c.messages)}),i?.usage?.then(c=>{this.onUsage?.(c)}),i}async chat(e){return this._chat(py,e)}async chatStream(e){return this._chat(Ku,e)}}Oe.AgentModelProvider=vR,Oe.Ajv=Fp,Oe.AuthClientProvider=PS,Oe.ContentScriptServerTransport=s5,Oe.ExtensionClientTransport=N0,Oe.ExtensionPageServerTransport=n5,Oe.InMemoryTransport=ao,Oe.QrCode=gm,Oe.ResourceTemplate=US,Oe.UriTemplate=xr,Oe.WebMcpClient=O0,Oe.WebMcpServer=BS,Oe.completable=MS,Oe.createMessageChannelClientTransport=XS,Oe.createMessageChannelPairTransport=GS,Oe.createMessageChannelServerTransport=JS,Oe.createRemoter=q5,Oe.createSSEClientTransport=YS,Oe.createStreamableHTTPClientTransport=QS,Oe.getAISDKTools=f_,Oe.getDisplayName=HS,Oe.isMcpClient=r5,Oe.isMcpServer=KS,Oe.isMessageChannelClientTransport=t5,Oe.isMessageChannelServerTransport=WS,Oe.isSSEClientTransport=e5,Oe.isStreamableHTTPClientTransport=A0,Oe.z=vw,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"})}));
631
+ `,r}function N1(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const NP={openai:D_,deepseek:M1};class AP{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=NP[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?r=new Ps(new URL(t.url)):"type"in t&&t.type==="extension"?r=new S0(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await u7({transport:r});return o.__transport__=r,o}else{const o=new k0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof qs||r&&r instanceof Ms)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await O1(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={}){const r=Object.values(this.mcpTools).reduce((n,o)=>({...n,...o}),{});return Object.assign(r,t),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(t,r,n){const o=OP(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
632
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},h=i[0]?.role==="system"?i:[u,...i];return t===zd?this._chatReActStream(h,s,l,n,o):this._chatReActNonStream(h,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:f,...g}=s,y=(await jv({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const v=N1(y,r);if(!v)return this.responseMessages=a,{text:y,response:{messages:a}};const m=await this._executeReActToolCall(v.toolName,v.arguments,r),T={role:"user",content:`<tool_response>
633
+ ${m.success?JSON.stringify(m.result):`工具执行失败 - ${m.error}`}
634
+ </tool_response>`};l.push(T),a.push(T)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,f)=>{l=p,c=f});return{fullStream:new ReadableStream({async start(p){let f=[...t];const g=t[0]?.role==="system"?t[0]:null,_=g?t.slice(1):[...t];let y=0,w="";const v=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const m=a._buildMessagesForModel(g,_,v),{tools:S,...k}=s;delete k.system,delete k.onFinish;const T=await zd({...k,model:i,messages:m});let b="";for await(const J of T.fullStream)J.type==="text-delta"?(b+=J.text||"",p.enqueue({type:"text-delta",text:J.text})):J.type==="text-start"?p.enqueue({type:"text-start"}):J.type==="text-end"||J.type==="finish-step"||J.type==="finish"||J.type==="start"||J.type==="start-step"||p.enqueue(J);w+=b;const x={role:"assistant",content:w};_.push(x),f.push(x);const I=N1(w,r);if(!I){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}const L=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:L,toolName:I.toolName});const O=JSON.stringify(I.arguments,null,2);p.enqueue({type:"tool-input-delta",id:L,delta:O}),p.enqueue({type:"tool-input-end",id:L}),p.enqueue({type:"tool-call",toolCallId:L,toolName:I.toolName,input:I.arguments});const A=await a._executeReActToolCall(I.toolName,I.arguments,r);let N,U=A.result;if(A.success&&A.result&&typeof A.result=="object"&&A.result.screenshot){N=A.result.screenshot;const{screenshot:J,...ue}=A.result;U=ue}let G="";if(A.success){U&&Array.isArray(U.content)&&U.content.length>0&&U.content[0].text?G=U.content[0].text:G=JSON.stringify(U);let J=`<tool_response>
635
+ ${G}
636
+ </tool_response>`;N&&(J+=`
637
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:L,result:J});const ue=N?{role:"user",content:[{type:"text",text:J},{type:"image",image:N}]}:{role:"user",content:J};_.push(ue),f.push(ue),w=""}else G=`工具执行失败 - ${A.error}`,p.enqueue({type:"tool-error",toolCallId:L,input:I.arguments,error:{message:G}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f})}catch(m){p.error(m),c(m)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:jd(n),...o,tools:this._tempMergeTools(o.tools)};let a=null;if(o.message&&!o.messages)a={role:"user",content:o.message},this.responseMessages.push(a),s.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const l=o.messages[o.messages.length-1];l.role==="user"&&(a=l)}const i=t(s);return i?.response?.then(l=>{const c=l.messages?.[0];a&&c?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...l.messages)}),i}async chat(t){return this._chat(jv,t)}async chatStream(t){return this._chat(zd,t)}}const qP=/^\.\/[^/]+\/SKILL\.md$/,LP=/^---\s*\n([\s\S]+?)\s*\n---/;function A1(e){const t=e.match(LP);if(!t?.[1])return null;const r=t[1],n=r.match(/^name:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),s=n?.[1]?.trim(),a=o?.[1]?.trim();return s&&a?{name:s,description:a}:null}function ep(e){return Object.keys(e).filter(t=>qP.test(t))}function jP(e){const t=ep(e),r=[];for(const n of t){const o=e[n];if(!o)continue;const s=A1(o);s&&r.push({name:s.name,description:s.description,path:n})}return r}function DP(e){return e.length===0?"":`## 可用技能
638
+
639
+ ${e.map(r=>`- **${r.name}**: ${r.description}`).join(`
640
+ `)}
641
+
642
+ 当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function UP(e){return Object.keys(e)}function tp(e,t){return e[t]}function rp(e,t){return ep(e).find(r=>r.startsWith(`./${t}/SKILL.md`))}function zP(e){return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整 Markdown 文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)",inputSchema:Ft({skillName:Fe().optional().describe("技能名称,与目录名一致,如 calculator"),path:Fe().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.md")}),execute:r=>{const{skillName:n,path:o}=r;let s;if(o)s=tp(e,o);else if(n){const a=rp(e,n);s=a?tp(e,a):void 0}return s===void 0?{error:"未找到对应技能文档",skillName:n??o}:{content:s,path:o??rp(e,n)}}}}}Re.AgentModelProvider=AP,Re.Ajv=qf,Re.AuthClientProvider=WS,Re.ContentScriptServerTransport=b6,Re.ExtensionClientTransport=S0,Re.ExtensionPageServerTransport=w6,Re.InMemoryTransport=qs,Re.QrCode=a2,Re.ResourceTemplate=o6,Re.UriTemplate=en,Re.WebMcpClient=k0,Re.WebMcpServer=c6,Re.completable=YS,Re.createMessageChannelClientTransport=g6,Re.createMessageChannelPairTransport=d6,Re.createMessageChannelServerTransport=u6,Re.createRemoter=t5,Re.createSSEClientTransport=h6,Re.createSkillTools=zP,Re.createStreamableHTTPClientTransport=m6,Re.formatSkillsForSystemPrompt=DP,Re.getAISDKTools=O1,Re.getDisplayName=l6,Re.getMainSkillPathByName=rp,Re.getMainSkillPaths=ep,Re.getSkillMdContent=tp,Re.getSkillMdPaths=UP,Re.getSkillOverviews=jP,Re.isMcpClient=_6,Re.isMcpServer=f6,Re.isMessageChannelClientTransport=v6,Re.isMessageChannelServerTransport=p6,Re.isSSEClientTransport=y6,Re.isStreamableHTTPClientTransport=T0,Re.parseSkillFrontMatter=A1,Re.z=qb,Object.defineProperty(Re,Symbol.toStringTag,{value:"Module"})}));