@opentiny/next-sdk 0.2.4 → 0.2.6

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,kn){typeof exports=="object"&&typeof module<"u"?kn(exports):typeof define=="function"&&define.amd?define(["exports"],kn):(Oe=typeof globalThis<"u"?globalThis:Oe||self,kn(Oe.WebMCP={}))})(this,(function(Oe){"use strict";function kn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oa={exports:{}},ml={},Nr={},Tn={},gl={},yl={},vl={},Qd;function sa(){return Qd||(Qd=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,T)=>`${m}${T}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((m,T)=>(T instanceof r&&(m[T.str]=(m[T.str]||0)+1),m),{})}}e._Code=n,e.nil=new n("");function o(b,...v){const m=[b[0]];let T=0;for(;T<v.length;)i(m,v[T]),m.push(b[++T]);return new n(m)}e._=o;const s=new n("+");function a(b,...v){const m=[h(b[0])];let T=0;for(;T<v.length;)m.push(s),i(m,v[T]),m.push(s,h(b[++T]));return l(m),new n(m)}e.str=a;function i(b,v){v instanceof n?b.push(...v._items):v instanceof r?b.push(v):b.push(f(v))}e.addCodeArg=i;function l(b){let v=1;for(;v<b.length-1;){if(b[v]===s){const m=c(b[v-1],b[v+1]);if(m!==void 0){b.splice(v-1,3,m);continue}b[v++]="+"}v++}}function c(b,v){if(v==='""')return b;if(b==='""')return v;if(typeof b=="string")return v instanceof r||b[b.length-1]!=='"'?void 0:typeof v!="string"?`${b.slice(0,-1)}${v}"`:v[0]==='"'?b.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(b instanceof r))return`"${b}${v.slice(1)}`}function u(b,v){return v.emptyStr()?b:b.emptyStr()?v:a`${b}${v}`}e.strConcat=u;function f(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:h(Array.isArray(b)?b.join(","):b)}function p(b){return new n(h(b))}e.stringify=p;function h(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function y(b){return typeof b=="string"&&e.IDENTIFIER.test(b)?new n(`.${b}`):o`[${b}]`}e.getProperty=y;function w(b){if(typeof b=="string"&&e.IDENTIFIER.test(b))return new n(`${b}`);throw new Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}e.getEsmExportName=w;function g(b){return new n(b.toString())}e.regexpCode=g})(vl)),vl}var _l={},Xd;function ep(){return Xd||(Xd=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=sa();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,f;if(!((f=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||f===void 0)&&f.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:f}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${f}]`}}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 f;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:h}=p,y=(f=u.key)!==null&&f!==void 0?f:u.ref;let w=this._values[h];if(w){const v=w.get(y);if(v)return v}else w=this._values[h]=new Map;w.set(y,p);const g=this._scope[h]||(this._scope[h]=[]),b=g.length;return g[b]=u.ref,p.setValue(u,{property:h,itemIndex:b}),p}getValue(c,u){const f=this._values[c];if(f)return f.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,f)}_reduceValues(c,u,f={},p){let h=t.nil;for(const y in c){const w=c[y];if(!w)continue;const g=f[y]=f[y]||new Map;w.forEach(b=>{if(g.has(b))return;g.set(b,n.Started);let v=u(b);if(v){const m=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${m} ${b} = ${v};${this.opts._n}`}else if(v=p?.(b))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new r(b);g.set(b,n.Completed)})}return h}}e.ValueScope=i})(_l)),_l}var tp;function Ne(){return tp||(tp=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=sa(),r=ep();var n=sa();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=ep();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(I,E){return this}}class a extends s{constructor(I,E,V){super(),this.varKind=I,this.name=E,this.rhs=V}render({es5:I,_n:E}){const V=I?r.varKinds.var:this.varKind,te=this.rhs===void 0?"":` = ${this.rhs}`;return`${V} ${this.name}${te};`+E}optimizeNames(I,E){if(I[this.name.str])return this.rhs&&(this.rhs=L(this.rhs,I,E)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(I,E,V){super(),this.lhs=I,this.rhs=E,this.sideEffects=V}render({_n:I}){return`${this.lhs} = ${this.rhs};`+I}optimizeNames(I,E){if(!(this.lhs instanceof t.Name&&!I[this.lhs.str]&&!this.sideEffects))return this.rhs=L(this.rhs,I,E),this}get names(){const I=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(I,this.rhs)}}class l extends i{constructor(I,E,V,te){super(I,V,te),this.op=E}render({_n:I}){return`${this.lhs} ${this.op}= ${this.rhs};`+I}}class c extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`${this.label}:`+I}}class u extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`break${this.label?` ${this.label}`:""};`+I}}class f extends s{constructor(I){super(),this.error=I}render({_n:I}){return`throw ${this.error};`+I}get names(){return this.error.names}}class p extends s{constructor(I){super(),this.code=I}render({_n:I}){return`${this.code};`+I}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(I,E){return this.code=L(this.code,I,E),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(I=[]){super(),this.nodes=I}render(I){return this.nodes.reduce((E,V)=>E+V.render(I),"")}optimizeNodes(){const{nodes:I}=this;let E=I.length;for(;E--;){const V=I[E].optimizeNodes();Array.isArray(V)?I.splice(E,1,...V):V?I[E]=V:I.splice(E,1)}return I.length>0?this:void 0}optimizeNames(I,E){const{nodes:V}=this;let te=V.length;for(;te--;){const Q=V[te];Q.optimizeNames(I,E)||(Y(I,Q.names),V.splice(te,1))}return V.length>0?this:void 0}get names(){return this.nodes.reduce((I,E)=>O(I,E.names),{})}}class y extends h{render(I){return"{"+I._n+super.render(I)+"}"+I._n}}class w extends h{}class g extends y{}g.kind="else";class b extends y{constructor(I,E){super(E),this.condition=I}render(I){let E=`if(${this.condition})`+super.render(I);return this.else&&(E+="else "+this.else.render(I)),E}optimizeNodes(){super.optimizeNodes();const I=this.condition;if(I===!0)return this.nodes;let E=this.else;if(E){const V=E.optimizeNodes();E=this.else=Array.isArray(V)?new g(V):V}if(E)return I===!1?E instanceof b?E:E.nodes:this.nodes.length?this:new b(J(I),E instanceof b?[E]:E.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,E){var V;if(this.else=(V=this.else)===null||V===void 0?void 0:V.optimizeNames(I,E),!!(super.optimizeNames(I,E)||this.else))return this.condition=L(this.condition,I,E),this}get names(){const I=super.names;return A(I,this.condition),this.else&&O(I,this.else.names),I}}b.kind="if";class v extends y{}v.kind="for";class m extends v{constructor(I){super(),this.iteration=I}render(I){return`for(${this.iteration})`+super.render(I)}optimizeNames(I,E){if(super.optimizeNames(I,E))return this.iteration=L(this.iteration,I,E),this}get names(){return O(super.names,this.iteration.names)}}class T extends v{constructor(I,E,V,te){super(),this.varKind=I,this.name=E,this.from=V,this.to=te}render(I){const E=I.es5?r.varKinds.var:this.varKind,{name:V,from:te,to:Q}=this;return`for(${E} ${V}=${te}; ${V}<${Q}; ${V}++)`+super.render(I)}get names(){const I=A(super.names,this.from);return A(I,this.to)}}class k extends v{constructor(I,E,V,te){super(),this.loop=I,this.varKind=E,this.name=V,this.iterable=te}render(I){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(I)}optimizeNames(I,E){if(super.optimizeNames(I,E))return this.iterable=L(this.iterable,I,E),this}get names(){return O(super.names,this.iterable.names)}}class _ extends y{constructor(I,E,V){super(),this.name=I,this.args=E,this.async=V}render(I){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(I)}}_.kind="func";class S extends h{render(I){return"return "+super.render(I)}}S.kind="return";class $ extends y{render(I){let E="try"+super.render(I);return this.catch&&(E+=this.catch.render(I)),this.finally&&(E+=this.finally.render(I)),E}optimizeNodes(){var I,E;return super.optimizeNodes(),(I=this.catch)===null||I===void 0||I.optimizeNodes(),(E=this.finally)===null||E===void 0||E.optimizeNodes(),this}optimizeNames(I,E){var V,te;return super.optimizeNames(I,E),(V=this.catch)===null||V===void 0||V.optimizeNames(I,E),(te=this.finally)===null||te===void 0||te.optimizeNames(I,E),this}get names(){const I=super.names;return this.catch&&O(I,this.catch.names),this.finally&&O(I,this.finally.names),I}}class x extends y{constructor(I){super(),this.error=I}render(I){return`catch(${this.error})`+super.render(I)}}x.kind="catch";class U extends y{render(I){return"finally"+super.render(I)}}U.kind="finally";class M{constructor(I,E={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...E,_n:E.lines?`
2
- `:""},this._extScope=I,this._scope=new r.Scope({parent:I}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(I){return this._scope.name(I)}scopeName(I){return this._extScope.name(I)}scopeValue(I,E){const V=this._extScope.value(I,E);return(this._values[V.prefix]||(this._values[V.prefix]=new Set)).add(V),V}getScopeValue(I,E){return this._extScope.getValue(I,E)}scopeRefs(I){return this._extScope.scopeRefs(I,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(I,E,V,te){const Q=this._scope.toName(E);return V!==void 0&&te&&(this._constants[Q.str]=V),this._leafNode(new a(I,Q,V)),Q}const(I,E,V){return this._def(r.varKinds.const,I,E,V)}let(I,E,V){return this._def(r.varKinds.let,I,E,V)}var(I,E,V){return this._def(r.varKinds.var,I,E,V)}assign(I,E,V){return this._leafNode(new i(I,E,V))}add(I,E){return this._leafNode(new l(I,e.operators.ADD,E))}code(I){return typeof I=="function"?I():I!==t.nil&&this._leafNode(new p(I)),this}object(...I){const E=["{"];for(const[V,te]of I)E.length>1&&E.push(","),E.push(V),(V!==te||this.opts.es5)&&(E.push(":"),(0,t.addCodeArg)(E,te));return E.push("}"),new t._Code(E)}if(I,E,V){if(this._blockNode(new b(I)),E&&V)this.code(E).else().code(V).endIf();else if(E)this.code(E).endIf();else if(V)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(I){return this._elseNode(new b(I))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(b,g)}_for(I,E){return this._blockNode(I),E&&this.code(E).endFor(),this}for(I,E){return this._for(new m(I),E)}forRange(I,E,V,te,Q=this.opts.es5?r.varKinds.var:r.varKinds.let){const _e=this._scope.toName(I);return this._for(new T(Q,_e,E,V),()=>te(_e))}forOf(I,E,V,te=r.varKinds.const){const Q=this._scope.toName(I);if(this.opts.es5){const _e=E instanceof t.Name?E:this.var("_arr",E);return this.forRange("_i",0,(0,t._)`${_e}.length`,xe=>{this.var(Q,(0,t._)`${_e}[${xe}]`),V(Q)})}return this._for(new k("of",te,Q,E),()=>V(Q))}forIn(I,E,V,te=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(I,(0,t._)`Object.keys(${E})`,V);const Q=this._scope.toName(I);return this._for(new k("in",te,Q,E),()=>V(Q))}endFor(){return this._endBlockNode(v)}label(I){return this._leafNode(new c(I))}break(I){return this._leafNode(new u(I))}return(I){const E=new S;if(this._blockNode(E),this.code(I),E.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(I,E,V){if(!E&&!V)throw new Error('CodeGen: "try" without "catch" and "finally"');const te=new $;if(this._blockNode(te),this.code(I),E){const Q=this.name("e");this._currNode=te.catch=new x(Q),E(Q)}return V&&(this._currNode=te.finally=new U,this.code(V)),this._endBlockNode(x,U)}throw(I){return this._leafNode(new f(I))}block(I,E){return this._blockStarts.push(this._nodes.length),I&&this.code(I).endBlock(E),this}endBlock(I){const E=this._blockStarts.pop();if(E===void 0)throw new Error("CodeGen: not in self-balancing block");const V=this._nodes.length-E;if(V<0||I!==void 0&&V!==I)throw new Error(`CodeGen: wrong number of nodes: ${V} vs ${I} expected`);return this._nodes.length=E,this}func(I,E=t.nil,V,te){return this._blockNode(new _(I,E,V)),te&&this.code(te).endFunc(),this}endFunc(){return this._endBlockNode(_)}optimize(I=1){for(;I-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(I){return this._currNode.nodes.push(I),this}_blockNode(I){this._currNode.nodes.push(I),this._nodes.push(I)}_endBlockNode(I,E){const V=this._currNode;if(V instanceof I||E&&V instanceof E)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${E?`${I.kind}/${E.kind}`:I.kind}"`)}_elseNode(I){const E=this._currNode;if(!(E instanceof b))throw new Error('CodeGen: "else" without "if"');return this._currNode=E.else=I,this}get _root(){return this._nodes[0]}get _currNode(){const I=this._nodes;return I[I.length-1]}set _currNode(I){const E=this._nodes;E[E.length-1]=I}}e.CodeGen=M;function O(z,I){for(const E in I)z[E]=(z[E]||0)+(I[E]||0);return z}function A(z,I){return I instanceof t._CodeOrName?O(z,I.names):z}function L(z,I,E){if(z instanceof t.Name)return V(z);if(!te(z))return z;return new t._Code(z._items.reduce((Q,_e)=>(_e instanceof t.Name&&(_e=V(_e)),_e instanceof t._Code?Q.push(..._e._items):Q.push(_e),Q),[]));function V(Q){const _e=E[Q.str];return _e===void 0||I[Q.str]!==1?Q:(delete I[Q.str],_e)}function te(Q){return Q instanceof t._Code&&Q._items.some(_e=>_e instanceof t.Name&&I[_e.str]===1&&E[_e.str]!==void 0)}}function Y(z,I){for(const E in I)z[E]=(z[E]||0)-(I[E]||0)}function J(z){return typeof z=="boolean"||typeof z=="number"||z===null?!z:(0,t._)`!${H(z)}`}e.not=J;const de=N(e.operators.AND);function K(...z){return z.reduce(de)}e.and=K;const $e=N(e.operators.OR);function Z(...z){return z.reduce($e)}e.or=Z;function N(z){return(I,E)=>I===t.nil?E:E===t.nil?I:(0,t._)`${H(I)} ${z} ${H(E)}`}function H(z){return z instanceof t.Name?z:(0,t._)`(${z})`}})(yl)),yl}var qe={},rp;function Ze(){if(rp)return qe;rp=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=Ne(),t=sa();function r(k){const _={};for(const S of k)_[S]=!0;return _}qe.toHash=r;function n(k,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(o(k,_),!s(_,k.self.RULES.all))}qe.alwaysValidSchema=n;function o(k,_=k.schema){const{opts:S,self:$}=k;if(!S.strictSchema||typeof _=="boolean")return;const x=$.RULES.keywords;for(const U in _)x[U]||T(k,`unknown keyword: "${U}"`)}qe.checkUnknownRules=o;function s(k,_){if(typeof k=="boolean")return!k;for(const S in k)if(_[S])return!0;return!1}qe.schemaHasRules=s;function a(k,_){if(typeof k=="boolean")return!k;for(const S in k)if(S!=="$ref"&&_.all[S])return!0;return!1}qe.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:_},S,$,x){if(!x){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${k}${_}${(0,e.getProperty)($)}`}qe.schemaRefOrVal=i;function l(k){return f(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 f(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}qe.unescapeJsonPointer=f;function p(k,_){if(Array.isArray(k))for(const S of k)_(S);else _(k)}qe.eachItem=p;function h({mergeNames:k,mergeToName:_,mergeValues:S,resultToName:$}){return(x,U,M,O)=>{const A=M===void 0?U:M instanceof e.Name?(U instanceof e.Name?k(x,U,M):_(x,U,M),M):U instanceof e.Name?(_(x,M,U),U):S(U,M);return O===e.Name&&!(A instanceof e.Name)?$(x,A):A}}qe.mergeEvaluated={props:h({mergeNames:(k,_,S)=>k.if((0,e._)`${S} !== true && ${_} !== undefined`,()=>{k.if((0,e._)`${_} === true`,()=>k.assign(S,!0),()=>k.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${_})`))}),mergeToName:(k,_,S)=>k.if((0,e._)`${S} !== true`,()=>{_===!0?k.assign(S,!0):(k.assign(S,(0,e._)`${S} || {}`),w(k,S,_))}),mergeValues:(k,_)=>k===!0?!0:{...k,..._},resultToName:y}),items:h({mergeNames:(k,_,S)=>k.if((0,e._)`${S} !== true && ${_} !== undefined`,()=>k.assign(S,(0,e._)`${_} === true ? true : ${S} > ${_} ? ${S} : ${_}`)),mergeToName:(k,_,S)=>k.if((0,e._)`${S} !== true`,()=>k.assign(S,_===!0?!0:(0,e._)`${S} > ${_} ? ${S} : ${_}`)),mergeValues:(k,_)=>k===!0?!0:Math.max(k,_),resultToName:(k,_)=>k.var("items",_)})};function y(k,_){if(_===!0)return k.var("props",!0);const S=k.var("props",(0,e._)`{}`);return _!==void 0&&w(k,S,_),S}qe.evaluatedPropsToName=y;function w(k,_,S){Object.keys(S).forEach($=>k.assign((0,e._)`${_}${(0,e.getProperty)($)}`,!0))}qe.setEvaluated=w;const g={};function b(k,_){return k.scopeValue("func",{ref:_,code:g[_.code]||(g[_.code]=new t._Code(_.code))})}qe.useFunc=b;var v;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(v||(qe.Type=v={}));function m(k,_,S){if(k instanceof e.Name){const $=_===v.Num;return S?$?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:$?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(k).toString():"/"+u(k)}qe.getErrorPath=m;function T(k,_,S=k.opts.strictSchema){if(S){if(_=`strict mode: ${_}`,S===!0)throw new Error(_);k.self.logger.warn(_)}}return qe.checkStrictMode=T,qe}var aa={},np;function en(){if(np)return aa;np=1,Object.defineProperty(aa,"__esModule",{value:!0});const e=Ne(),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 aa.default=t,aa}var op;function ia(){return op||(op=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=Ne(),r=Ze(),n=en();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:b})=>b?(0,t.str)`"${g}" keyword must be ${b} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function o(g,b=e.keywordError,v,m){const{it:T}=g,{gen:k,compositeRule:_,allErrors:S}=T,$=f(g,b,v);m??(_||S)?l(k,$):c(T,(0,t._)`[${$}]`)}e.reportError=o;function s(g,b=e.keywordError,v){const{it:m}=g,{gen:T,compositeRule:k,allErrors:_}=m,S=f(g,b,v);l(T,S),k||_||c(m,n.default.vErrors)}e.reportExtraError=s;function a(g,b){g.assign(n.default.errors,b),g.if((0,t._)`${n.default.vErrors} !== null`,()=>g.if(b,()=>g.assign((0,t._)`${n.default.vErrors}.length`,b),()=>g.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:g,keyword:b,schemaValue:v,data:m,errsCount:T,it:k}){if(T===void 0)throw new Error("ajv implementation error");const _=g.name("err");g.forRange("i",T,n.default.errors,S=>{g.const(_,(0,t._)`${n.default.vErrors}[${S}]`),g.if((0,t._)`${_}.instancePath === undefined`,()=>g.assign((0,t._)`${_}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),g.assign((0,t._)`${_}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${b}`),k.opts.verbose&&(g.assign((0,t._)`${_}.schema`,v),g.assign((0,t._)`${_}.data`,m))})}e.extendErrors=i;function l(g,b){const v=g.const("err",b);g.if((0,t._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),g.code((0,t._)`${n.default.errors}++`)}function c(g,b){const{gen:v,validateName:m,schemaEnv:T}=g;T.$async?v.throw((0,t._)`new ${g.ValidationError}(${b})`):(v.assign((0,t._)`${m}.errors`,b),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 f(g,b,v){const{createErrors:m}=g.it;return m===!1?(0,t._)`{}`:p(g,b,v)}function p(g,b,v={}){const{gen:m,it:T}=g,k=[h(T,v),y(g,v)];return w(g,b,k),m.object(...k)}function h({errorPath:g},{instancePath:b}){const v=b?(0,t.str)`${g}${(0,r.getErrorPath)(b,r.Type.Str)}`:g;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function y({keyword:g,it:{errSchemaPath:b}},{schemaPath:v,parentSchema:m}){let T=m?b:(0,t.str)`${b}/${g}`;return v&&(T=(0,t.str)`${T}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,T]}function w(g,{params:b,message:v},m){const{keyword:T,data:k,schemaValue:_,it:S}=g,{opts:$,propertyName:x,topSchemaRef:U,schemaPath:M}=S;m.push([u.keyword,T],[u.params,typeof b=="function"?b(g):b||(0,t._)`{}`]),$.messages&&m.push([u.message,typeof v=="function"?v(g):v]),$.verbose&&m.push([u.schema,_],[u.parentSchema,(0,t._)`${U}${M}`],[n.default.data,k]),x&&m.push([u.propertyName,x])}})(gl)),gl}var sp;function E1(){if(sp)return Tn;sp=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.boolOrEmptySchema=Tn.topBoolOrEmptySchema=void 0;const e=ia(),t=Ne(),r=en(),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))}Tn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Tn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,f={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(f,n,void 0,l)}return Tn}var _t={},Cn={},ap;function ip(){if(ap)return Cn;ap=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.getRules=Cn.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)}Cn.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 Cn.getRules=n,Cn}var qr={},lp;function cp(){if(lp)return qr;lp=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.shouldUseRule=qr.shouldUseGroup=qr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}qr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}qr.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 qr.shouldUseRule=r,qr}var up;function la(){if(up)return _t;up=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.reportTypeError=_t.checkDataTypes=_t.checkDataType=_t.coerceAndCheckDataType=_t.getJSONTypes=_t.getSchemaTypes=_t.DataType=void 0;const e=ip(),t=cp(),r=ia(),n=Ne(),o=Ze();var s;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(s||(_t.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}_t.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(","))}_t.getJSONTypes=i;function l(v,m){const{gen:T,data:k,opts:_}=v,S=u(m,_.coerceTypes),$=m.length>0&&!(S.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(v,m[0]));if($){const x=y(m,k,_.strictNumbers,s.Wrong);T.if(x,()=>{S.length?f(v,m,S):g(v)})}return $}_t.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,m){return m?v.filter(T=>c.has(T)||m==="array"&&T==="array"):[]}function f(v,m,T){const{gen:k,data:_,opts:S}=v,$=k.let("dataType",(0,n._)`typeof ${_}`),x=k.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&k.if((0,n._)`${$} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>k.assign(_,(0,n._)`${_}[0]`).assign($,(0,n._)`typeof ${_}`).if(y(m,_,S.strictNumbers),()=>k.assign(x,_))),k.if((0,n._)`${x} !== undefined`);for(const M of T)(c.has(M)||M==="array"&&S.coerceTypes==="array")&&U(M);k.else(),g(v),k.endIf(),k.if((0,n._)`${x} !== undefined`,()=>{k.assign(_,x),p(v,x)});function U(M){switch(M){case"string":k.elseIf((0,n._)`${$} == "number" || ${$} == "boolean"`).assign(x,(0,n._)`"" + ${_}`).elseIf((0,n._)`${_} === null`).assign(x,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${$} == "boolean" || ${_} === null
3
- || (${$} == "string" && ${_} && ${_} == +${_})`).assign(x,(0,n._)`+${_}`);return;case"integer":k.elseIf((0,n._)`${$} === "boolean" || ${_} === null
4
- || (${$} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(x,(0,n._)`+${_}`);return;case"boolean":k.elseIf((0,n._)`${_} === "false" || ${_} === 0 || ${_} === null`).assign(x,!1).elseIf((0,n._)`${_} === "true" || ${_} === 1`).assign(x,!0);return;case"null":k.elseIf((0,n._)`${_} === "" || ${_} === 0 || ${_} === false`),k.assign(x,null);return;case"array":k.elseIf((0,n._)`${$} === "string" || ${$} === "number"
5
- || ${$} === "boolean" || ${_} === null`).assign(x,(0,n._)`[${_}]`)}}}function p({gen:v,parentData:m,parentDataProperty:T},k){v.if((0,n._)`${m} !== undefined`,()=>v.assign((0,n._)`${m}[${T}]`,k))}function h(v,m,T,k=s.Correct){const _=k===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(v){case"null":return(0,n._)`${m} ${_} null`;case"array":S=(0,n._)`Array.isArray(${m})`;break;case"object":S=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":S=$((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":S=$();break;default:return(0,n._)`typeof ${m} ${_} ${v}`}return k===s.Correct?S:(0,n.not)(S);function $(x=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,x,T?(0,n._)`isFinite(${m})`:n.nil)}}_t.checkDataType=h;function y(v,m,T,k){if(v.length===1)return h(v[0],m,T,k);let _;const S=(0,o.toHash)(v);if(S.array&&S.object){const $=(0,n._)`typeof ${m} != "object"`;_=S.null?$:(0,n._)`!${m} || ${$}`,delete S.null,delete S.array,delete S.object}else _=n.nil;S.number&&delete S.integer;for(const $ in S)_=(0,n.and)(_,h($,m,T,k));return _}_t.checkDataTypes=y;const w={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:m})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${m}}`};function g(v){const m=b(v);(0,r.reportError)(m,w)}_t.reportTypeError=g;function b(v){const{gen:m,data:T,schema:k}=v,_=(0,o.schemaRefOrVal)(v,k,"type");return{gen:m,keyword:"type",data:T,schema:k.type,schemaCode:_,schemaValue:_,parentSchema:k,params:{},it:v}}return _t}var Ao={},dp;function x1(){if(dp)return Ao;dp=1,Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.assignDefaults=void 0;const e=Ne(),t=Ze();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))}Ao.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const f=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),i.if(p,(0,e._)`${f} = ${(0,e.stringify)(a)}`)}return Ao}var ar={},We={},pp;function ir(){if(pp)return We;pp=1,Object.defineProperty(We,"__esModule",{value:!0}),We.validateUnion=We.validateArray=We.usePattern=We.callValidateCode=We.schemaProperties=We.allSchemaProperties=We.noPropertyInData=We.propertyInData=We.isOwnProperty=We.hasPropFunc=We.reportMissingProp=We.checkMissingProp=We.checkReportMissingProp=void 0;const e=Ne(),t=Ze(),r=en(),n=Ze();function o(v,m){const{gen:T,data:k,it:_}=v;T.if(u(T,k,m,_.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${m}`},!0),v.error()})}We.checkReportMissingProp=o;function s({gen:v,data:m,it:{opts:T}},k,_){return(0,e.or)(...k.map(S=>(0,e.and)(u(v,m,S,T.ownProperties),(0,e._)`${_} = ${S}`)))}We.checkMissingProp=s;function a(v,m){v.setParams({missingProperty:m},!0),v.error()}We.reportMissingProp=a;function i(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}We.hasPropFunc=i;function l(v,m,T){return(0,e._)`${i(v)}.call(${m}, ${T})`}We.isOwnProperty=l;function c(v,m,T,k){const _=(0,e._)`${m}${(0,e.getProperty)(T)} !== undefined`;return k?(0,e._)`${_} && ${l(v,m,T)}`:_}We.propertyInData=c;function u(v,m,T,k){const _=(0,e._)`${m}${(0,e.getProperty)(T)} === undefined`;return k?(0,e.or)(_,(0,e.not)(l(v,m,T))):_}We.noPropertyInData=u;function f(v){return v?Object.keys(v).filter(m=>m!=="__proto__"):[]}We.allSchemaProperties=f;function p(v,m){return f(m).filter(T=>!(0,t.alwaysValidSchema)(v,m[T]))}We.schemaProperties=p;function h({schemaCode:v,data:m,it:{gen:T,topSchemaRef:k,schemaPath:_,errorPath:S},it:$},x,U,M){const O=M?(0,e._)`${v}, ${m}, ${k}${_}`:m,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,$.parentData],[r.default.parentDataProperty,$.parentDataProperty],[r.default.rootData,r.default.rootData]];$.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const L=(0,e._)`${O}, ${T.object(...A)}`;return U!==e.nil?(0,e._)`${x}.call(${U}, ${L})`:(0,e._)`${x}(${L})`}We.callValidateCode=h;const y=(0,e._)`new RegExp`;function w({gen:v,it:{opts:m}},T){const k=m.unicodeRegExp?"u":"",{regExp:_}=m.code,S=_(T,k);return v.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${_.code==="new RegExp"?y:(0,n.useFunc)(v,_)}(${T}, ${k})`})}We.usePattern=w;function g(v){const{gen:m,data:T,keyword:k,it:_}=v,S=m.name("valid");if(_.allErrors){const x=m.let("valid",!0);return $(()=>m.assign(x,!1)),x}return m.var(S,!0),$(()=>m.break()),S;function $(x){const U=m.const("len",(0,e._)`${T}.length`);m.forRange("i",0,U,M=>{v.subschema({keyword:k,dataProp:M,dataPropType:t.Type.Num},S),m.if((0,e.not)(S),x)})}}We.validateArray=g;function b(v){const{gen:m,schema:T,keyword:k,it:_}=v;if(!Array.isArray(T))throw new Error("ajv implementation error");if(T.some(U=>(0,t.alwaysValidSchema)(_,U))&&!_.opts.unevaluated)return;const $=m.let("valid",!1),x=m.name("_valid");m.block(()=>T.forEach((U,M)=>{const O=v.subschema({keyword:k,schemaProp:M,compositeRule:!0},x);m.assign($,(0,e._)`${$} || ${x}`),v.mergeValidEvaluated(O,x)||m.if((0,e.not)($))})),v.result($,()=>v.reset(),()=>v.error(!0))}return We.validateUnion=b,We}var fp;function $1(){if(fp)return ar;fp=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.validateKeywordUsage=ar.validSchemaType=ar.funcKeywordCode=ar.macroKeywordCode=void 0;const e=Ne(),t=en(),r=ir(),n=ia();function o(p,h){const{gen:y,keyword:w,schema:g,parentSchema:b,it:v}=p,m=h.macro.call(v.self,g,b,v),T=c(y,w,m);v.opts.validateSchema!==!1&&v.self.validateSchema(m,!0);const k=y.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${w}`,topSchemaRef:T,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}ar.macroKeywordCode=o;function s(p,h){var y;const{gen:w,keyword:g,schema:b,parentSchema:v,$data:m,it:T}=p;l(T,h);const k=!m&&h.compile?h.compile.call(T.self,b,v,T):h.validate,_=c(w,g,k),S=w.let("valid");p.block$data(S,$),p.ok((y=h.valid)!==null&&y!==void 0?y:S);function $(){if(h.errors===!1)M(),h.modifying&&a(p),O(()=>p.error());else{const A=h.async?x():U();h.modifying&&a(p),O(()=>i(p,A))}}function x(){const A=w.let("ruleErrs",null);return w.try(()=>M((0,e._)`await `),L=>w.assign(S,!1).if((0,e._)`${L} instanceof ${T.ValidationError}`,()=>w.assign(A,(0,e._)`${L}.errors`),()=>w.throw(L))),A}function U(){const A=(0,e._)`${_}.errors`;return w.assign(A,null),M(e.nil),A}function M(A=h.async?(0,e._)`await `:e.nil){const L=T.opts.passContext?t.default.this:t.default.self,Y=!("compile"in h&&!m||h.schema===!1);w.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,_,L,Y)}`,h.modifying)}function O(A){var L;w.if((0,e.not)((L=h.valid)!==null&&L!==void 0?L:S),A)}}ar.funcKeywordCode=s;function a(p){const{gen:h,data:y,it:w}=p;h.if(w.parentData,()=>h.assign(y,(0,e._)`${w.parentData}[${w.parentDataProperty}]`))}function i(p,h){const{gen:y}=p;y.if((0,e._)`Array.isArray(${h})`,()=>{y.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,h,y){if(y===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof y=="function"?{ref:y}:{ref:y,code:(0,e.stringify)(y)})}function u(p,h,y=!1){return!h.length||h.some(w=>w==="array"?Array.isArray(p):w==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==w||y&&typeof p>"u")}ar.validSchemaType=u;function f({schema:p,opts:h,self:y,errSchemaPath:w},g,b){if(Array.isArray(g.keyword)?!g.keyword.includes(b):g.keyword!==b)throw new Error("ajv implementation error");const v=g.dependencies;if(v?.some(m=>!Object.prototype.hasOwnProperty.call(p,m)))throw new Error(`parent schema must have dependencies of ${b}: ${v.join(",")}`);if(g.validateSchema&&!g.validateSchema(p[b])){const T=`keyword "${b}" value is invalid at path "${w}": `+y.errorsText(g.validateSchema.errors);if(h.validateSchema==="log")y.logger.error(T);else throw new Error(T)}}return ar.validateKeywordUsage=f,ar}var Lr={},hp;function R1(){if(hp)return Lr;hp=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.extendSubschemaMode=Lr.extendSubschemaData=Lr.getSubschema=void 0;const e=Ne(),t=Ze();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:f}){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||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:f,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Lr.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:f}){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:y,dataPathArr:w,opts:g}=a,b=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);h(b),s.errorPath=(0,e.str)`${y}${(0,t.getErrorPath)(i,l,g.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...w,s.parentDataProperty]}if(c!==void 0){const y=c instanceof e.Name?c:p.let("data",c,!0);h(y),f!==void 0&&(s.propertyName=f)}u&&(s.dataTypes=u);function h(y){s.data=y,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,y]}}Lr.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 Lr.extendSubschemaMode=o,Lr}var Pt={},wl,mp;function gp(){return mp||(mp=1,wl=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}),wl}var bl={exports:{}},yp;function P1(){if(yp)return bl.exports;yp=1;var e=bl.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,f,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,f,p);for(var h in a){var y=a[h];if(Array.isArray(y)){if(h in e.arrayKeywords)for(var w=0;w<y.length;w++)t(n,o,s,y[w],i+"/"+h+"/"+w,l,i,h,a,w)}else if(h in e.propsKeywords){if(y&&typeof y=="object")for(var g in y)t(n,o,s,y[g],i+"/"+h+"/"+r(g),l,i,h,a,g)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,s,y,i+"/"+h,l,i,h,a)}s(a,i,l,c,u,f,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return bl.exports}var vp;function ca(){if(vp)return Pt;vp=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.getSchemaRefs=Pt.resolveUrl=Pt.normalizeId=Pt._getFullPath=Pt.getFullPath=Pt.inlineRef=void 0;const e=Ze(),t=gp(),r=P1(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(w,g=!0){return typeof w=="boolean"?!0:g===!0?!a(w):g?i(w)<=g:!1}Pt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(w){for(const g in w){if(s.has(g))return!0;const b=w[g];if(Array.isArray(b)&&b.some(a)||typeof b=="object"&&a(b))return!0}return!1}function i(w){let g=0;for(const b in w){if(b==="$ref")return 1/0;if(g++,!n.has(b)&&(typeof w[b]=="object"&&(0,e.eachItem)(w[b],v=>g+=i(v)),g===1/0))return 1/0}return g}function l(w,g="",b){b!==!1&&(g=f(g));const v=w.parse(g);return c(w,v)}Pt.getFullPath=l;function c(w,g){return w.serialize(g).split("#")[0]+"#"}Pt._getFullPath=c;const u=/#\/?$/;function f(w){return w?w.replace(u,""):""}Pt.normalizeId=f;function p(w,g,b){return b=f(b),w.resolve(g,b)}Pt.resolveUrl=p;const h=/^[a-z_][-a-z0-9._]*$/i;function y(w,g){if(typeof w=="boolean")return{};const{schemaId:b,uriResolver:v}=this.opts,m=f(w[b]||g),T={"":m},k=l(v,m,!1),_={},S=new Set;return r(w,{allKeys:!0},(U,M,O,A)=>{if(A===void 0)return;const L=k+M;let Y=T[A];typeof U[b]=="string"&&(Y=J.call(this,U[b])),de.call(this,U.$anchor),de.call(this,U.$dynamicAnchor),T[M]=Y;function J(K){const $e=this.opts.uriResolver.resolve;if(K=f(Y?$e(Y,K):K),S.has(K))throw x(K);S.add(K);let Z=this.refs[K];return typeof Z=="string"&&(Z=this.refs[Z]),typeof Z=="object"?$(U,Z.schema,K):K!==f(L)&&(K[0]==="#"?($(U,_[K],K),_[K]=U):this.refs[K]=L),K}function de(K){if(typeof K=="string"){if(!h.test(K))throw new Error(`invalid anchor "${K}"`);J.call(this,`#${K}`)}}}),_;function $(U,M,O){if(M!==void 0&&!t(U,M))throw x(O)}function x(U){return new Error(`reference "${U}" resolves to more than one schema`)}}return Pt.getSchemaRefs=y,Pt}var _p;function ua(){if(_p)return Nr;_p=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.getData=Nr.KeywordCxt=Nr.validateFunctionCode=void 0;const e=E1(),t=la(),r=cp(),n=la(),o=x1(),s=$1(),a=R1(),i=Ne(),l=en(),c=ca(),u=Ze(),f=ia();function p(D){if(k(D)&&(S(D),T(D))){g(D);return}h(D,()=>(0,e.topBoolOrEmptySchema)(D))}Nr.validateFunctionCode=p;function h({gen:D,validateName:F,schema:G,schemaEnv:ee,opts:pe},ke){pe.code.es5?D.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,ee.$async,()=>{D.code((0,i._)`"use strict"; ${v(G,pe)}`),w(D,pe),D.code(ke)}):D.func(F,(0,i._)`${l.default.data}, ${y(pe)}`,ee.$async,()=>D.code(v(G,pe)).code(ke))}function y(D){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${D.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(D,F){D.if(l.default.valCxt,()=>{D.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),D.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),D.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),D.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&D.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{D.var(l.default.instancePath,(0,i._)`""`),D.var(l.default.parentData,(0,i._)`undefined`),D.var(l.default.parentDataProperty,(0,i._)`undefined`),D.var(l.default.rootData,l.default.data),F.dynamicRef&&D.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function g(D){const{schema:F,opts:G,gen:ee}=D;h(D,()=>{G.$comment&&F.$comment&&A(D),U(D),ee.let(l.default.vErrors,null),ee.let(l.default.errors,0),G.unevaluated&&b(D),$(D),L(D)})}function b(D){const{gen:F,validateName:G}=D;D.evaluated=F.const("evaluated",(0,i._)`${G}.evaluated`),F.if((0,i._)`${D.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${D.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${D.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${D.evaluated}.items`,(0,i._)`undefined`))}function v(D,F){const G=typeof D=="object"&&D[F.schemaId];return G&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function m(D,F){if(k(D)&&(S(D),T(D))){_(D,F);return}(0,e.boolOrEmptySchema)(D,F)}function T({schema:D,self:F}){if(typeof D=="boolean")return!D;for(const G in D)if(F.RULES.all[G])return!0;return!1}function k(D){return typeof D.schema!="boolean"}function _(D,F){const{schema:G,gen:ee,opts:pe}=D;pe.$comment&&G.$comment&&A(D),M(D),O(D);const ke=ee.const("_errs",l.default.errors);$(D,ke),ee.var(F,(0,i._)`${ke} === ${l.default.errors}`)}function S(D){(0,u.checkUnknownRules)(D),x(D)}function $(D,F){if(D.opts.jtd)return J(D,[],!1,F);const G=(0,t.getSchemaTypes)(D.schema),ee=(0,t.coerceAndCheckDataType)(D,G);J(D,G,!ee,F)}function x(D){const{schema:F,errSchemaPath:G,opts:ee,self:pe}=D;F.$ref&&ee.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,pe.RULES)&&pe.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function U(D){const{schema:F,opts:G}=D;F.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(D,"default is ignored in the schema root")}function M(D){const F=D.schema[D.opts.schemaId];F&&(D.baseId=(0,c.resolveUrl)(D.opts.uriResolver,D.baseId,F))}function O(D){if(D.schema.$async&&!D.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:D,schemaEnv:F,schema:G,errSchemaPath:ee,opts:pe}){const ke=G.$comment;if(pe.$comment===!0)D.code((0,i._)`${l.default.self}.logger.log(${ke})`);else if(typeof pe.$comment=="function"){const R=(0,i.str)`${ee}/$comment`,re=D.scopeValue("root",{ref:F.root});D.code((0,i._)`${l.default.self}.opts.$comment(${ke}, ${R}, ${re}.schema)`)}}function L(D){const{gen:F,schemaEnv:G,validateName:ee,ValidationError:pe,opts:ke}=D;G.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${pe}(${l.default.vErrors})`)):(F.assign((0,i._)`${ee}.errors`,l.default.vErrors),ke.unevaluated&&Y(D),F.return((0,i._)`${l.default.errors} === 0`))}function Y({gen:D,evaluated:F,props:G,items:ee}){G instanceof i.Name&&D.assign((0,i._)`${F}.props`,G),ee instanceof i.Name&&D.assign((0,i._)`${F}.items`,ee)}function J(D,F,G,ee){const{gen:pe,schema:ke,data:R,allErrors:re,opts:ve,self:Te}=D,{RULES:Re}=Te;if(ke.$ref&&(ve.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ke,Re))){pe.block(()=>te(D,"$ref",Re.all.$ref.definition));return}ve.jtd||K(D,F),pe.block(()=>{for(const ie of Re.rules)Xe(ie);Xe(Re.post)});function Xe(ie){(0,r.shouldUseGroup)(ke,ie)&&(ie.type?(pe.if((0,n.checkDataType)(ie.type,R,ve.strictNumbers)),de(D,ie),F.length===1&&F[0]===ie.type&&G&&(pe.else(),(0,n.reportTypeError)(D)),pe.endIf()):de(D,ie),re||pe.if((0,i._)`${l.default.errors} === ${ee||0}`))}}function de(D,F){const{gen:G,schema:ee,opts:{useDefaults:pe}}=D;pe&&(0,o.assignDefaults)(D,F.type),G.block(()=>{for(const ke of F.rules)(0,r.shouldUseRule)(ee,ke)&&te(D,ke.keyword,ke.definition,F.type)})}function K(D,F){D.schemaEnv.meta||!D.opts.strictTypes||($e(D,F),D.opts.allowUnionTypes||Z(D,F),N(D,D.dataTypes))}function $e(D,F){if(F.length){if(!D.dataTypes.length){D.dataTypes=F;return}F.forEach(G=>{z(D.dataTypes,G)||E(D,`type "${G}" not allowed by context "${D.dataTypes.join(",")}"`)}),I(D,F)}}function Z(D,F){F.length>1&&!(F.length===2&&F.includes("null"))&&E(D,"use allowUnionTypes to allow union type keyword")}function N(D,F){const G=D.self.RULES.all;for(const ee in G){const pe=G[ee];if(typeof pe=="object"&&(0,r.shouldUseRule)(D.schema,pe)){const{type:ke}=pe.definition;ke.length&&!ke.some(R=>H(F,R))&&E(D,`missing type "${ke.join(",")}" for keyword "${ee}"`)}}}function H(D,F){return D.includes(F)||F==="number"&&D.includes("integer")}function z(D,F){return D.includes(F)||F==="integer"&&D.includes("number")}function I(D,F){const G=[];for(const ee of D.dataTypes)z(F,ee)?G.push(ee):F.includes("integer")&&ee==="number"&&G.push("integer");D.dataTypes=G}function E(D,F){const G=D.schemaEnv.baseId+D.errSchemaPath;F+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(D,F,D.opts.strictTypes)}class V{constructor(F,G,ee){if((0,s.validateKeywordUsage)(F,G,ee),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=ee,this.data=F.data,this.schema=F.schema[ee],this.$data=G.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,ee,this.$data),this.schemaType=G.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=G,this.$data)this.schemaCode=F.gen.const("vSchema",xe(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${ee} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,G,ee){this.failResult((0,i.not)(F),G,ee)}failResult(F,G,ee){this.gen.if(F),ee?ee():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,G){this.failResult((0,i.not)(F),void 0,G)}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:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,G,ee){if(G){this.setParams(G),this._error(F,ee),this.setParams({});return}this._error(F,ee)}_error(F,G){(F?f.reportExtraError:f.reportError)(this,this.def.error,G)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,G){G?Object.assign(this.params,F):this.params=F}block$data(F,G,ee=i.nil){this.gen.block(()=>{this.check$data(F,ee),G()})}check$data(F=i.nil,G=i.nil){if(!this.$data)return;const{gen:ee,schemaCode:pe,schemaType:ke,def:R}=this;ee.if((0,i.or)((0,i._)`${pe} === undefined`,G)),F!==i.nil&&ee.assign(F,!0),(ke.length||R.validateSchema)&&(ee.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&ee.assign(F,!1)),ee.else()}invalid$data(){const{gen:F,schemaCode:G,schemaType:ee,def:pe,it:ke}=this;return(0,i.or)(R(),re());function R(){if(ee.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const ve=Array.isArray(ee)?ee:[ee];return(0,i._)`${(0,n.checkDataTypes)(ve,G,ke.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function re(){if(pe.validateSchema){const ve=F.scopeValue("validate$data",{ref:pe.validateSchema});return(0,i._)`!${ve}(${G})`}return i.nil}}subschema(F,G){const ee=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(ee,this.it,F),(0,a.extendSubschemaMode)(ee,F);const pe={...this.it,...ee,items:void 0,props:void 0};return m(pe,G),pe}mergeEvaluated(F,G){const{it:ee,gen:pe}=this;ee.opts.unevaluated&&(ee.props!==!0&&F.props!==void 0&&(ee.props=u.mergeEvaluated.props(pe,F.props,ee.props,G)),ee.items!==!0&&F.items!==void 0&&(ee.items=u.mergeEvaluated.items(pe,F.items,ee.items,G)))}mergeValidEvaluated(F,G){const{it:ee,gen:pe}=this;if(ee.opts.unevaluated&&(ee.props!==!0||ee.items!==!0))return pe.if(G,()=>this.mergeEvaluated(F,i.Name)),!0}}Nr.KeywordCxt=V;function te(D,F,G,ee){const pe=new V(D,G,F);"code"in G?G.code(pe,ee):pe.$data&&G.validate?(0,s.funcKeywordCode)(pe,G):"macro"in G?(0,s.macroKeywordCode)(pe,G):(G.compile||G.validate)&&(0,s.funcKeywordCode)(pe,G)}const Q=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(D,{dataLevel:F,dataNames:G,dataPathArr:ee}){let pe,ke;if(D==="")return l.default.rootData;if(D[0]==="/"){if(!Q.test(D))throw new Error(`Invalid JSON-pointer: ${D}`);pe=D,ke=l.default.rootData}else{const Te=_e.exec(D);if(!Te)throw new Error(`Invalid JSON-pointer: ${D}`);const Re=+Te[1];if(pe=Te[2],pe==="#"){if(Re>=F)throw new Error(ve("property/index",Re));return ee[F-Re]}if(Re>F)throw new Error(ve("data",Re));if(ke=G[F-Re],!pe)return ke}let R=ke;const re=pe.split("/");for(const Te of re)Te&&(ke=(0,i._)`${ke}${(0,i.getProperty)((0,u.unescapeJsonPointer)(Te))}`,R=(0,i._)`${R} && ${ke}`);return R;function ve(Te,Re){return`Cannot access ${Te} ${Re} levels up, current level is ${F}`}}return Nr.getData=xe,Nr}var da={},wp;function kl(){if(wp)return da;wp=1,Object.defineProperty(da,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return da.default=e,da}var pa={},bp;function fa(){if(bp)return pa;bp=1,Object.defineProperty(pa,"__esModule",{value:!0});const e=ca();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 pa.default=t,pa}var Ht={},kp;function Tl(){if(kp)return Ht;kp=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.resolveSchema=Ht.getCompilingSchema=Ht.resolveRef=Ht.compileSchema=Ht.SchemaEnv=void 0;const e=Ne(),t=kl(),r=en(),n=ca(),o=Ze(),s=ua();class a{constructor(b){var v;this.refs={},this.dynamicAnchors={};let m;typeof b.schema=="object"&&(m=b.schema),this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(v=b.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(m?.[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=m?.$async,this.refs={}}}Ht.SchemaEnv=a;function i(g){const b=u.call(this,g);if(b)return b;const v=(0,n.getFullPath)(this.opts.uriResolver,g.root.baseId),{es5:m,lines:T}=this.opts.code,{ownProperties:k}=this.opts,_=new e.CodeGen(this.scope,{es5:m,lines:T,ownProperties:k});let S;g.$async&&(S=_.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const $=_.scopeName("validate");g.validateName=$;const x={gen:_,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:_.scopeValue("schema",this.opts.code.source===!0?{ref:g.schema,code:(0,e.stringify)(g.schema)}:{ref:g.schema}),validateName:$,ValidationError:S,schema:g.schema,schemaEnv:g,rootId:v,baseId:g.baseId||v,schemaPath:e.nil,errSchemaPath:g.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let U;try{this._compilations.add(g),(0,s.validateFunctionCode)(x),_.optimize(this.opts.code.optimize);const M=_.toString();U=`${_.scopeRefs(r.default.scope)}return ${M}`,this.opts.code.process&&(U=this.opts.code.process(U,g));const A=new Function(`${r.default.self}`,`${r.default.scope}`,U)(this,this.scope.get());if(this.scope.value($,{ref:A}),A.errors=null,A.schema=g.schema,A.schemaEnv=g,g.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:$,validateCode:M,scopeValues:_._values}),this.opts.unevaluated){const{props:L,items:Y}=x;A.evaluated={props:L instanceof e.Name?void 0:L,items:Y instanceof e.Name?void 0:Y,dynamicProps:L instanceof e.Name,dynamicItems:Y instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return g.validate=A,g}catch(M){throw delete g.validate,delete g.validateName,U&&this.logger.error("Error compiling schema, function code:",U),M}finally{this._compilations.delete(g)}}Ht.compileSchema=i;function l(g,b,v){var m;v=(0,n.resolveUrl)(this.opts.uriResolver,b,v);const T=g.refs[v];if(T)return T;let k=p.call(this,g,v);if(k===void 0){const _=(m=g.localRefs)===null||m===void 0?void 0:m[v],{schemaId:S}=this.opts;_&&(k=new a({schema:_,schemaId:S,root:g,baseId:b}))}if(k!==void 0)return g.refs[v]=c.call(this,k)}Ht.resolveRef=l;function c(g){return(0,n.inlineRef)(g.schema,this.opts.inlineRefs)?g.schema:g.validate?g:i.call(this,g)}function u(g){for(const b of this._compilations)if(f(b,g))return b}Ht.getCompilingSchema=u;function f(g,b){return g.schema===b.schema&&g.root===b.root&&g.baseId===b.baseId}function p(g,b){let v;for(;typeof(v=this.refs[b])=="string";)b=v;return v||this.schemas[b]||h.call(this,g,b)}function h(g,b){const v=this.opts.uriResolver.parse(b),m=(0,n._getFullPath)(this.opts.uriResolver,v);let T=(0,n.getFullPath)(this.opts.uriResolver,g.baseId,void 0);if(Object.keys(g.schema).length>0&&m===T)return w.call(this,v,g);const k=(0,n.normalizeId)(m),_=this.refs[k]||this.schemas[k];if(typeof _=="string"){const S=h.call(this,g,_);return typeof S?.schema!="object"?void 0:w.call(this,v,S)}if(typeof _?.schema=="object"){if(_.validate||i.call(this,_),k===(0,n.normalizeId)(b)){const{schema:S}=_,{schemaId:$}=this.opts,x=S[$];return x&&(T=(0,n.resolveUrl)(this.opts.uriResolver,T,x)),new a({schema:S,schemaId:$,root:g,baseId:T})}return w.call(this,v,_)}}Ht.resolveSchema=h;const y=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(g,{baseId:b,schema:v,root:m}){var T;if(((T=g.fragment)===null||T===void 0?void 0:T[0])!=="/")return;for(const S of g.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const $=v[(0,o.unescapeFragment)(S)];if($===void 0)return;v=$;const x=typeof v=="object"&&v[this.opts.schemaId];!y.has(S)&&x&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,x))}let k;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,b,v.$ref);k=h.call(this,m,S)}const{schemaId:_}=this.opts;if(k=k||new a({schema:v,schemaId:_,root:m,baseId:b}),k.schema!==k.root.schema)return k}return Ht}const M1={$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 ha={},No={exports:{}},Cl,Tp;function Cp(){if(Tp)return Cl;Tp=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 h="",y=0,w=0;for(w=0;w<p.length;w++)if(y=p[w].charCodeAt(0),y!==48){if(!(y>=48&&y<=57||y>=65&&y<=70||y>=97&&y<=102))return"";h+=p[w];break}for(w+=1;w<p.length;w++){if(y=p[w].charCodeAt(0),!(y>=48&&y<=57||y>=65&&y<=70||y>=97&&y<=102))return"";h+=p[w]}return h}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,h,y){if(p.length){const w=r(p);if(w!=="")h.push(w);else return y.error=!0,!1;p.length=0}return!0}function a(p){let h=0;const y={error:!1,address:"",zone:""},w=[],g=[];let b=!1,v=!1,m=s;for(let T=0;T<p.length;T++){const k=p[T];if(!(k==="["||k==="]"))if(k===":"){if(b===!0&&(v=!0),!m(g,w,y))break;if(++h>7){y.error=!0;break}T>0&&p[T-1]===":"&&(b=!0),w.push(":");continue}else if(k==="%"){if(!m(g,w,y))break;m=o}else{g.push(k);continue}}return g.length&&(m===o?y.zone=g.join(""):v?w.push(g.join("")):w.push(r(g))),y.address=w.join(""),y}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const h=a(p);if(h.error)return{host:p,isIPV6:!1};{let y=h.address,w=h.address;return h.zone&&(y+="%"+h.zone,w+="%25"+h.zone),{host:y,isIPV6:!0,escapedHost:w}}}function l(p,h){let y=0;for(let w=0;w<p.length;w++)p[w]===h&&y++;return y}function c(p){let h=p;const y=[];let w=-1,g=0;for(;g=h.length;){if(g===1){if(h===".")break;if(h==="/"){y.push("/");break}else{y.push(h);break}}else if(g===2){if(h[0]==="."){if(h[1]===".")break;if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&(h[1]==="."||h[1]==="/")){y.push("/");break}}else if(g===3&&h==="/.."){y.length!==0&&y.pop(),y.push("/");break}if(h[0]==="."){if(h[1]==="."){if(h[2]==="/"){h=h.slice(3);continue}}else if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&h[1]==="."){if(h[2]==="/"){h=h.slice(2);continue}else if(h[2]==="."&&h[3]==="/"){h=h.slice(3),y.length!==0&&y.pop();continue}}if((w=h.indexOf("/",1))===-1){y.push(h);break}else y.push(h.slice(0,w)),h=h.slice(w)}return y.join("")}function u(p,h){const y=h!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=y(p.scheme)),p.userinfo!==void 0&&(p.userinfo=y(p.userinfo)),p.host!==void 0&&(p.host=y(p.host)),p.path!==void 0&&(p.path=y(p.path)),p.query!==void 0&&(p.query=y(p.query)),p.fragment!==void 0&&(p.fragment=y(p.fragment)),p}function f(p){const h=[];if(p.userinfo!==void 0&&(h.push(p.userinfo),h.push("@")),p.host!==void 0){let y=unescape(p.host);if(!t(y)){const w=i(y);w.isIPV6===!0?y=`[${w.escapedHost}]`:y=p.host}h.push(y)}return(typeof p.port=="number"||typeof p.port=="string")&&(h.push(":"),h.push(String(p.port))),h.length?h.join(""):void 0}return Cl={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},Cl}var Sl,Sp;function O1(){if(Sp)return Sl;Sp=1;const{isUUID:e}=Cp(),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 _=String(k.scheme).toLowerCase()==="https";return(k.port===(_?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[_,S]=k.resourceName.split("?");k.path=_&&_!=="/"?_:void 0,k.query=S,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,_){if(!k.path)return k.error="URN can not be parsed",k;const S=k.path.match(t);if(S){const $=_.scheme||k.scheme||"urn";k.nid=S[1].toLowerCase(),k.nss=S[2];const x=`${$}:${_.nid||k.nid}`,U=T(x);k.path=void 0,U&&(k=U.parse(k,_))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,_){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=_.scheme||k.scheme||"urn",$=k.nid.toLowerCase(),x=`${S}:${_.nid||$}`,U=T(x);U&&(k=U.serialize(k,_));const M=k,O=k.nss;return M.path=`${$||_.nid}:${O}`,_.skipEscape=!0,M}function f(k,_){const S=k;return S.uuid=S.nss,S.nss=void 0,!_.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(k){const _=k;return _.nss=(k.uuid||"").toLowerCase(),_}const h={scheme:"http",domainHost:!0,parse:s,serialize:a},y={scheme:"https",domainHost:h.domainHost,parse:s,serialize:a},w={scheme:"ws",domainHost:!0,parse:i,serialize:l},g={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},m={http:h,https:y,ws:w,wss:g,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:f,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(m,null);function T(k){return k&&(m[k]||m[k.toLowerCase()])||void 0}return Sl={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:T},Sl}var Ip;function A1(){if(Ip)return No.exports;Ip=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Cp(),{SCHEMES:a,getSchemeHandler:i}=O1();function l(g,b){return typeof g=="string"?g=p(y(g,b),b):typeof g=="object"&&(g=y(p(g,b),b)),g}function c(g,b,v){const m=v?Object.assign({scheme:"null"},v):{scheme:"null"},T=u(y(g,m),y(b,m),m,!0);return m.skipEscape=!0,p(T,m)}function u(g,b,v,m){const T={};return m||(g=y(p(g,v),v),b=y(p(b,v),v)),v=v||{},!v.tolerant&&b.scheme?(T.scheme=b.scheme,T.userinfo=b.userinfo,T.host=b.host,T.port=b.port,T.path=t(b.path||""),T.query=b.query):(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0?(T.userinfo=b.userinfo,T.host=b.host,T.port=b.port,T.path=t(b.path||""),T.query=b.query):(b.path?(b.path[0]==="/"?T.path=t(b.path):((g.userinfo!==void 0||g.host!==void 0||g.port!==void 0)&&!g.path?T.path="/"+b.path:g.path?T.path=g.path.slice(0,g.path.lastIndexOf("/")+1)+b.path:T.path=b.path,T.path=t(T.path)),T.query=b.query):(T.path=g.path,b.query!==void 0?T.query=b.query:T.query=g.query),T.userinfo=g.userinfo,T.host=g.host,T.port=g.port),T.scheme=g.scheme),T.fragment=b.fragment,T}function f(g,b,v){return typeof g=="string"?(g=unescape(g),g=p(n(y(g,v),!0),{...v,skipEscape:!0})):typeof g=="object"&&(g=p(n(g,!0),{...v,skipEscape:!0})),typeof b=="string"?(b=unescape(b),b=p(n(y(b,v),!0),{...v,skipEscape:!0})):typeof b=="object"&&(b=p(n(b,!0),{...v,skipEscape:!0})),g.toLowerCase()===b.toLowerCase()}function p(g,b){const v={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:""},m=Object.assign({},b),T=[],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&&T.push(v.scheme,":");const _=r(v);if(_!==void 0&&(m.reference!=="suffix"&&T.push("//"),T.push(_),v.path&&v.path[0]!=="/"&&T.push("/")),v.path!==void 0){let S=v.path;!m.absolutePath&&(!k||!k.absolutePath)&&(S=t(S)),_===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),T.push(S)}return v.query!==void 0&&T.push("?",v.query),v.fragment!==void 0&&T.push("#",v.fragment),T.join("")}const h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function y(g,b){const v=Object.assign({},b),m={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let T=!1;v.reference==="suffix"&&(v.scheme?g=v.scheme+":"+g:g="//"+g);const k=g.match(h);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 $=e(m.host);m.host=$.host.toLowerCase(),T=$.isIPV6}else T=!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 _=i(v.scheme||m.scheme);if(!v.unicodeSupport&&(!_||!_.unicodeSupport)&&m.host&&(v.domainHost||_&&_.domainHost)&&T===!1&&s(m.host))try{m.host=URL.domainToASCII(m.host.toLowerCase())}catch(S){m.error=m.error||"Host's domain name can not be converted to ASCII: "+S}(!_||_&&!_.skipNormalize)&&(g.indexOf("%")!==-1&&(m.scheme!==void 0&&(m.scheme=unescape(m.scheme)),m.host!==void 0&&(m.host=unescape(m.host))),m.path&&(m.path=escape(unescape(m.path))),m.fragment&&(m.fragment=encodeURI(decodeURIComponent(m.fragment)))),_&&_.parse&&_.parse(m,v)}else m.error=m.error||"URI can not be parsed.";return m}const w={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:f,serialize:p,parse:y};return No.exports=w,No.exports.default=w,No.exports.fastUri=w,No.exports}var Ep;function N1(){if(Ep)return ha;Ep=1,Object.defineProperty(ha,"__esModule",{value:!0});const e=A1();return e.code='require("ajv/dist/runtime/uri").default',ha.default=e,ha}var xp;function q1(){return xp||(xp=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=ua();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ne();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=kl(),o=fa(),s=ip(),a=Tl(),i=Ne(),l=ca(),c=la(),u=Ze(),f=M1,p=N1(),h=(Z,N)=>new RegExp(Z,N);h.code="new RegExp";const y=["removeAdditional","useDefaults","coerceTypes"],w=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."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function m(Z){var N,H,z,I,E,V,te,Q,_e,xe,D,F,G,ee,pe,ke,R,re,ve,Te,Re,Xe,ie,lt,Ct;const ne=Z.strict,ze=(N=Z.code)===null||N===void 0?void 0:N.optimize,De=ze===!0||ze===void 0?1:ze||0,kr=(z=(H=Z.code)===null||H===void 0?void 0:H.regExp)!==null&&z!==void 0?z:h,Yr=(I=Z.uriResolver)!==null&&I!==void 0?I:p.default;return{strictSchema:(V=(E=Z.strictSchema)!==null&&E!==void 0?E:ne)!==null&&V!==void 0?V:!0,strictNumbers:(Q=(te=Z.strictNumbers)!==null&&te!==void 0?te:ne)!==null&&Q!==void 0?Q:!0,strictTypes:(xe=(_e=Z.strictTypes)!==null&&_e!==void 0?_e:ne)!==null&&xe!==void 0?xe:"log",strictTuples:(F=(D=Z.strictTuples)!==null&&D!==void 0?D:ne)!==null&&F!==void 0?F:"log",strictRequired:(ee=(G=Z.strictRequired)!==null&&G!==void 0?G:ne)!==null&&ee!==void 0?ee:!1,code:Z.code?{...Z.code,optimize:De,regExp:kr}:{optimize:De,regExp:kr},loopRequired:(pe=Z.loopRequired)!==null&&pe!==void 0?pe:v,loopEnum:(ke=Z.loopEnum)!==null&&ke!==void 0?ke:v,meta:(R=Z.meta)!==null&&R!==void 0?R:!0,messages:(re=Z.messages)!==null&&re!==void 0?re:!0,inlineRefs:(ve=Z.inlineRefs)!==null&&ve!==void 0?ve:!0,schemaId:(Te=Z.schemaId)!==null&&Te!==void 0?Te:"$id",addUsedSchema:(Re=Z.addUsedSchema)!==null&&Re!==void 0?Re:!0,validateSchema:(Xe=Z.validateSchema)!==null&&Xe!==void 0?Xe:!0,validateFormats:(ie=Z.validateFormats)!==null&&ie!==void 0?ie:!0,unicodeRegExp:(lt=Z.unicodeRegExp)!==null&&lt!==void 0?lt:!0,int32range:(Ct=Z.int32range)!==null&&Ct!==void 0?Ct:!0,uriResolver:Yr}}class T{constructor(N={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,N=this.opts={...N,...m(N)};const{es5:H,lines:z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:H,lines:z}),this.logger=O(N.logger);const I=N.validateFormats;N.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,g,N,"NOT SUPPORTED"),k.call(this,b,N,"DEPRECATED","warn"),this._metaOpts=U.call(this),N.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),N.keywords&&x.call(this,N.keywords),typeof N.meta=="object"&&this.addMetaSchema(N.meta),S.call(this),N.validateFormats=I}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:N,meta:H,schemaId:z}=this.opts;let I=f;z==="id"&&(I={...f},I.id=I.$id,delete I.$id),H&&N&&this.addMetaSchema(I,I[z],!1)}defaultMeta(){const{meta:N,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof N=="object"?N[H]||N:void 0}validate(N,H){let z;if(typeof N=="string"){if(z=this.getSchema(N),!z)throw new Error(`no schema with key or ref "${N}"`)}else z=this.compile(N);const I=z(H);return"$async"in z||(this.errors=z.errors),I}compile(N,H){const z=this._addSchema(N,H);return z.validate||this._compileSchemaEnv(z)}compileAsync(N,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:z}=this.opts;return I.call(this,N,H);async function I(xe,D){await E.call(this,xe.$schema);const F=this._addSchema(xe,D);return F.validate||V.call(this,F)}async function E(xe){xe&&!this.getSchema(xe)&&await I.call(this,{$ref:xe},!0)}async function V(xe){try{return this._compileSchemaEnv(xe)}catch(D){if(!(D instanceof o.default))throw D;return te.call(this,D),await Q.call(this,D.missingSchema),V.call(this,xe)}}function te({missingSchema:xe,missingRef:D}){if(this.refs[xe])throw new Error(`AnySchema ${xe} is loaded but ${D} cannot be resolved`)}async function Q(xe){const D=await _e.call(this,xe);this.refs[xe]||await E.call(this,D.$schema),this.refs[xe]||this.addSchema(D,xe,H)}async function _e(xe){const D=this._loading[xe];if(D)return D;try{return await(this._loading[xe]=z(xe))}finally{delete this._loading[xe]}}}addSchema(N,H,z,I=this.opts.validateSchema){if(Array.isArray(N)){for(const V of N)this.addSchema(V,void 0,z,I);return this}let E;if(typeof N=="object"){const{schemaId:V}=this.opts;if(E=N[V],E!==void 0&&typeof E!="string")throw new Error(`schema ${V} must be string`)}return H=(0,l.normalizeId)(H||E),this._checkUnique(H),this.schemas[H]=this._addSchema(N,z,H,I,!0),this}addMetaSchema(N,H,z=this.opts.validateSchema){return this.addSchema(N,H,!0,z),this}validateSchema(N,H){if(typeof N=="boolean")return!0;let z;if(z=N.$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 I=this.validate(z,N);if(!I&&H){const E="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(E);else throw new Error(E)}return I}getSchema(N){let H;for(;typeof(H=_.call(this,N))=="string";)N=H;if(H===void 0){const{schemaId:z}=this.opts,I=new a.SchemaEnv({schema:{},schemaId:z});if(H=a.resolveSchema.call(this,I,N),!H)return;this.refs[N]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(N){if(N instanceof RegExp)return this._removeAllSchemas(this.schemas,N),this._removeAllSchemas(this.refs,N),this;switch(typeof N){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const H=_.call(this,N);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[N],delete this.refs[N],this}case"object":{const H=N;this._cache.delete(H);let z=N[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(N){for(const H of N)this.addKeyword(H);return this}addKeyword(N,H){let z;if(typeof N=="string")z=N,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=z);else if(typeof N=="object"&&H===void 0){if(H=N,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(L.call(this,z,H),!H)return(0,u.eachItem)(z,E=>Y.call(this,E)),this;de.call(this,H);const I={...H,type:(0,c.getJSONTypes)(H.type),schemaType:(0,c.getJSONTypes)(H.schemaType)};return(0,u.eachItem)(z,I.type.length===0?E=>Y.call(this,E,I):E=>I.type.forEach(V=>Y.call(this,E,I,V))),this}getKeyword(N){const H=this.RULES.all[N];return typeof H=="object"?H.definition:!!H}removeKeyword(N){const{RULES:H}=this;delete H.keywords[N],delete H.all[N];for(const z of H.rules){const I=z.rules.findIndex(E=>E.keyword===N);I>=0&&z.rules.splice(I,1)}return this}addFormat(N,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[N]=H,this}errorsText(N=this.errors,{separator:H=", ",dataVar:z="data"}={}){return!N||N.length===0?"No errors":N.map(I=>`${z}${I.instancePath} ${I.message}`).reduce((I,E)=>I+H+E)}$dataMetaSchema(N,H){const z=this.RULES.all;N=JSON.parse(JSON.stringify(N));for(const I of H){const E=I.split("/").slice(1);let V=N;for(const te of E)V=V[te];for(const te in z){const Q=z[te];if(typeof Q!="object")continue;const{$data:_e}=Q.definition,xe=V[te];_e&&xe&&(V[te]=$e(xe))}}return N}_removeAllSchemas(N,H){for(const z in N){const I=N[z];(!H||H.test(z))&&(typeof I=="string"?delete N[z]:I&&!I.meta&&(this._cache.delete(I.schema),delete N[z]))}}_addSchema(N,H,z,I=this.opts.validateSchema,E=this.opts.addUsedSchema){let V;const{schemaId:te}=this.opts;if(typeof N=="object")V=N[te];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof N!="boolean")throw new Error("schema must be object or boolean")}let Q=this._cache.get(N);if(Q!==void 0)return Q;z=(0,l.normalizeId)(V||z);const _e=l.getSchemaRefs.call(this,N,z);return Q=new a.SchemaEnv({schema:N,schemaId:te,meta:H,baseId:z,localRefs:_e}),this._cache.set(Q.schema,Q),E&&!z.startsWith("#")&&(z&&this._checkUnique(z),this.refs[z]=Q),I&&this.validateSchema(N,!0),Q}_checkUnique(N){if(this.schemas[N]||this.refs[N])throw new Error(`schema with key or id "${N}" already exists`)}_compileSchemaEnv(N){if(N.meta?this._compileMetaSchema(N):a.compileSchema.call(this,N),!N.validate)throw new Error("ajv implementation error");return N.validate}_compileMetaSchema(N){const H=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,N)}finally{this.opts=H}}}T.ValidationError=n.default,T.MissingRefError=o.default,e.default=T;function k(Z,N,H,z="error"){for(const I in Z){const E=I;E in N&&this.logger[z](`${H}: option ${I}. ${Z[E]}`)}}function _(Z){return Z=(0,l.normalizeId)(Z),this.schemas[Z]||this.refs[Z]}function S(){const Z=this.opts.schemas;if(Z)if(Array.isArray(Z))this.addSchema(Z);else for(const N in Z)this.addSchema(Z[N],N)}function $(){for(const Z in this.opts.formats){const N=this.opts.formats[Z];N&&this.addFormat(Z,N)}}function x(Z){if(Array.isArray(Z)){this.addVocabulary(Z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const N in Z){const H=Z[N];H.keyword||(H.keyword=N),this.addKeyword(H)}}function U(){const Z={...this.opts};for(const N of y)delete Z[N];return Z}const M={log(){},warn(){},error(){}};function O(Z){if(Z===!1)return M;if(Z===void 0)return console;if(Z.log&&Z.warn&&Z.error)return Z;throw new Error("logger must implement log, warn and error methods")}const A=/^[a-z_$][a-z0-9_$:-]*$/i;function L(Z,N){const{RULES:H}=this;if((0,u.eachItem)(Z,z=>{if(H.keywords[z])throw new Error(`Keyword ${z} is already defined`);if(!A.test(z))throw new Error(`Keyword ${z} has invalid name`)}),!!N&&N.$data&&!("code"in N||"validate"in N))throw new Error('$data keyword must have "code" or "validate" function')}function Y(Z,N,H){var z;const I=N?.post;if(H&&I)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:E}=this;let V=I?E.post:E.rules.find(({type:Q})=>Q===H);if(V||(V={type:H,rules:[]},E.rules.push(V)),E.keywords[Z]=!0,!N)return;const te={keyword:Z,definition:{...N,type:(0,c.getJSONTypes)(N.type),schemaType:(0,c.getJSONTypes)(N.schemaType)}};N.before?J.call(this,V,te,N.before):V.rules.push(te),E.all[Z]=te,(z=N.implements)===null||z===void 0||z.forEach(Q=>this.addKeyword(Q))}function J(Z,N,H){const z=Z.rules.findIndex(I=>I.keyword===H);z>=0?Z.rules.splice(z,0,N):(Z.rules.push(N),this.logger.warn(`rule ${H} is not defined`))}function de(Z){let{metaSchema:N}=Z;N!==void 0&&(Z.$data&&this.opts.$data&&(N=$e(N)),Z.validateSchema=this.compile(N,!0))}const K={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $e(Z){return{anyOf:[Z,K]}}})(ml)),ml}var ma={},ga={},ya={},$p;function L1(){if($p)return ya;$p=1,Object.defineProperty(ya,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return ya.default=e,ya}var tn={},Rp;function j1(){if(Rp)return tn;Rp=1,Object.defineProperty(tn,"__esModule",{value:!0}),tn.callRef=tn.getValidate=void 0;const e=fa(),t=ir(),r=Ne(),n=en(),o=Tl(),s=Ze(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:f,it:p}=c,{baseId:h,schemaEnv:y,validateName:w,opts:g,self:b}=p,{root:v}=y;if((f==="#"||f==="#/")&&h===v.baseId)return T();const m=o.resolveRef.call(b,v,h,f);if(m===void 0)throw new e.default(p.opts.uriResolver,h,f);if(m instanceof o.SchemaEnv)return k(m);return _(m);function T(){if(y===v)return l(c,w,y,y.$async);const S=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${S}.validate`,v,v.$async)}function k(S){const $=i(c,S);l(c,$,S,S.$async)}function _(S){const $=u.scopeValue("schema",g.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),x=u.name("valid"),U=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:$,errSchemaPath:f},x);c.mergeEvaluated(U),c.ok(x)}}};function i(c,u){const{gen:f}=c;return u.validate?f.scopeValue("validate",{ref:u.validate}):(0,r._)`${f.scopeValue("wrapper",{ref:u})}.validate`}tn.getValidate=i;function l(c,u,f,p){const{gen:h,it:y}=c,{allErrors:w,schemaEnv:g,opts:b}=y,v=b.passContext?n.default.this:r.nil;p?m():T();function m(){if(!g.$async)throw new Error("async schema referenced by sync schema");const S=h.let("valid");h.try(()=>{h.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),_(u),w||h.assign(S,!0)},$=>{h.if((0,r._)`!(${$} instanceof ${y.ValidationError})`,()=>h.throw($)),k($),w||h.assign(S,!1)}),c.ok(S)}function T(){c.result((0,t.callValidateCode)(c,u,v),()=>_(u),()=>k(u))}function k(S){const $=(0,r._)`${S}.errors`;h.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${$} : ${n.default.vErrors}.concat(${$})`),h.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function _(S){var $;if(!y.opts.unevaluated)return;const x=($=f?.validate)===null||$===void 0?void 0:$.evaluated;if(y.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(y.props=s.mergeEvaluated.props(h,x.props,y.props));else{const U=h.var("props",(0,r._)`${S}.evaluated.props`);y.props=s.mergeEvaluated.props(h,U,y.props,r.Name)}if(y.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(y.items=s.mergeEvaluated.items(h,x.items,y.items));else{const U=h.var("items",(0,r._)`${S}.evaluated.items`);y.items=s.mergeEvaluated.items(h,U,y.items,r.Name)}}}return tn.callRef=l,tn.default=a,tn}var Pp;function D1(){if(Pp)return ga;Pp=1,Object.defineProperty(ga,"__esModule",{value:!0});const e=L1(),t=j1(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return ga.default=r,ga}var va={},_a={},Mp;function U1(){if(Mp)return _a;Mp=1,Object.defineProperty(_a,"__esModule",{value:!0});const e=Ne(),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 _a.default=o,_a}var wa={},Op;function z1(){if(Op)return wa;Op=1,Object.defineProperty(wa,"__esModule",{value:!0});const e=Ne(),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 wa.default=r,wa}var ba={},ka={},Ap;function Z1(){if(Ap)return ka;Ap=1,Object.defineProperty(ka,"__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 ka.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ka}var Np;function F1(){if(Np)return ba;Np=1,Object.defineProperty(ba,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Z1(),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,f=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${f} ${u} ${l}`)}};return ba.default=o,ba}var Ta={},qp;function V1(){if(qp)return Ta;qp=1,Object.defineProperty(Ta,"__esModule",{value:!0});const e=ir(),t=Ne(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:o})=>(0,t.str)`must match pattern "${o}"`,params:({schemaCode:o})=>(0,t._)`{pattern: ${o}}`},code(o){const{data:s,$data:a,schema:i,schemaCode:l,it:c}=o,u=c.opts.unicodeRegExp?"u":"",f=a?(0,t._)`(new RegExp(${l}, ${u}))`:(0,e.usePattern)(o,i);o.fail$data((0,t._)`!${f}.test(${s})`)}};return Ta.default=n,Ta}var Ca={},Lp;function H1(){if(Lp)return Ca;Lp=1,Object.defineProperty(Ca,"__esModule",{value:!0});const e=Ne(),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 Ca.default=r,Ca}var Sa={},jp;function B1(){if(jp)return Sa;jp=1,Object.defineProperty(Sa,"__esModule",{value:!0});const e=ir(),t=Ne(),r=Ze(),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:f}=s,{opts:p}=f;if(!u&&i.length===0)return;const h=i.length>=p.loopRequired;if(f.allErrors?y():w(),p.strictRequired){const v=s.parentSchema.properties,{definedProperties:m}=s.it;for(const T of i)if(v?.[T]===void 0&&!m.has(T)){const k=f.schemaEnv.baseId+f.errSchemaPath,_=`required property "${T}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(f,_,f.opts.strictRequired)}}function y(){if(h||u)s.block$data(t.nil,g);else for(const v of i)(0,e.checkReportMissingProp)(s,v)}function w(){const v=a.let("missing");if(h||u){const m=a.let("valid",!0);s.block$data(m,()=>b(v,m)),s.ok(m)}else a.if((0,e.checkMissingProp)(s,i,v)),(0,e.reportMissingProp)(s,v),a.else()}function g(){a.forOf("prop",l,v=>{s.setParams({missingProperty:v}),a.if((0,e.noPropertyInData)(a,c,v,p.ownProperties),()=>s.error())})}function b(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 Sa.default=o,Sa}var Ia={},Dp;function J1(){if(Dp)return Ia;Dp=1,Object.defineProperty(Ia,"__esModule",{value:!0});const e=Ne(),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 Ia.default=r,Ia}var Ea={},xa={},Up;function Il(){if(Up)return xa;Up=1,Object.defineProperty(xa,"__esModule",{value:!0});const e=gp();return e.code='require("ajv/dist/runtime/equal").default',xa.default=e,xa}var zp;function W1(){if(zp)return Ea;zp=1,Object.defineProperty(Ea,"__esModule",{value:!0});const e=la(),t=Ne(),r=Ze(),n=Il(),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:f,schemaCode:p,it:h}=a;if(!c&&!u)return;const y=i.let("valid"),w=f.items?(0,e.getSchemaTypes)(f.items):[];a.block$data(y,g,(0,t._)`${p} === false`),a.ok(y);function g(){const T=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:T,j:k}),i.assign(y,!0),i.if((0,t._)`${T} > 1`,()=>(b()?v:m)(T,k))}function b(){return w.length>0&&!w.some(T=>T==="object"||T==="array")}function v(T,k){const _=i.name("item"),S=(0,e.checkDataTypes)(w,_,h.opts.strictNumbers,e.DataType.Wrong),$=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${T}--;`,()=>{i.let(_,(0,t._)`${l}[${T}]`),i.if(S,(0,t._)`continue`),w.length>1&&i.if((0,t._)`typeof ${_} == "string"`,(0,t._)`${_} += "_"`),i.if((0,t._)`typeof ${$}[${_}] == "number"`,()=>{i.assign(k,(0,t._)`${$}[${_}]`),a.error(),i.assign(y,!1).break()}).code((0,t._)`${$}[${_}] = ${T}`)})}function m(T,k){const _=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${T}--;`,()=>i.for((0,t._)`${k} = ${T}; ${k}--;`,()=>i.if((0,t._)`${_}(${l}[${T}], ${l}[${k}])`,()=>{a.error(),i.assign(y,!1).break(S)})))}}};return Ea.default=s,Ea}var $a={},Zp;function G1(){if(Zp)return $a;Zp=1,Object.defineProperty($a,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Il(),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 $a.default=o,$a}var Ra={},Fp;function K1(){if(Fp)return Ra;Fp=1,Object.defineProperty(Ra,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Il(),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:f}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=f.opts.loopEnum;let h;const y=()=>h??(h=(0,t.useFunc)(a,r.default));let w;if(p||l)w=a.let("valid"),s.block$data(w,g);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=a.const("vSchema",u);w=(0,e.or)(...c.map((m,T)=>b(v,T)))}s.pass(w);function g(){a.assign(w,!1),a.forOf("v",u,v=>a.if((0,e._)`${y()}(${i}, ${v})`,()=>a.assign(w,!0).break()))}function b(v,m){const T=c[m];return typeof T=="object"&&T!==null?(0,e._)`${y()}(${i}, ${v}[${m}])`:(0,e._)`${i} === ${T}`}}};return Ra.default=o,Ra}var Vp;function Y1(){if(Vp)return va;Vp=1,Object.defineProperty(va,"__esModule",{value:!0});const e=U1(),t=z1(),r=F1(),n=V1(),o=H1(),s=B1(),a=J1(),i=W1(),l=G1(),c=K1(),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 va.default=u,va}var Pa={},Yn={},Hp;function Bp(){if(Hp)return Yn;Hp=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.validateAdditionalItems=void 0;const e=Ne(),t=Ze(),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:f}=s;f.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)(f,l)){const y=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(y),()=>h(y)),s.ok(y)}function h(y){i.forRange("i",a.length,p,w=>{s.subschema({keyword:u,dataProp:w,dataPropType:t.Type.Num},y),f.allErrors||i.if((0,e.not)(y),()=>i.break())})}}return Yn.validateAdditionalItems=o,Yn.default=n,Yn}var Ma={},Qn={},Jp;function Wp(){if(Jp)return Qn;Jp=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.validateTuple=void 0;const e=Ne(),t=Ze(),r=ir(),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:f,it:p}=s;w(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const h=l.name("valid"),y=l.const("len",(0,e._)`${u}.length`);i.forEach((g,b)=>{(0,t.alwaysValidSchema)(p,g)||(l.if((0,e._)`${y} > ${b}`,()=>s.subschema({keyword:f,schemaProp:b,dataProp:b},h)),s.ok(h))});function w(g){const{opts:b,errSchemaPath:v}=p,m=i.length,T=m===g.minItems&&(m===g.maxItems||g[a]===!1);if(b.strictTuples&&!T){const k=`"${f}" is ${m}-tuple, but minItems or maxItems/${a} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,k,b.strictTuples)}}}return Qn.validateTuple=o,Qn.default=n,Qn}var Gp;function Q1(){if(Gp)return Ma;Gp=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=Wp(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Ma.default=t,Ma}var Oa={},Kp;function X1(){if(Kp)return Oa;Kp=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=ir(),n=Bp(),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 Oa.default=s,Oa}var Aa={},Yp;function ew(){if(Yp)return Aa;Yp=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Ne(),t=Ze(),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,f;const{minContains:p,maxContains:h}=i;c.opts.next?(u=p===void 0?1:p,f=h):u=1;const y=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:f}),f===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&u>f){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let m=(0,e._)`${y} >= ${u}`;f!==void 0&&(m=(0,e._)`${m} && ${y} <= ${f}`),o.pass(m);return}c.items=!0;const w=s.name("valid");f===void 0&&u===1?b(w,()=>s.if(w,()=>s.break())):u===0?(s.let(w,!0),f!==void 0&&s.if((0,e._)`${l}.length > 0`,g)):(s.let(w,!1),g()),o.result(w,()=>o.reset());function g(){const m=s.name("_valid"),T=s.let("count",0);b(m,()=>s.if(m,()=>v(T)))}function b(m,T){s.forRange("i",0,y,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},m),T()})}function v(m){s.code((0,e._)`${m}++`),f===void 0?s.if((0,e._)`${m} >= ${u}`,()=>s.assign(w,!0).break()):(s.if((0,e._)`${m} > ${f}`,()=>s.assign(w,!1).break()),u===1?s.assign(w,!0):s.if((0,e._)`${m} >= ${u}`,()=>s.assign(w,!0)))}}};return Aa.default=n,Aa}var El={},Qp;function tw(){return Qp||(Qp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ne(),r=Ze(),n=ir();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,t.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,t._)`{property: ${l},
6
- missingProperty: ${f},
1
+ (function(Re,Mn){typeof exports=="object"&&typeof module<"u"?Mn(exports):typeof define=="function"&&define.amd?define(["exports"],Mn):(Re=typeof globalThis<"u"?globalThis:Re||self,Mn(Re.WebMCP={}))})(this,(function(Re){"use strict";function Mn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ya={exports:{}},Ol={},Hr={},On={},Nl={},Al={},ql={},mp;function va(){return mp||(mp=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,C)=>`${m}${C}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((m,C)=>(C instanceof r&&(m[C.str]=(m[C.str]||0)+1),m),{})}}e._Code=n,e.nil=new n("");function o(w,...v){const m=[w[0]];let C=0;for(;C<v.length;)i(m,v[C]),m.push(w[++C]);return new n(m)}e._=o;const s=new n("+");function a(w,...v){const m=[f(w[0])];let C=0;for(;C<v.length;)m.push(s),i(m,v[C]),m.push(s,f(w[++C]));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})(ql)),ql}var Ll={},gp;function yp(){return gp||(gp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=va();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})(Ll)),Ll}var vp;function Ne(){return vp||(vp=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=va(),r=yp();var n=va();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=yp();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,O){return this}}class a extends s{constructor(E,O,D){super(),this.varKind=E,this.name=O,this.rhs=D}render({es5:E,_n:O}){const D=E?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${D} ${this.name}${G};`+O}optimizeNames(E,O){if(E[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,E,O)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,O,D){super(),this.lhs=E,this.rhs=O,this.sideEffects=D}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,O){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,E,O),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(E,this.rhs)}}class l extends i{constructor(E,O,D,G){super(E,D,G),this.op=O}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,O){return this.code=U(this.code,E,O),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((O,D)=>O+D.render(E),"")}optimizeNodes(){const{nodes:E}=this;let O=E.length;for(;O--;){const D=E[O].optimizeNodes();Array.isArray(D)?E.splice(O,1,...D):D?E[O]=D:E.splice(O,1)}return E.length>0?this:void 0}optimizeNames(E,O){const{nodes:D}=this;let G=D.length;for(;G--;){const re=D[G];re.optimizeNames(E,O)||(V(E,re.names),D.splice(G,1))}return D.length>0?this:void 0}get names(){return this.nodes.reduce((E,O)=>N(E,O.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,O){super(O),this.condition=E}render(E){let O=`if(${this.condition})`+super.render(E);return this.else&&(O+="else "+this.else.render(E)),O}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let O=this.else;if(O){const D=O.optimizeNodes();O=this.else=Array.isArray(D)?new y(D):D}if(O)return E===!1?O instanceof w?O:O.nodes:this.nodes.length?this:new w(Q(E),O instanceof w?[O]:O.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,O){var D;if(this.else=(D=this.else)===null||D===void 0?void 0:D.optimizeNames(E,O),!!(super.optimizeNames(E,O)||this.else))return this.condition=U(this.condition,E,O),this}get names(){const E=super.names;return A(E,this.condition),this.else&&N(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,O){if(super.optimizeNames(E,O))return this.iteration=U(this.iteration,E,O),this}get names(){return N(super.names,this.iteration.names)}}class C extends v{constructor(E,O,D,G){super(),this.varKind=E,this.name=O,this.from=D,this.to=G}render(E){const O=E.es5?r.varKinds.var:this.varKind,{name:D,from:G,to:re}=this;return`for(${O} ${D}=${G}; ${D}<${re}; ${D}++)`+super.render(E)}get names(){const E=A(super.names,this.from);return A(E,this.to)}}class k extends v{constructor(E,O,D,G){super(),this.loop=E,this.varKind=O,this.name=D,this.iterable=G}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,O){if(super.optimizeNames(E,O))return this.iterable=U(this.iterable,E,O),this}get names(){return N(super.names,this.iterable.names)}}class b extends g{constructor(E,O,D){super(),this.name=E,this.args=O,this.async=D}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}b.kind="func";class S extends f{render(E){return"return "+super.render(E)}}S.kind="return";class x extends g{render(E){let O="try"+super.render(E);return this.catch&&(O+=this.catch.render(E)),this.finally&&(O+=this.finally.render(E)),O}optimizeNodes(){var E,O;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(O=this.finally)===null||O===void 0||O.optimizeNodes(),this}optimizeNames(E,O){var D,G;return super.optimizeNames(E,O),(D=this.catch)===null||D===void 0||D.optimizeNames(E,O),(G=this.finally)===null||G===void 0||G.optimizeNames(E,O),this}get names(){const E=super.names;return this.catch&&N(E,this.catch.names),this.finally&&N(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 ${constructor(E,O={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...O,_n:O.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,O){const D=this._extScope.value(E,O);return(this._values[D.prefix]||(this._values[D.prefix]=new Set)).add(D),D}getScopeValue(E,O){return this._extScope.getValue(E,O)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,O,D,G){const re=this._scope.toName(O);return D!==void 0&&G&&(this._constants[re.str]=D),this._leafNode(new a(E,re,D)),re}const(E,O,D){return this._def(r.varKinds.const,E,O,D)}let(E,O,D){return this._def(r.varKinds.let,E,O,D)}var(E,O,D){return this._def(r.varKinds.var,E,O,D)}assign(E,O,D){return this._leafNode(new i(E,O,D))}add(E,O){return this._leafNode(new l(E,e.operators.ADD,O))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const O=["{"];for(const[D,G]of E)O.length>1&&O.push(","),O.push(D),(D!==G||this.opts.es5)&&(O.push(":"),(0,t.addCodeArg)(O,G));return O.push("}"),new t._Code(O)}if(E,O,D){if(this._blockNode(new w(E)),O&&D)this.code(O).else().code(D).endIf();else if(O)this.code(O).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,O){return this._blockNode(E),O&&this.code(O).endFor(),this}for(E,O){return this._for(new m(E),O)}forRange(E,O,D,G,re=this.opts.es5?r.varKinds.var:r.varKinds.let){const ie=this._scope.toName(E);return this._for(new C(re,ie,O,D),()=>G(ie))}forOf(E,O,D,G=r.varKinds.const){const re=this._scope.toName(E);if(this.opts.es5){const ie=O instanceof t.Name?O:this.var("_arr",O);return this.forRange("_i",0,(0,t._)`${ie}.length`,Ie=>{this.var(re,(0,t._)`${ie}[${Ie}]`),D(re)})}return this._for(new k("of",G,re,O),()=>D(re))}forIn(E,O,D,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${O})`,D);const re=this._scope.toName(E);return this._for(new k("in",G,re,O),()=>D(re))}endFor(){return this._endBlockNode(v)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const O=new S;if(this._blockNode(O),this.code(E),O.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(E,O,D){if(!O&&!D)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new x;if(this._blockNode(G),this.code(E),O){const re=this.name("e");this._currNode=G.catch=new I(re),O(re)}return D&&(this._currNode=G.finally=new L,this.code(D)),this._endBlockNode(I,L)}throw(E){return this._leafNode(new h(E))}block(E,O){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(O),this}endBlock(E){const O=this._blockStarts.pop();if(O===void 0)throw new Error("CodeGen: not in self-balancing block");const D=this._nodes.length-O;if(D<0||E!==void 0&&D!==E)throw new Error(`CodeGen: wrong number of nodes: ${D} vs ${E} expected`);return this._nodes.length=O,this}func(E,O=t.nil,D,G){return this._blockNode(new b(E,O,D)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(b)}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,O){const D=this._currNode;if(D instanceof E||O&&D instanceof O)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${O?`${E.kind}/${O.kind}`:E.kind}"`)}_elseNode(E){const O=this._currNode;if(!(O instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=O.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const O=this._nodes;O[O.length-1]=E}}e.CodeGen=$;function N(Z,E){for(const O in E)Z[O]=(Z[O]||0)+(E[O]||0);return Z}function A(Z,E){return E instanceof t._CodeOrName?N(Z,E.names):Z}function U(Z,E,O){if(Z instanceof t.Name)return D(Z);if(!G(Z))return Z;return new t._Code(Z._items.reduce((re,ie)=>(ie instanceof t.Name&&(ie=D(ie)),ie instanceof t._Code?re.push(...ie._items):re.push(ie),re),[]));function D(re){const ie=O[re.str];return ie===void 0||E[re.str]!==1?re:(delete E[re.str],ie)}function G(re){return re instanceof t._Code&&re._items.some(ie=>ie instanceof t.Name&&E[ie.str]===1&&O[ie.str]!==void 0)}}function V(Z,E){for(const O in E)Z[O]=(Z[O]||0)-(E[O]||0)}function Q(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${B(Z)}`}e.not=Q;const _e=M(e.operators.AND);function te(...Z){return Z.reduce(_e)}e.and=te;const ge=M(e.operators.OR);function H(...Z){return Z.reduce(ge)}e.or=H;function M(Z){return(E,O)=>E===t.nil?O:O===t.nil?E:(0,t._)`${B(E)} ${Z} ${B(O)}`}function B(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(Al)),Al}var Ae={},_p;function Ue(){if(_p)return Ae;_p=1,Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.checkStrictMode=Ae.getErrorPath=Ae.Type=Ae.useFunc=Ae.setEvaluated=Ae.evaluatedPropsToName=Ae.mergeEvaluated=Ae.eachItem=Ae.unescapeJsonPointer=Ae.escapeJsonPointer=Ae.escapeFragment=Ae.unescapeFragment=Ae.schemaRefOrVal=Ae.schemaHasRulesButRef=Ae.schemaHasRules=Ae.checkUnknownRules=Ae.alwaysValidSchema=Ae.toHash=void 0;const e=Ne(),t=va();function r(k){const b={};for(const S of k)b[S]=!0;return b}Ae.toHash=r;function n(k,b){return typeof b=="boolean"?b:Object.keys(b).length===0?!0:(o(k,b),!s(b,k.self.RULES.all))}Ae.alwaysValidSchema=n;function o(k,b=k.schema){const{opts:S,self:x}=k;if(!S.strictSchema||typeof b=="boolean")return;const I=x.RULES.keywords;for(const L in b)I[L]||C(k,`unknown keyword: "${L}"`)}Ae.checkUnknownRules=o;function s(k,b){if(typeof k=="boolean")return!k;for(const S in k)if(b[S])return!0;return!1}Ae.schemaHasRules=s;function a(k,b){if(typeof k=="boolean")return!k;for(const S in k)if(S!=="$ref"&&b.all[S])return!0;return!1}Ae.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:b},S,x,I){if(!I){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${k}${b}${(0,e.getProperty)(x)}`}Ae.schemaRefOrVal=i;function l(k){return h(decodeURIComponent(k))}Ae.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Ae.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Ae.escapeJsonPointer=u;function h(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Ae.unescapeJsonPointer=h;function p(k,b){if(Array.isArray(k))for(const S of k)b(S);else b(k)}Ae.eachItem=p;function f({mergeNames:k,mergeToName:b,mergeValues:S,resultToName:x}){return(I,L,$,N)=>{const A=$===void 0?L:$ instanceof e.Name?(L instanceof e.Name?k(I,L,$):b(I,L,$),$):L instanceof e.Name?(b(I,$,L),L):S(L,$);return N===e.Name&&!(A instanceof e.Name)?x(I,A):A}}Ae.mergeEvaluated={props:f({mergeNames:(k,b,S)=>k.if((0,e._)`${S} !== true && ${b} !== undefined`,()=>{k.if((0,e._)`${b} === true`,()=>k.assign(S,!0),()=>k.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${b})`))}),mergeToName:(k,b,S)=>k.if((0,e._)`${S} !== true`,()=>{b===!0?k.assign(S,!0):(k.assign(S,(0,e._)`${S} || {}`),_(k,S,b))}),mergeValues:(k,b)=>k===!0?!0:{...k,...b},resultToName:g}),items:f({mergeNames:(k,b,S)=>k.if((0,e._)`${S} !== true && ${b} !== undefined`,()=>k.assign(S,(0,e._)`${b} === true ? true : ${S} > ${b} ? ${S} : ${b}`)),mergeToName:(k,b,S)=>k.if((0,e._)`${S} !== true`,()=>k.assign(S,b===!0?!0:(0,e._)`${S} > ${b} ? ${S} : ${b}`)),mergeValues:(k,b)=>k===!0?!0:Math.max(k,b),resultToName:(k,b)=>k.var("items",b)})};function g(k,b){if(b===!0)return k.var("props",!0);const S=k.var("props",(0,e._)`{}`);return b!==void 0&&_(k,S,b),S}Ae.evaluatedPropsToName=g;function _(k,b,S){Object.keys(S).forEach(x=>k.assign((0,e._)`${b}${(0,e.getProperty)(x)}`,!0))}Ae.setEvaluated=_;const y={};function w(k,b){return k.scopeValue("func",{ref:b,code:y[b.code]||(y[b.code]=new t._Code(b.code))})}Ae.useFunc=w;var v;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(v||(Ae.Type=v={}));function m(k,b,S){if(k instanceof e.Name){const x=b===v.Num;return S?x?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:x?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(k).toString():"/"+u(k)}Ae.getErrorPath=m;function C(k,b,S=k.opts.strictSchema){if(S){if(b=`strict mode: ${b}`,S===!0)throw new Error(b);k.self.logger.warn(b)}}return Ae.checkStrictMode=C,Ae}var _a={},wp;function pn(){if(wp)return _a;wp=1,Object.defineProperty(_a,"__esModule",{value:!0});const e=Ne(),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 _a.default=t,_a}var bp;function wa(){return bp||(bp=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=Ne(),r=Ue(),n=pn();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:C}=y,{gen:k,compositeRule:b,allErrors:S}=C,x=h(y,w,v);m??(b||S)?l(k,x):c(C,(0,t._)`[${x}]`)}e.reportError=o;function s(y,w=e.keywordError,v){const{it:m}=y,{gen:C,compositeRule:k,allErrors:b}=m,S=h(y,w,v);l(C,S),k||b||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:C,it:k}){if(C===void 0)throw new Error("ajv implementation error");const b=y.name("err");y.forRange("i",C,n.default.errors,S=>{y.const(b,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${b}.instancePath === undefined`,()=>y.assign((0,t._)`${b}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),y.assign((0,t._)`${b}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(y.assign((0,t._)`${b}.schema`,v),y.assign((0,t._)`${b}.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:C}=y;C.$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:C}=y,k=[f(C,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 C=m?w:(0,t.str)`${w}/${y}`;return v&&(C=(0,t.str)`${C}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,C]}function _(y,{params:w,message:v},m){const{keyword:C,data:k,schemaValue:b,it:S}=y,{opts:x,propertyName:I,topSchemaRef:L,schemaPath:$}=S;m.push([u.keyword,C],[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,b],[u.parentSchema,(0,t._)`${L}${$}`],[n.default.data,k]),I&&m.push([u.propertyName,I])}})(Nl)),Nl}var kp;function B1(){if(kp)return On;kp=1,Object.defineProperty(On,"__esModule",{value:!0}),On.boolOrEmptySchema=On.topBoolOrEmptySchema=void 0;const e=wa(),t=Ne(),r=pn(),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))}On.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}On.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 On}var xt={},Nn={},Tp;function Cp(){if(Tp)return Nn;Tp=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.getRules=Nn.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)}Nn.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 Nn.getRules=n,Nn}var Br={},Sp;function Ip(){if(Sp)return Br;Sp=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.shouldUseRule=Br.shouldUseGroup=Br.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Br.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Br.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 Br.shouldUseRule=r,Br}var xp;function ba(){if(xp)return xt;xp=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.reportTypeError=xt.checkDataTypes=xt.checkDataType=xt.coerceAndCheckDataType=xt.getJSONTypes=xt.getSchemaTypes=xt.DataType=void 0;const e=Cp(),t=Ip(),r=wa(),n=Ne(),o=Ue();var s;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(s||(xt.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}xt.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(","))}xt.getJSONTypes=i;function l(v,m){const{gen:C,data:k,opts:b}=v,S=u(m,b.coerceTypes),x=m.length>0&&!(S.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(v,m[0]));if(x){const I=g(m,k,b.strictNumbers,s.Wrong);C.if(I,()=>{S.length?h(v,m,S):y(v)})}return x}xt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,m){return m?v.filter(C=>c.has(C)||m==="array"&&C==="array"):[]}function h(v,m,C){const{gen:k,data:b,opts:S}=v,x=k.let("dataType",(0,n._)`typeof ${b}`),I=k.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${b}) && ${b}.length == 1`,()=>k.assign(b,(0,n._)`${b}[0]`).assign(x,(0,n._)`typeof ${b}`).if(g(m,b,S.strictNumbers),()=>k.assign(I,b))),k.if((0,n._)`${I} !== undefined`);for(const $ of C)(c.has($)||$==="array"&&S.coerceTypes==="array")&&L($);k.else(),y(v),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(b,I),p(v,I)});function L($){switch($){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(I,(0,n._)`"" + ${b}`).elseIf((0,n._)`${b} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${b} === null
3
+ || (${x} == "string" && ${b} && ${b} == +${b})`).assign(I,(0,n._)`+${b}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${b} === null
4
+ || (${x} === "string" && ${b} && ${b} == +${b} && !(${b} % 1))`).assign(I,(0,n._)`+${b}`);return;case"boolean":k.elseIf((0,n._)`${b} === "false" || ${b} === 0 || ${b} === null`).assign(I,!1).elseIf((0,n._)`${b} === "true" || ${b} === 1`).assign(I,!0);return;case"null":k.elseIf((0,n._)`${b} === "" || ${b} === 0 || ${b} === false`),k.assign(I,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
5
+ || ${x} === "boolean" || ${b} === null`).assign(I,(0,n._)`[${b}]`)}}}function p({gen:v,parentData:m,parentDataProperty:C},k){v.if((0,n._)`${m} !== undefined`,()=>v.assign((0,n._)`${m}[${C}]`,k))}function f(v,m,C,k=s.Correct){const b=k===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(v){case"null":return(0,n._)`${m} ${b} null`;case"array":S=(0,n._)`Array.isArray(${m})`;break;case"object":S=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":S=x((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":S=x();break;default:return(0,n._)`typeof ${m} ${b} ${v}`}return k===s.Correct?S:(0,n.not)(S);function x(I=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,I,C?(0,n._)`isFinite(${m})`:n.nil)}}xt.checkDataType=f;function g(v,m,C,k){if(v.length===1)return f(v[0],m,C,k);let b;const S=(0,o.toHash)(v);if(S.array&&S.object){const x=(0,n._)`typeof ${m} != "object"`;b=S.null?x:(0,n._)`!${m} || ${x}`,delete S.null,delete S.array,delete S.object}else b=n.nil;S.number&&delete S.integer;for(const x in S)b=(0,n.and)(b,f(x,m,C,k));return b}xt.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,_)}xt.reportTypeError=y;function w(v){const{gen:m,data:C,schema:k}=v,b=(0,o.schemaRefOrVal)(v,k,"type");return{gen:m,keyword:"type",data:C,schema:k.type,schemaCode:b,schemaValue:b,parentSchema:k,params:{},it:v}}return xt}var Vo={},Ep;function J1(){if(Ep)return Vo;Ep=1,Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.assignDefaults=void 0;const e=Ne(),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))}Vo.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 Vo}var hr={},Be={},$p;function mr(){if($p)return Be;$p=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=Ne(),t=Ue(),r=pn(),n=Ue();function o(v,m){const{gen:C,data:k,it:b}=v;C.if(u(C,k,m,b.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${m}`},!0),v.error()})}Be.checkReportMissingProp=o;function s({gen:v,data:m,it:{opts:C}},k,b){return(0,e.or)(...k.map(S=>(0,e.and)(u(v,m,S,C.ownProperties),(0,e._)`${b} = ${S}`)))}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,C){return(0,e._)`${i(v)}.call(${m}, ${C})`}Be.isOwnProperty=l;function c(v,m,C,k){const b=(0,e._)`${m}${(0,e.getProperty)(C)} !== undefined`;return k?(0,e._)`${b} && ${l(v,m,C)}`:b}Be.propertyInData=c;function u(v,m,C,k){const b=(0,e._)`${m}${(0,e.getProperty)(C)} === undefined`;return k?(0,e.or)(b,(0,e.not)(l(v,m,C))):b}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(C=>!(0,t.alwaysValidSchema)(v,m[C]))}Be.schemaProperties=p;function f({schemaCode:v,data:m,it:{gen:C,topSchemaRef:k,schemaPath:b,errorPath:S},it:x},I,L,$){const N=$?(0,e._)`${v}, ${m}, ${k}${b}`:m,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const U=(0,e._)`${N}, ${C.object(...A)}`;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}},C){const k=m.unicodeRegExp?"u":"",{regExp:b}=m.code,S=b(C,k);return v.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${b.code==="new RegExp"?g:(0,n.useFunc)(v,b)}(${C}, ${k})`})}Be.usePattern=_;function y(v){const{gen:m,data:C,keyword:k,it:b}=v,S=m.name("valid");if(b.allErrors){const I=m.let("valid",!0);return x(()=>m.assign(I,!1)),I}return m.var(S,!0),x(()=>m.break()),S;function x(I){const L=m.const("len",(0,e._)`${C}.length`);m.forRange("i",0,L,$=>{v.subschema({keyword:k,dataProp:$,dataPropType:t.Type.Num},S),m.if((0,e.not)(S),I)})}}Be.validateArray=y;function w(v){const{gen:m,schema:C,keyword:k,it:b}=v;if(!Array.isArray(C))throw new Error("ajv implementation error");if(C.some(L=>(0,t.alwaysValidSchema)(b,L))&&!b.opts.unevaluated)return;const x=m.let("valid",!1),I=m.name("_valid");m.block(()=>C.forEach((L,$)=>{const N=v.subschema({keyword:k,schemaProp:$,compositeRule:!0},I);m.assign(x,(0,e._)`${x} || ${I}`),v.mergeValidEvaluated(N,I)||m.if((0,e.not)(x))})),v.result(x,()=>v.reset(),()=>v.error(!0))}return Be.validateUnion=w,Be}var Rp;function W1(){if(Rp)return hr;Rp=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.validateKeywordUsage=hr.validSchemaType=hr.funcKeywordCode=hr.macroKeywordCode=void 0;const e=Ne(),t=pn(),r=mr(),n=wa();function o(p,f){const{gen:g,keyword:_,schema:y,parentSchema:w,it:v}=p,m=f.macro.call(v.self,y,w,v),C=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:C,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}hr.macroKeywordCode=o;function s(p,f){var g;const{gen:_,keyword:y,schema:w,parentSchema:v,$data:m,it:C}=p;l(C,f);const k=!m&&f.compile?f.compile.call(C.self,w,v,C):f.validate,b=c(_,y,k),S=_.let("valid");p.block$data(S,x),p.ok((g=f.valid)!==null&&g!==void 0?g:S);function x(){if(f.errors===!1)$(),f.modifying&&a(p),N(()=>p.error());else{const A=f.async?I():L();f.modifying&&a(p),N(()=>i(p,A))}}function I(){const A=_.let("ruleErrs",null);return _.try(()=>$((0,e._)`await `),U=>_.assign(S,!1).if((0,e._)`${U} instanceof ${C.ValidationError}`,()=>_.assign(A,(0,e._)`${U}.errors`),()=>_.throw(U))),A}function L(){const A=(0,e._)`${b}.errors`;return _.assign(A,null),$(e.nil),A}function $(A=f.async?(0,e._)`await `:e.nil){const U=C.opts.passContext?t.default.this:t.default.self,V=!("compile"in f&&!m||f.schema===!1);_.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,b,U,V)}`,f.modifying)}function N(A){var U;_.if((0,e.not)((U=f.valid)!==null&&U!==void 0?U:S),A)}}hr.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")}hr.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 C=`keyword "${w}" value is invalid at path "${_}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(C);else throw new Error(C)}}return hr.validateKeywordUsage=h,hr}var Jr={},Pp;function G1(){if(Pp)return Jr;Pp=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.extendSubschemaMode=Jr.extendSubschemaData=Jr.getSubschema=void 0;const e=Ne(),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')}Jr.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]}}Jr.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 Jr.extendSubschemaMode=o,Jr}var jt={},jl,Mp;function Op(){return Mp||(Mp=1,jl=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}),jl}var Dl={exports:{}},Np;function K1(){if(Np)return Dl.exports;Np=1;var e=Dl.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 Dl.exports}var Ap;function ka(){if(Ap)return jt;Ap=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.getSchemaRefs=jt.resolveUrl=jt.normalizeId=jt._getFullPath=jt.getFullPath=jt.inlineRef=void 0;const e=Ue(),t=Op(),r=K1(),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}jt.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)}jt.getFullPath=l;function c(_,y){return _.serialize(y).split("#")[0]+"#"}jt._getFullPath=c;const u=/#\/?$/;function h(_){return _?_.replace(u,""):""}jt.normalizeId=h;function p(_,y,w){return w=h(w),_.resolve(y,w)}jt.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),C={"":m},k=l(v,m,!1),b={},S=new Set;return r(_,{allKeys:!0},(L,$,N,A)=>{if(A===void 0)return;const U=k+$;let V=C[A];typeof L[w]=="string"&&(V=Q.call(this,L[w])),_e.call(this,L.$anchor),_e.call(this,L.$dynamicAnchor),C[$]=V;function Q(te){const ge=this.opts.uriResolver.resolve;if(te=h(V?ge(V,te):te),S.has(te))throw I(te);S.add(te);let H=this.refs[te];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(L,H.schema,te):te!==h(U)&&(te[0]==="#"?(x(L,b[te],te),b[te]=L):this.refs[te]=U),te}function _e(te){if(typeof te=="string"){if(!f.test(te))throw new Error(`invalid anchor "${te}"`);Q.call(this,`#${te}`)}}}),b;function x(L,$,N){if($!==void 0&&!t(L,$))throw I(N)}function I(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return jt.getSchemaRefs=g,jt}var qp;function Ta(){if(qp)return Hr;qp=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.getData=Hr.KeywordCxt=Hr.validateFunctionCode=void 0;const e=B1(),t=ba(),r=Ip(),n=ba(),o=J1(),s=W1(),a=G1(),i=Ne(),l=pn(),c=ka(),u=Ue(),h=wa();function p(z){if(k(z)&&(S(z),C(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Hr.validateFunctionCode=p;function f({gen:z,validateName:F,schema:K,schemaEnv:ee,opts:le},we){le.code.es5?z.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,ee.$async,()=>{z.code((0,i._)`"use strict"; ${v(K,le)}`),_(z,le),z.code(we)}):z.func(F,(0,i._)`${l.default.data}, ${g(le)}`,ee.$async,()=>z.code(v(K,le)).code(we))}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:K,gen:ee}=z;f(z,()=>{K.$comment&&F.$comment&&A(z),L(z),ee.let(l.default.vErrors,null),ee.let(l.default.errors,0),K.unevaluated&&w(z),x(z),U(z)})}function w(z){const{gen:F,validateName:K}=z;z.evaluated=F.const("evaluated",(0,i._)`${K}.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 K=typeof z=="object"&&z[F.schemaId];return K&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${K} */`:i.nil}function m(z,F){if(k(z)&&(S(z),C(z))){b(z,F);return}(0,e.boolOrEmptySchema)(z,F)}function C({schema:z,self:F}){if(typeof z=="boolean")return!z;for(const K in z)if(F.RULES.all[K])return!0;return!1}function k(z){return typeof z.schema!="boolean"}function b(z,F){const{schema:K,gen:ee,opts:le}=z;le.$comment&&K.$comment&&A(z),$(z),N(z);const we=ee.const("_errs",l.default.errors);x(z,we),ee.var(F,(0,i._)`${we} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),I(z)}function x(z,F){if(z.opts.jtd)return Q(z,[],!1,F);const K=(0,t.getSchemaTypes)(z.schema),ee=(0,t.coerceAndCheckDataType)(z,K);Q(z,K,!ee,F)}function I(z){const{schema:F,errSchemaPath:K,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 "${K}"`)}function L(z){const{schema:F,opts:K}=z;F.default!==void 0&&K.useDefaults&&K.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function $(z){const F=z.schema[z.opts.schemaId];F&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,F))}function N(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:F,schema:K,errSchemaPath:ee,opts:le}){const we=K.$comment;if(le.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${we})`);else if(typeof le.$comment=="function"){const et=(0,i.str)`${ee}/$comment`,pt=z.scopeValue("root",{ref:F.root});z.code((0,i._)`${l.default.self}.opts.$comment(${we}, ${et}, ${pt}.schema)`)}}function U(z){const{gen:F,schemaEnv:K,validateName:ee,ValidationError:le,opts:we}=z;K.$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),we.unevaluated&&V(z),F.return((0,i._)`${l.default.errors} === 0`))}function V({gen:z,evaluated:F,props:K,items:ee}){K instanceof i.Name&&z.assign((0,i._)`${F}.props`,K),ee instanceof i.Name&&z.assign((0,i._)`${F}.items`,ee)}function Q(z,F,K,ee){const{gen:le,schema:we,data:et,allErrors:pt,opts:mt,self:st}=z,{RULES:P}=st;if(we.$ref&&(mt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(we,P))){le.block(()=>G(z,"$ref",P.all.$ref.definition));return}mt.jtd||te(z,F),le.block(()=>{for(const Oe of P.rules)ne(Oe);ne(P.post)});function ne(Oe){(0,r.shouldUseGroup)(we,Oe)&&(Oe.type?(le.if((0,n.checkDataType)(Oe.type,et,mt.strictNumbers)),_e(z,Oe),F.length===1&&F[0]===Oe.type&&K&&(le.else(),(0,n.reportTypeError)(z)),le.endIf()):_e(z,Oe),pt||le.if((0,i._)`${l.default.errors} === ${ee||0}`))}}function _e(z,F){const{gen:K,schema:ee,opts:{useDefaults:le}}=z;le&&(0,o.assignDefaults)(z,F.type),K.block(()=>{for(const we of F.rules)(0,r.shouldUseRule)(ee,we)&&G(z,we.keyword,we.definition,F.type)})}function te(z,F){z.schemaEnv.meta||!z.opts.strictTypes||(ge(z,F),z.opts.allowUnionTypes||H(z,F),M(z,z.dataTypes))}function ge(z,F){if(F.length){if(!z.dataTypes.length){z.dataTypes=F;return}F.forEach(K=>{Z(z.dataTypes,K)||O(z,`type "${K}" not allowed by context "${z.dataTypes.join(",")}"`)}),E(z,F)}}function H(z,F){F.length>1&&!(F.length===2&&F.includes("null"))&&O(z,"use allowUnionTypes to allow union type keyword")}function M(z,F){const K=z.self.RULES.all;for(const ee in K){const le=K[ee];if(typeof le=="object"&&(0,r.shouldUseRule)(z.schema,le)){const{type:we}=le.definition;we.length&&!we.some(et=>B(F,et))&&O(z,`missing type "${we.join(",")}" for keyword "${ee}"`)}}}function B(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 K=[];for(const ee of z.dataTypes)Z(F,ee)?K.push(ee):F.includes("integer")&&ee==="number"&&K.push("integer");z.dataTypes=K}function O(z,F){const K=z.schemaEnv.baseId+z.errSchemaPath;F+=` at "${K}" (strictTypes)`,(0,u.checkStrictMode)(z,F,z.opts.strictTypes)}class D{constructor(F,K,ee){if((0,s.validateKeywordUsage)(F,K,ee),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=ee,this.data=F.data,this.schema=F.schema[ee],this.$data=K.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,ee,this.$data),this.schemaType=K.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=K,this.$data)this.schemaCode=F.gen.const("vSchema",Ie(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,K.schemaType,K.allowUndefined))throw new Error(`${ee} value must be ${JSON.stringify(K.schemaType)}`);("code"in K?K.trackErrors:K.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,K,ee){this.failResult((0,i.not)(F),K,ee)}failResult(F,K,ee){this.gen.if(F),ee?ee():this.error(),K?(this.gen.else(),K(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,K){this.failResult((0,i.not)(F),void 0,K)}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:K}=this;this.fail((0,i._)`${K} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,K,ee){if(K){this.setParams(K),this._error(F,ee),this.setParams({});return}this._error(F,ee)}_error(F,K){(F?h.reportExtraError:h.reportError)(this,this.def.error,K)}$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,K){K?Object.assign(this.params,F):this.params=F}block$data(F,K,ee=i.nil){this.gen.block(()=>{this.check$data(F,ee),K()})}check$data(F=i.nil,K=i.nil){if(!this.$data)return;const{gen:ee,schemaCode:le,schemaType:we,def:et}=this;ee.if((0,i.or)((0,i._)`${le} === undefined`,K)),F!==i.nil&&ee.assign(F,!0),(we.length||et.validateSchema)&&(ee.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&ee.assign(F,!1)),ee.else()}invalid$data(){const{gen:F,schemaCode:K,schemaType:ee,def:le,it:we}=this;return(0,i.or)(et(),pt());function et(){if(ee.length){if(!(K instanceof i.Name))throw new Error("ajv implementation error");const mt=Array.isArray(ee)?ee:[ee];return(0,i._)`${(0,n.checkDataTypes)(mt,K,we.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function pt(){if(le.validateSchema){const mt=F.scopeValue("validate$data",{ref:le.validateSchema});return(0,i._)`!${mt}(${K})`}return i.nil}}subschema(F,K){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,K),le}mergeEvaluated(F,K){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,K)),ee.items!==!0&&F.items!==void 0&&(ee.items=u.mergeEvaluated.items(le,F.items,ee.items,K)))}mergeValidEvaluated(F,K){const{it:ee,gen:le}=this;if(ee.opts.unevaluated&&(ee.props!==!0||ee.items!==!0))return le.if(K,()=>this.mergeEvaluated(F,i.Name)),!0}}Hr.KeywordCxt=D;function G(z,F,K,ee){const le=new D(z,K,F);"code"in K?K.code(le,ee):le.$data&&K.validate?(0,s.funcKeywordCode)(le,K):"macro"in K?(0,s.macroKeywordCode)(le,K):(K.compile||K.validate)&&(0,s.funcKeywordCode)(le,K)}const re=/^\/(?:[^~]|~0|~1)*$/,ie=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ie(z,{dataLevel:F,dataNames:K,dataPathArr:ee}){let le,we;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!re.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);le=z,we=l.default.rootData}else{const st=ie.exec(z);if(!st)throw new Error(`Invalid JSON-pointer: ${z}`);const P=+st[1];if(le=st[2],le==="#"){if(P>=F)throw new Error(mt("property/index",P));return ee[F-P]}if(P>F)throw new Error(mt("data",P));if(we=K[F-P],!le)return we}let et=we;const pt=le.split("/");for(const st of pt)st&&(we=(0,i._)`${we}${(0,i.getProperty)((0,u.unescapeJsonPointer)(st))}`,et=(0,i._)`${et} && ${we}`);return et;function mt(st,P){return`Cannot access ${st} ${P} levels up, current level is ${F}`}}return Hr.getData=Ie,Hr}var Ca={},Lp;function Ul(){if(Lp)return Ca;Lp=1,Object.defineProperty(Ca,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ca.default=e,Ca}var Sa={},jp;function Ia(){if(jp)return Sa;jp=1,Object.defineProperty(Sa,"__esModule",{value:!0});const e=ka();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 Sa.default=t,Sa}var Yt={},Dp;function zl(){if(Dp)return Yt;Dp=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;const e=Ne(),t=Ul(),r=pn(),n=ka(),o=Ue(),s=Ta();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:C}=this.opts.code,{ownProperties:k}=this.opts,b=new e.CodeGen(this.scope,{es5:m,lines:C,ownProperties:k});let S;y.$async&&(S=b.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const x=b.scopeName("validate");y.validateName=x;const I={gen:b,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:b.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:x,ValidationError:S,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),b.optimize(this.opts.code.optimize);const $=b.toString();L=`${b.scopeRefs(r.default.scope)}return ${$}`,this.opts.code.process&&(L=this.opts.code.process(L,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(x,{ref:A}),A.errors=null,A.schema=y.schema,A.schemaEnv=y,y.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:x,validateCode:$,scopeValues:b._values}),this.opts.unevaluated){const{props:U,items:V}=I;A.evaluated={props:U instanceof e.Name?void 0:U,items:V instanceof e.Name?void 0:V,dynamicProps:U instanceof e.Name,dynamicItems:V instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch($){throw delete y.validate,delete y.validateName,L&&this.logger.error("Error compiling schema, function code:",L),$}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 C=y.refs[v];if(C)return C;let k=p.call(this,y,v);if(k===void 0){const b=(m=y.localRefs)===null||m===void 0?void 0:m[v],{schemaId:S}=this.opts;b&&(k=new a({schema:b,schemaId:S,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 C=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&m===C)return _.call(this,v,y);const k=(0,n.normalizeId)(m),b=this.refs[k]||this.schemas[k];if(typeof b=="string"){const S=f.call(this,y,b);return typeof S?.schema!="object"?void 0:_.call(this,v,S)}if(typeof b?.schema=="object"){if(b.validate||i.call(this,b),k===(0,n.normalizeId)(w)){const{schema:S}=b,{schemaId:x}=this.opts,I=S[x];return I&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,I)),new a({schema:S,schemaId:x,root:y,baseId:C})}return _.call(this,v,b)}}Yt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(y,{baseId:w,schema:v,root:m}){var C;if(((C=y.fragment)===null||C===void 0?void 0:C[0])!=="/")return;for(const S of y.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const x=v[(0,o.unescapeFragment)(S)];if(x===void 0)return;v=x;const I=typeof v=="object"&&v[this.opts.schemaId];!g.has(S)&&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 S=(0,n.resolveUrl)(this.opts.uriResolver,w,v.$ref);k=f.call(this,m,S)}const{schemaId:b}=this.opts;if(k=k||new a({schema:v,schemaId:b,root:m,baseId:w}),k.schema!==k.root.schema)return k}return Yt}const Y1={$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 xa={},Ho={exports:{}},Zl,Up;function zp(){if(Up)return Zl;Up=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 C=0;C<p.length;C++){const k=p[C];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(v=!0),!m(y,_,g))break;if(++f>7){g.error=!0;break}C>0&&p[C-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 Fl,Zp;function Q1(){if(Zp)return Fl;Zp=1;const{isUUID:e}=zp(),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 b=String(k.scheme).toLowerCase()==="https";return(k.port===(b?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[b,S]=k.resourceName.split("?");k.path=b&&b!=="/"?b:void 0,k.query=S,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,b){if(!k.path)return k.error="URN can not be parsed",k;const S=k.path.match(t);if(S){const x=b.scheme||k.scheme||"urn";k.nid=S[1].toLowerCase(),k.nss=S[2];const I=`${x}:${b.nid||k.nid}`,L=C(I);k.path=void 0,L&&(k=L.parse(k,b))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,b){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=b.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),I=`${S}:${b.nid||x}`,L=C(I);L&&(k=L.serialize(k,b));const $=k,N=k.nss;return $.path=`${x||b.nid}:${N}`,b.skipEscape=!0,$}function h(k,b){const S=k;return S.uuid=S.nss,S.nss=void 0,!b.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(k){const b=k;return b.nss=(k.uuid||"").toLowerCase(),b}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 C(k){return k&&(m[k]||m[k.toLowerCase()])||void 0}return Fl={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:C},Fl}var Fp;function X1(){if(Fp)return Ho.exports;Fp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=zp(),{SCHEMES:a,getSchemeHandler:i}=Q1();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"},C=u(g(y,m),g(w,m),m,!0);return m.skipEscape=!0,p(C,m)}function u(y,w,v,m){const C={};return m||(y=g(p(y,v),v),w=g(p(w,v),v)),v=v||{},!v.tolerant&&w.scheme?(C.scheme=w.scheme,C.userinfo=w.userinfo,C.host=w.host,C.port=w.port,C.path=t(w.path||""),C.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(C.userinfo=w.userinfo,C.host=w.host,C.port=w.port,C.path=t(w.path||""),C.query=w.query):(w.path?(w.path[0]==="/"?C.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?C.path="/"+w.path:y.path?C.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:C.path=w.path,C.path=t(C.path)),C.query=w.query):(C.path=y.path,w.query!==void 0?C.query=w.query:C.query=y.query),C.userinfo=y.userinfo,C.host=y.host,C.port=y.port),C.scheme=y.scheme),C.fragment=w.fragment,C}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),C=[],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&&C.push(v.scheme,":");const b=r(v);if(b!==void 0&&(m.reference!=="suffix"&&C.push("//"),C.push(b),v.path&&v.path[0]!=="/"&&C.push("/")),v.path!==void 0){let S=v.path;!m.absolutePath&&(!k||!k.absolutePath)&&(S=t(S)),b===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),C.push(S)}return v.query!==void 0&&C.push("?",v.query),v.fragment!==void 0&&C.push("#",v.fragment),C.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 C=!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(),C=x.isIPV6}else C=!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 b=i(v.scheme||m.scheme);if(!v.unicodeSupport&&(!b||!b.unicodeSupport)&&m.host&&(v.domainHost||b&&b.domainHost)&&C===!1&&s(m.host))try{m.host=URL.domainToASCII(m.host.toLowerCase())}catch(S){m.error=m.error||"Host's domain name can not be converted to ASCII: "+S}(!b||b&&!b.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)))),b&&b.parse&&b.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 Ho.exports=_,Ho.exports.default=_,Ho.exports.fastUri=_,Ho.exports}var Vp;function ew(){if(Vp)return xa;Vp=1,Object.defineProperty(xa,"__esModule",{value:!0});const e=X1();return e.code='require("ajv/dist/runtime/uri").default',xa.default=e,xa}var Hp;function tw(){return Hp||(Hp=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=Ta();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ne();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=Ul(),o=Ia(),s=Cp(),a=zl(),i=Ne(),l=ka(),c=ba(),u=Ue(),h=Y1,p=ew(),f=(H,M)=>new RegExp(H,M);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(H){var M,B,Z,E,O,D,G,re,ie,Ie,z,F,K,ee,le,we,et,pt,mt,st,P,ne,Oe,qe,pr;const tt=H.strict,nr=(M=H.code)===null||M===void 0?void 0:M.optimize,ln=nr===!0||nr===void 0?1:nr||0,rt=(Z=(B=H.code)===null||B===void 0?void 0:B.regExp)!==null&&Z!==void 0?Z:f,xe=(E=H.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(D=(O=H.strictSchema)!==null&&O!==void 0?O:tt)!==null&&D!==void 0?D:!0,strictNumbers:(re=(G=H.strictNumbers)!==null&&G!==void 0?G:tt)!==null&&re!==void 0?re:!0,strictTypes:(Ie=(ie=H.strictTypes)!==null&&ie!==void 0?ie:tt)!==null&&Ie!==void 0?Ie:"log",strictTuples:(F=(z=H.strictTuples)!==null&&z!==void 0?z:tt)!==null&&F!==void 0?F:"log",strictRequired:(ee=(K=H.strictRequired)!==null&&K!==void 0?K:tt)!==null&&ee!==void 0?ee:!1,code:H.code?{...H.code,optimize:ln,regExp:rt}:{optimize:ln,regExp:rt},loopRequired:(le=H.loopRequired)!==null&&le!==void 0?le:v,loopEnum:(we=H.loopEnum)!==null&&we!==void 0?we:v,meta:(et=H.meta)!==null&&et!==void 0?et:!0,messages:(pt=H.messages)!==null&&pt!==void 0?pt:!0,inlineRefs:(mt=H.inlineRefs)!==null&&mt!==void 0?mt:!0,schemaId:(st=H.schemaId)!==null&&st!==void 0?st:"$id",addUsedSchema:(P=H.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(ne=H.validateSchema)!==null&&ne!==void 0?ne:!0,validateFormats:(Oe=H.validateFormats)!==null&&Oe!==void 0?Oe:!0,unicodeRegExp:(qe=H.unicodeRegExp)!==null&&qe!==void 0?qe:!0,int32range:(pr=H.int32range)!==null&&pr!==void 0?pr:!0,uriResolver:xe}}class C{constructor(M={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,M=this.opts={...M,...m(M)};const{es5:B,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:_,es5:B,lines:Z}),this.logger=N(M.logger);const E=M.validateFormats;M.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,y,M,"NOT SUPPORTED"),k.call(this,w,M,"DEPRECATED","warn"),this._metaOpts=L.call(this),M.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),M.keywords&&I.call(this,M.keywords),typeof M.meta=="object"&&this.addMetaSchema(M.meta),S.call(this),M.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:M,meta:B,schemaId:Z}=this.opts;let E=h;Z==="id"&&(E={...h},E.id=E.$id,delete E.$id),B&&M&&this.addMetaSchema(E,E[Z],!1)}defaultMeta(){const{meta:M,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof M=="object"?M[B]||M:void 0}validate(M,B){let Z;if(typeof M=="string"){if(Z=this.getSchema(M),!Z)throw new Error(`no schema with key or ref "${M}"`)}else Z=this.compile(M);const E=Z(B);return"$async"in Z||(this.errors=Z.errors),E}compile(M,B){const Z=this._addSchema(M,B);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(M,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return E.call(this,M,B);async function E(Ie,z){await O.call(this,Ie.$schema);const F=this._addSchema(Ie,z);return F.validate||D.call(this,F)}async function O(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 G.call(this,z),await re.call(this,z.missingSchema),D.call(this,Ie)}}function G({missingSchema:Ie,missingRef:z}){if(this.refs[Ie])throw new Error(`AnySchema ${Ie} is loaded but ${z} cannot be resolved`)}async function re(Ie){const z=await ie.call(this,Ie);this.refs[Ie]||await O.call(this,z.$schema),this.refs[Ie]||this.addSchema(z,Ie,B)}async function ie(Ie){const z=this._loading[Ie];if(z)return z;try{return await(this._loading[Ie]=Z(Ie))}finally{delete this._loading[Ie]}}}addSchema(M,B,Z,E=this.opts.validateSchema){if(Array.isArray(M)){for(const D of M)this.addSchema(D,void 0,Z,E);return this}let O;if(typeof M=="object"){const{schemaId:D}=this.opts;if(O=M[D],O!==void 0&&typeof O!="string")throw new Error(`schema ${D} must be string`)}return B=(0,l.normalizeId)(B||O),this._checkUnique(B),this.schemas[B]=this._addSchema(M,Z,B,E,!0),this}addMetaSchema(M,B,Z=this.opts.validateSchema){return this.addSchema(M,B,!0,Z),this}validateSchema(M,B){if(typeof M=="boolean")return!0;let Z;if(Z=M.$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,M);if(!E&&B){const O="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(O);else throw new Error(O)}return E}getSchema(M){let B;for(;typeof(B=b.call(this,M))=="string";)M=B;if(B===void 0){const{schemaId:Z}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:Z});if(B=a.resolveSchema.call(this,E,M),!B)return;this.refs[M]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema(M){if(M instanceof RegExp)return this._removeAllSchemas(this.schemas,M),this._removeAllSchemas(this.refs,M),this;switch(typeof M){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const B=b.call(this,M);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[M],delete this.refs[M],this}case"object":{const B=M;this._cache.delete(B);let Z=M[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(M){for(const B of M)this.addKeyword(B);return this}addKeyword(M,B){let Z;if(typeof M=="string")Z=M,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=Z);else if(typeof M=="object"&&B===void 0){if(B=M,Z=B.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,B),!B)return(0,u.eachItem)(Z,O=>V.call(this,O)),this;_e.call(this,B);const E={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(Z,E.type.length===0?O=>V.call(this,O,E):O=>E.type.forEach(D=>V.call(this,O,E,D))),this}getKeyword(M){const B=this.RULES.all[M];return typeof B=="object"?B.definition:!!B}removeKeyword(M){const{RULES:B}=this;delete B.keywords[M],delete B.all[M];for(const Z of B.rules){const E=Z.rules.findIndex(O=>O.keyword===M);E>=0&&Z.rules.splice(E,1)}return this}addFormat(M,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[M]=B,this}errorsText(M=this.errors,{separator:B=", ",dataVar:Z="data"}={}){return!M||M.length===0?"No errors":M.map(E=>`${Z}${E.instancePath} ${E.message}`).reduce((E,O)=>E+B+O)}$dataMetaSchema(M,B){const Z=this.RULES.all;M=JSON.parse(JSON.stringify(M));for(const E of B){const O=E.split("/").slice(1);let D=M;for(const G of O)D=D[G];for(const G in Z){const re=Z[G];if(typeof re!="object")continue;const{$data:ie}=re.definition,Ie=D[G];ie&&Ie&&(D[G]=ge(Ie))}}return M}_removeAllSchemas(M,B){for(const Z in M){const E=M[Z];(!B||B.test(Z))&&(typeof E=="string"?delete M[Z]:E&&!E.meta&&(this._cache.delete(E.schema),delete M[Z]))}}_addSchema(M,B,Z,E=this.opts.validateSchema,O=this.opts.addUsedSchema){let D;const{schemaId:G}=this.opts;if(typeof M=="object")D=M[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof M!="boolean")throw new Error("schema must be object or boolean")}let re=this._cache.get(M);if(re!==void 0)return re;Z=(0,l.normalizeId)(D||Z);const ie=l.getSchemaRefs.call(this,M,Z);return re=new a.SchemaEnv({schema:M,schemaId:G,meta:B,baseId:Z,localRefs:ie}),this._cache.set(re.schema,re),O&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=re),E&&this.validateSchema(M,!0),re}_checkUnique(M){if(this.schemas[M]||this.refs[M])throw new Error(`schema with key or id "${M}" already exists`)}_compileSchemaEnv(M){if(M.meta?this._compileMetaSchema(M):a.compileSchema.call(this,M),!M.validate)throw new Error("ajv implementation error");return M.validate}_compileMetaSchema(M){const B=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,M)}finally{this.opts=B}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function k(H,M,B,Z="error"){for(const E in H){const O=E;O in M&&this.logger[Z](`${B}: option ${E}. ${H[O]}`)}}function b(H){return H=(0,l.normalizeId)(H),this.schemas[H]||this.refs[H]}function S(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const M in H)this.addSchema(H[M],M)}function x(){for(const H in this.opts.formats){const M=this.opts.formats[H];M&&this.addFormat(H,M)}}function I(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const M in H){const B=H[M];B.keyword||(B.keyword=M),this.addKeyword(B)}}function L(){const H={...this.opts};for(const M of g)delete H[M];return H}const $={log(){},warn(){},error(){}};function N(H){if(H===!1)return $;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 A=/^[a-z_$][a-z0-9_$:-]*$/i;function U(H,M){const{RULES:B}=this;if((0,u.eachItem)(H,Z=>{if(B.keywords[Z])throw new Error(`Keyword ${Z} is already defined`);if(!A.test(Z))throw new Error(`Keyword ${Z} has invalid name`)}),!!M&&M.$data&&!("code"in M||"validate"in M))throw new Error('$data keyword must have "code" or "validate" function')}function V(H,M,B){var Z;const E=M?.post;if(B&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:O}=this;let D=E?O.post:O.rules.find(({type:re})=>re===B);if(D||(D={type:B,rules:[]},O.rules.push(D)),O.keywords[H]=!0,!M)return;const G={keyword:H,definition:{...M,type:(0,c.getJSONTypes)(M.type),schemaType:(0,c.getJSONTypes)(M.schemaType)}};M.before?Q.call(this,D,G,M.before):D.rules.push(G),O.all[H]=G,(Z=M.implements)===null||Z===void 0||Z.forEach(re=>this.addKeyword(re))}function Q(H,M,B){const Z=H.rules.findIndex(E=>E.keyword===B);Z>=0?H.rules.splice(Z,0,M):(H.rules.push(M),this.logger.warn(`rule ${B} is not defined`))}function _e(H){let{metaSchema:M}=H;M!==void 0&&(H.$data&&this.opts.$data&&(M=ge(M)),H.validateSchema=this.compile(M,!0))}const te={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ge(H){return{anyOf:[H,te]}}})(Ol)),Ol}var Ea={},$a={},Ra={},Bp;function rw(){if(Bp)return Ra;Bp=1,Object.defineProperty(Ra,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Ra.default=e,Ra}var fn={},Jp;function nw(){if(Jp)return fn;Jp=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.callRef=fn.getValidate=void 0;const e=Ia(),t=mr(),r=Ne(),n=pn(),o=zl(),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 C();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 b(m);function C(){if(g===v)return l(c,_,g,g.$async);const S=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${S}.validate`,v,v.$async)}function k(S){const x=i(c,S);l(c,x,S,S.$async)}function b(S){const x=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),I=u.name("valid"),L=c.subschema({schema:S,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`}fn.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():C();function m(){if(!y.$async)throw new Error("async schema referenced by sync schema");const S=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),b(u),_||f.assign(S,!0)},x=>{f.if((0,r._)`!(${x} instanceof ${g.ValidationError})`,()=>f.throw(x)),k(x),_||f.assign(S,!1)}),c.ok(S)}function C(){c.result((0,t.callValidateCode)(c,u,v),()=>b(u),()=>k(u))}function k(S){const x=(0,r._)`${S}.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 b(S){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._)`${S}.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._)`${S}.evaluated.items`);g.items=s.mergeEvaluated.items(f,L,g.items,r.Name)}}}return fn.callRef=l,fn.default=a,fn}var Wp;function ow(){if(Wp)return $a;Wp=1,Object.defineProperty($a,"__esModule",{value:!0});const e=rw(),t=nw(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return $a.default=r,$a}var Pa={},Ma={},Gp;function sw(){if(Gp)return Ma;Gp=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=Ne(),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 Ma.default=o,Ma}var Oa={},Kp;function aw(){if(Kp)return Oa;Kp=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=Ne(),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 Oa.default=r,Oa}var Na={},Aa={},Yp;function iw(){if(Yp)return Aa;Yp=1,Object.defineProperty(Aa,"__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 Aa.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Aa}var Qp;function lw(){if(Qp)return Na;Qp=1,Object.defineProperty(Na,"__esModule",{value:!0});const e=Ne(),t=Ue(),r=iw(),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 Na.default=o,Na}var qa={},Xp;function cw(){if(Xp)return qa;Xp=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=mr(),t=Ue(),r=Ne(),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 qa.default=o,qa}var La={},ef;function uw(){if(ef)return La;ef=1,Object.defineProperty(La,"__esModule",{value:!0});const e=Ne(),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 La.default=r,La}var ja={},tf;function dw(){if(tf)return ja;tf=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=mr(),t=Ne(),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 C of i)if(v?.[C]===void 0&&!m.has(C)){const k=h.schemaEnv.baseId+h.errSchemaPath,b=`required property "${C}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(h,b,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 ja.default=o,ja}var Da={},rf;function pw(){if(rf)return Da;rf=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=Ne(),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 Da.default=r,Da}var Ua={},za={},nf;function Vl(){if(nf)return za;nf=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Op();return e.code='require("ajv/dist/runtime/equal").default',za.default=e,za}var of;function fw(){if(of)return Ua;of=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=ba(),t=Ne(),r=Ue(),n=Vl(),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 C=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:C,j:k}),i.assign(g,!0),i.if((0,t._)`${C} > 1`,()=>(w()?v:m)(C,k))}function w(){return _.length>0&&!_.some(C=>C==="object"||C==="array")}function v(C,k){const b=i.name("item"),S=(0,e.checkDataTypes)(_,b,f.opts.strictNumbers,e.DataType.Wrong),x=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${C}--;`,()=>{i.let(b,(0,t._)`${l}[${C}]`),i.if(S,(0,t._)`continue`),_.length>1&&i.if((0,t._)`typeof ${b} == "string"`,(0,t._)`${b} += "_"`),i.if((0,t._)`typeof ${x}[${b}] == "number"`,()=>{i.assign(k,(0,t._)`${x}[${b}]`),a.error(),i.assign(g,!1).break()}).code((0,t._)`${x}[${b}] = ${C}`)})}function m(C,k){const b=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${C}--;`,()=>i.for((0,t._)`${k} = ${C}; ${k}--;`,()=>i.if((0,t._)`${b}(${l}[${C}], ${l}[${k}])`,()=>{a.error(),i.assign(g,!1).break(S)})))}}};return Ua.default=s,Ua}var Za={},sf;function hw(){if(sf)return Za;sf=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Ne(),t=Ue(),r=Vl(),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 Fa={},af;function mw(){if(af)return Fa;af=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Ne(),t=Ue(),r=Vl(),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,C)=>w(v,C)))}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 C=c[m];return typeof C=="object"&&C!==null?(0,e._)`${g()}(${i}, ${v}[${m}])`:(0,e._)`${i} === ${C}`}}};return Fa.default=o,Fa}var lf;function gw(){if(lf)return Pa;lf=1,Object.defineProperty(Pa,"__esModule",{value:!0});const e=sw(),t=aw(),r=lw(),n=cw(),o=uw(),s=dw(),a=pw(),i=fw(),l=hw(),c=mw(),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 Pa.default=u,Pa}var Va={},so={},cf;function uf(){if(cf)return so;cf=1,Object.defineProperty(so,"__esModule",{value:!0}),so.validateAdditionalItems=void 0;const e=Ne(),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 so.validateAdditionalItems=o,so.default=n,so}var Ha={},ao={},df;function pf(){if(df)return ao;df=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.validateTuple=void 0;const e=Ne(),t=Ue(),r=mr(),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,C=m===y.minItems&&(m===y.maxItems||y[a]===!1);if(w.strictTuples&&!C){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 ao.validateTuple=o,ao.default=n,ao}var ff;function yw(){if(ff)return Ha;ff=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=pf(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Ha.default=t,Ha}var Ba={},hf;function vw(){if(hf)return Ba;hf=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Ne(),t=Ue(),r=mr(),n=uf(),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 Ba.default=s,Ba}var Ja={},mf;function _w(){if(mf)return Ja;mf=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Ne(),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"),C=s.let("count",0);w(m,()=>s.if(m,()=>v(C)))}function w(m,C){s.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},m),C()})}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 Ja.default=n,Ja}var Hl={},gf;function ww(){return gf||(gf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ne(),r=Ue(),n=mr();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
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 f in l){if(f==="__proto__")continue;const p=Array.isArray(l[f])?c:u;p[f]=l[f]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:f,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const y in c){const w=c[y];if(w.length===0)continue;const g=(0,n.propertyInData)(u,f,y,p.opts.ownProperties);l.setParams({property:y,depsCount:w.length,deps:w.join(", ")}),p.allErrors?u.if(g,()=>{for(const b of w)(0,n.checkReportMissingProp)(l,b)}):(u.if((0,t._)`${g} && (${(0,n.checkMissingProp)(l,w,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:f,keyword:p,it:h}=l,y=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(h,c[w])||(u.if((0,n.propertyInData)(u,f,w,h.opts.ownProperties),()=>{const g=l.subschema({keyword:p,schemaProp:w},y);l.mergeValidEvaluated(g,y)},()=>u.var(y,!0)),l.ok(y))}e.validateSchemaDeps=i,e.default=o})(El)),El}var Na={},Xp;function rw(){if(Xp)return Na;Xp=1,Object.defineProperty(Na,"__esModule",{value:!0});const e=Ne(),t=Ze(),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 Na.default=n,Na}var qa={},ef;function tf(){if(ef)return qa;ef=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=ir(),t=Ne(),r=en(),n=Ze(),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:f,it:p}=a;if(!f)throw new Error("ajv implementation error");const{allErrors:h,opts:y}=p;if(p.props=!0,y.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const w=(0,e.allSchemaProperties)(c.properties),g=(0,e.allSchemaProperties)(c.patternProperties);b(),a.ok((0,t._)`${f} === ${r.default.errors}`);function b(){i.forIn("key",u,_=>{!w.length&&!g.length?T(_):i.if(v(_),()=>T(_))})}function v(_){let S;if(w.length>8){const $=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,$,_)}else w.length?S=(0,t.or)(...w.map($=>(0,t._)`${_} === ${$}`)):S=t.nil;return g.length&&(S=(0,t.or)(S,...g.map($=>(0,t._)`${(0,e.usePattern)(a,$)}.test(${_})`))),(0,t.not)(S)}function m(_){i.code((0,t._)`delete ${u}[${_}]`)}function T(_){if(y.removeAdditional==="all"||y.removeAdditional&&l===!1){m(_);return}if(l===!1){a.setParams({additionalProperty:_}),a.error(),h||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");y.removeAdditional==="failing"?(k(_,S,!1),i.if((0,t.not)(S),()=>{a.reset(),m(_)})):(k(_,S),h||i.if((0,t.not)(S),()=>i.break()))}}function k(_,S,$){const x={keyword:"additionalProperties",dataProp:_,dataPropType:n.Type.Str};$===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(x,S)}}};return qa.default=s,qa}var La={},rf;function nw(){if(rf)return La;rf=1,Object.defineProperty(La,"__esModule",{value:!0});const e=ua(),t=ir(),r=Ze(),n=tf(),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 f=(0,t.allSchemaProperties)(i);for(const g of f)u.definedProperties.add(g);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),u.props));const p=f.filter(g=>!(0,r.alwaysValidSchema)(u,i[g]));if(p.length===0)return;const h=a.name("valid");for(const g of p)y(g)?w(g):(a.if((0,t.propertyInData)(a,c,g,u.opts.ownProperties)),w(g),u.allErrors||a.else().var(h,!0),a.endIf()),s.it.definedProperties.add(g),s.ok(h);function y(g){return u.opts.useDefaults&&!u.compositeRule&&i[g].default!==void 0}function w(g){s.subschema({keyword:"properties",schemaProp:g,dataProp:g},h)}}};return La.default=o,La}var ja={},nf;function ow(){if(nf)return ja;nf=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=ir(),t=Ne(),r=Ze(),n=Ze(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:f}=u,p=(0,e.allSchemaProperties)(i),h=p.filter(T=>(0,r.alwaysValidSchema)(u,i[T]));if(p.length===0||h.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const y=f.strictSchema&&!f.allowMatchingProperties&&c.properties,w=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:g}=u;b();function b(){for(const T of p)y&&v(T),u.allErrors?m(T):(a.var(w,!0),m(T),a.if(w))}function v(T){for(const k in y)new RegExp(T).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${T} (use allowMatchingProperties)`)}function m(T){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,T)}.test(${k})`,()=>{const _=h.includes(T);_||s.subschema({keyword:"patternProperties",schemaProp:T,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&g!==!0?a.assign((0,t._)`${g}[${k}]`,!0):!_&&!u.allErrors&&a.if((0,t.not)(w),()=>a.break())})})}}};return ja.default=o,ja}var Da={},of;function sw(){if(of)return Da;of=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=Ze(),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 Da.default=t,Da}var Ua={},sf;function aw(){if(sf)return Ua;sf=1,Object.defineProperty(Ua,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ir().validateUnion,error:{message:"must match a schema in anyOf"}};return Ua.default=t,Ua}var za={},af;function iw(){if(af)return za;af=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Ne(),t=Ze(),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),f=s.let("passing",null),p=s.name("_valid");o.setParams({passing:f}),s.block(h),o.result(u,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((y,w)=>{let g;(0,t.alwaysValidSchema)(l,y)?s.var(p,!0):g=o.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},p),w>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(f,(0,e._)`[${f}, ${w}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(f,w),g&&o.mergeEvaluated(g,e.Name)})})}}};return za.default=n,za}var Za={},lf;function lw(){if(lf)return Za;lf=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Ze(),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 Za.default=t,Za}var Fa={},cf;function cw(){if(cf)return Fa;cf=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Ne(),t=Ze(),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 f=a.let("valid",!0),p=a.name("_valid");if(h(),s.reset(),c&&u){const w=a.let("ifClause");s.setParams({ifClause:w}),a.if(p,y("then",w),y("else",w))}else c?a.if(p,y("then")):a.if((0,e.not)(p),y("else"));s.pass(f,()=>s.error(!0));function h(){const w=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(w)}function y(w,g){return()=>{const b=s.subschema({keyword:w},p);a.assign(f,p),s.mergeValidEvaluated(b,f),g?a.assign(g,(0,e._)`${w}`):s.setParams({ifClause:w})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return Fa.default=n,Fa}var Va={},uf;function uw(){if(uf)return Va;uf=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Ze(),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 Va.default=t,Va}var df;function dw(){if(df)return Pa;df=1,Object.defineProperty(Pa,"__esModule",{value:!0});const e=Bp(),t=Q1(),r=Wp(),n=X1(),o=ew(),s=tw(),a=rw(),i=tf(),l=nw(),c=ow(),u=sw(),f=aw(),p=iw(),h=lw(),y=cw(),w=uw();function g(b=!1){const v=[u.default,f.default,p.default,h.default,y.default,w.default,a.default,i.default,s.default,l.default,c.default];return b?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return Pa.default=g,Pa}var Ha={},Ba={},pf;function pw(){if(pf)return Ba;pf=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Ne(),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:f,errSchemaPath:p,schemaEnv:h,self:y}=u;if(!f.validateFormats)return;i?w():g();function w(){const b=s.scopeValue("formats",{ref:y.formats,code:f.code.formats}),v=s.const("fDef",(0,e._)`${b}[${c}]`),m=s.let("fType"),T=s.let("format");s.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>s.assign(m,(0,e._)`${v}.type || "string"`).assign(T,(0,e._)`${v}.validate`),()=>s.assign(m,(0,e._)`"string"`).assign(T,v)),n.fail$data((0,e.or)(k(),_()));function k(){return f.strictSchema===!1?e.nil:(0,e._)`${c} && !${T}`}function _(){const S=h.$async?(0,e._)`(${v}.async ? await ${T}(${a}) : ${T}(${a}))`:(0,e._)`${T}(${a})`,$=(0,e._)`(typeof ${T} == "function" ? ${S} : ${T}.test(${a}))`;return(0,e._)`${T} && ${T} !== true && ${m} === ${o} && !${$}`}}function g(){const b=y.formats[l];if(!b){k();return}if(b===!0)return;const[v,m,T]=_(b);v===o&&n.pass(S());function k(){if(f.strictSchema===!1){y.logger.warn($());return}throw new Error($());function $(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function _($){const x=$ instanceof RegExp?(0,e.regexpCode)($):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(l)}`:void 0,U=s.scopeValue("formats",{key:l,ref:$,code:x});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,e._)`${U}.validate`]:["string",$,U]}function S(){if(typeof b=="object"&&!(b instanceof RegExp)&&b.async){if(!h.$async)throw new Error("async format in sync schema");return(0,e._)`await ${T}(${a})`}return typeof m=="function"?(0,e._)`${T}(${a})`:(0,e._)`${T}.test(${a})`}}}};return Ba.default=r,Ba}var ff;function fw(){if(ff)return Ha;ff=1,Object.defineProperty(Ha,"__esModule",{value:!0});const t=[pw().default];return Ha.default=t,Ha}var Sn={},hf;function hw(){return hf||(hf=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.contentVocabulary=Sn.metadataVocabulary=void 0,Sn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Sn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Sn}var mf;function mw(){if(mf)return ma;mf=1,Object.defineProperty(ma,"__esModule",{value:!0});const e=D1(),t=Y1(),r=dw(),n=fw(),o=hw(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ma.default=s,ma}var Ja={},qo={},gf;function gw(){if(gf)return qo;gf=1,Object.defineProperty(qo,"__esModule",{value:!0}),qo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(qo.DiscrError=e={})),qo}var yf;function yw(){if(yf)return Ja;yf=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Ne(),t=gw(),r=Tl(),n=fa(),o=Ze(),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:f,it:p}=i,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const y=u.propertyName;if(typeof y!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),g=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(y)}`);l.if((0,e._)`typeof ${g} == "string"`,()=>b(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:g,tagName:y})),i.ok(w);function b(){const T=m();l.if(!1);for(const k in T)l.elseIf((0,e._)`${g} === ${k}`),l.assign(w,v(T[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:g,tagName:y}),l.endIf()}function v(T){const k=l.name("valid"),_=i.subschema({keyword:"oneOf",schemaProp:T},k);return i.mergeEvaluated(_,e.Name),k}function m(){var T;const k={},_=$(f);let S=!0;for(let M=0;M<h.length;M++){let O=h[M];if(O?.$ref&&!(0,o.schemaHasRulesButRef)(O,p.self.RULES)){const L=O.$ref;if(O=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,L),O instanceof r.SchemaEnv&&(O=O.schema),O===void 0)throw new n.default(p.opts.uriResolver,p.baseId,L)}const A=(T=O?.properties)===null||T===void 0?void 0:T[y];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${y}"`);S=S&&(_||$(O)),x(A,M)}if(!S)throw new Error(`discriminator: "${y}" must be required`);return k;function $({required:M}){return Array.isArray(M)&&M.includes(y)}function x(M,O){if(M.const)U(M.const,O);else if(M.enum)for(const A of M.enum)U(A,O);else throw new Error(`discriminator: "properties/${y}" must have "const" or "enum"`)}function U(M,O){if(typeof M!="string"||M in k)throw new Error(`discriminator: "${y}" values must be unique strings`);k[M]=O}}}};return Ja.default=a,Ja}const vw={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var vf;function _f(){return vf||(vf=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=q1(),n=mw(),o=yw(),s=vw,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(y=>this.addVocabulary(y)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const y=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(y,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=ua();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ne();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 f=kl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=fa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(oa,oa.exports)),oa.exports}var _w=_f();const wf=kn(_w);var Ue;(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})(Ue||(Ue={}));var xl;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(xl||(xl={}));const le=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),jr=e=>{switch(typeof e){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(e)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":return Array.isArray(e)?le.array:e===null?le.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?le.promise:typeof Map<"u"&&e instanceof Map?le.map:typeof Set<"u"&&e instanceof Set?le.set:typeof Date<"u"&&e instanceof Date?le.date:le.object;default:return le.unknown}},X=Ue.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"]),ww=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Bt 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 Bt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ue.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()}}Bt.create=e=>new Bt(e);const Xn=(e,t)=>{let r;switch(e.code){case X.invalid_type:e.received===le.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ue.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(e.keys,", ")}`;break;case X.invalid_union:r="Invalid input";break;case X.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(e.options)}`;break;case X.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.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}"`:Ue.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,Ue.assertNever(e)}return{message:r}};let bf=Xn;function bw(e){bf=e}function Wa(){return bf}const Ga=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}},kw=[];function se(e,t){const r=Wa(),n=Ga({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Xn?void 0:Xn].filter(o=>!!o)});e.common.issues.push(n)}class xt{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 be;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 xt.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 be;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 be=Object.freeze({status:"aborted"}),eo=e=>({status:"dirty",value:e}),Mt=e=>({status:"valid",value:e}),$l=e=>e.status==="aborted",Rl=e=>e.status==="dirty",In=e=>e.status==="valid",Lo=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 Sr{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 kf=(e,t)=>{if(In(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 Bt(e.common.issues);return this._error=r,this._error}}};function Me(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 Ae=class{get description(){return this._def.description}_getType(t){return jr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new xt,ctx:{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Lo(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:jr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return kf(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return In(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=>In(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:jr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Lo(o)?o:Promise.resolve(o));return kf(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 lr({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 cr.create(this,this._def)}nullable(){return nn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $n.create(this)}promise(){return so.create(this,this._def)}or(t){return Zo.create([this,t],this._def)}and(t){return Fo.create(this,t,this._def)}transform(t){return new lr({...Me(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new Wo({...Me(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new Ol({typeName:B.ZodBranded,type:this,...Me(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new Go({...Me(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 Ko.create(this,t)}readonly(){return Yo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Tw=/^c[^\s-]{8,}$/i,Cw=/^[0-9a-z]+$/,Sw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Iw=/^[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,Ew=/^[a-z0-9_-]{21}$/i,xw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$w=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Pl;const Mw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ow=/^(?:(?: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])$/,Aw=/^(([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]))$/,Nw=/^(([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])$/,qw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Tf="((\\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])))",jw=new RegExp(`^${Tf}$`);function Cf(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 Dw(e){return new RegExp(`^${Cf(e)}$`)}function Sf(e){let t=`${Tf}T${Cf(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 Uw(e,t){return!!((t==="v4"||!t)&&Mw.test(e)||(t==="v6"||!t)&&Aw.test(e))}function zw(e,t){if(!xw.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 Zw(e,t){return!!((t==="v4"||!t)&&Ow.test(e)||(t==="v6"||!t)&&Nw.test(e))}let to=class na extends Ae{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==le.string){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:le.string,received:s.parsedType}),be}const n=new xt;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")Rw.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")Pl||(Pl=new RegExp(Pw,"u")),Pl.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")Iw.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")Ew.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")Tw.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")Cw.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")Sw.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"?Sf(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"?jw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Dw(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"?$w.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"duration",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Uw(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"?zw(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"?Zw(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"?qw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Lw.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64url",code:X.invalid_string,message:s.message}),n.dirty()):Ue.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 na({...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 na({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new na({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new na({...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}};to.create=e=>new to({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...Me(e)});function Fw(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 jo=class Jd extends Ae{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)!==le.number){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:le.number,received:s.parsedType}),be}let n;const o=new xt;for(const s of this._def.checks)s.kind==="int"?Ue.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"?Fw(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()):Ue.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 Jd({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new Jd({...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"&&Ue.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)}};jo.create=e=>new jo({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...Me(e)});class rn extends Ae{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)!==le.bigint)return this._getInvalidInput(t);let n;const o=new xt;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()):Ue.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:le.bigint,received:r.parsedType}),be}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 rn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new rn({...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}}rn.create=e=>new rn({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...Me(e)});let Do=class extends Ae{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==le.boolean){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.boolean,received:n.parsedType}),be}return Mt(t.data)}};Do.create=e=>new Do({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...Me(e)});class En extends Ae{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==le.date){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:le.date,received:s.parsedType}),be}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_date}),be}const n=new xt;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()):Ue.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new En({...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}}En.create=e=>new En({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...Me(e)});class Ka extends Ae{_parse(t){if(this._getType(t)!==le.symbol){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.symbol,received:n.parsedType}),be}return Mt(t.data)}}Ka.create=e=>new Ka({typeName:B.ZodSymbol,...Me(e)});class Uo extends Ae{_parse(t){if(this._getType(t)!==le.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.undefined,received:n.parsedType}),be}return Mt(t.data)}}Uo.create=e=>new Uo({typeName:B.ZodUndefined,...Me(e)});let zo=class extends Ae{_parse(t){if(this._getType(t)!==le.null){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.null,received:n.parsedType}),be}return Mt(t.data)}};zo.create=e=>new zo({typeName:B.ZodNull,...Me(e)});let ro=class extends Ae{constructor(){super(...arguments),this._any=!0}_parse(t){return Mt(t.data)}};ro.create=e=>new ro({typeName:B.ZodAny,...Me(e)});let xn=class extends Ae{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Mt(t.data)}};xn.create=e=>new xn({typeName:B.ZodUnknown,...Me(e)});let Dr=class extends Ae{_parse(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:le.never,received:r.parsedType}),be}};Dr.create=e=>new Dr({typeName:B.ZodNever,...Me(e)});class Ya extends Ae{_parse(t){if(this._getType(t)!==le.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.void,received:n.parsedType}),be}return Mt(t.data)}}Ya.create=e=>new Ya({typeName:B.ZodVoid,...Me(e)});let $n=class hl extends Ae{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==le.array)return se(r,{code:X.invalid_type,expected:le.array,received:r.parsedType}),be;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 Sr(r,a,r.path,i)))).then(a=>xt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Sr(r,a,r.path,i)));return xt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new hl({...this._def,minLength:{value:t,message:he.toString(r)}})}max(t,r){return new hl({...this._def,maxLength:{value:t,message:he.toString(r)}})}length(t,r){return new hl({...this._def,exactLength:{value:t,message:he.toString(r)}})}nonempty(t){return this.min(1,t)}};$n.create=(e,t)=>new $n({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...Me(t)});function no(e){if(e instanceof Qt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=cr.create(no(n))}return new Qt({...e._def,shape:()=>t})}else return e instanceof $n?new $n({...e._def,type:no(e.element)}):e instanceof cr?cr.create(no(e.unwrap())):e instanceof nn?nn.create(no(e.unwrap())):e instanceof Ir?Ir.create(e.items.map(t=>no(t))):e}let Qt=class Cr extends Ae{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=Ue.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==le.object){const c=this._getOrReturnCtx(t);return se(c,{code:X.invalid_type,expected:le.object,received:c.parsedType}),be}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Dr&&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],f=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Sr(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Dr){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 f=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Sr(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,p=await u.value;c.push({key:f,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>xt.mergeObjectSync(n,c)):xt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return he.errToObj,new Cr({...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 Cr({...this._def,unknownKeys:"strip"})}passthrough(){return new Cr({...this._def,unknownKeys:"passthrough"})}extend(t){return new Cr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Cr({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 Cr({...this._def,catchall:t})}pick(t){const r={};for(const n of Ue.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Cr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ue.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Cr({...this._def,shape:()=>r})}deepPartial(){return no(this)}partial(t){const r={};for(const n of Ue.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Cr({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ue.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof cr;)s=s._def.innerType;r[n]=s}return new Cr({...this._def,shape:()=>r})}keyof(){return xf(Ue.objectKeys(this.shape))}};Qt.create=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strip",catchall:Dr.create(),typeName:B.ZodObject,...Me(t)}),Qt.strictCreate=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strict",catchall:Dr.create(),typeName:B.ZodObject,...Me(t)}),Qt.lazycreate=(e,t)=>new Qt({shape:e,unknownKeys:"strip",catchall:Dr.create(),typeName:B.ZodObject,...Me(t)});let Zo=class extends Ae{_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 Bt(i.ctx.common.issues));return se(r,{code:X.invalid_union,unionErrors:a}),be}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 Bt(l));return se(r,{code:X.invalid_union,unionErrors:i}),be}}get options(){return this._def.options}};Zo.create=(e,t)=>new Zo({options:e,typeName:B.ZodUnion,...Me(t)});const Ur=e=>e instanceof Vo?Ur(e.schema):e instanceof lr?Ur(e.innerType()):e instanceof Ho?[e.value]:e instanceof Bo?e.options:e instanceof Jo?Ue.objectValues(e.enum):e instanceof Wo?Ur(e._def.innerType):e instanceof Uo?[void 0]:e instanceof zo?[null]:e instanceof cr?[void 0,...Ur(e.unwrap())]:e instanceof nn?[null,...Ur(e.unwrap())]:e instanceof Ol||e instanceof Yo?Ur(e.unwrap()):e instanceof Go?Ur(e._def.innerType):[];let If=class b1 extends Ae{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==le.object)return se(r,{code:X.invalid_type,expected:le.object,received:r.parsedType}),be;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]}),be)}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=Ur(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 b1({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...Me(n)})}};function Ml(e,t){const r=jr(e),n=jr(t);if(e===t)return{valid:!0,data:e};if(r===le.object&&n===le.object){const o=Ue.objectKeys(t),s=Ue.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Ml(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===le.array&&n===le.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=Ml(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===le.date&&n===le.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let Fo=class extends Ae{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if($l(s)||$l(a))return be;const i=Ml(s.value,a.value);return i.valid?((Rl(s)||Rl(a))&&r.dirty(),{status:r.value,value:i.data}):(se(n,{code:X.invalid_intersection_types}),be)};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}))}};Fo.create=(e,t,r)=>new Fo({left:e,right:t,typeName:B.ZodIntersection,...Me(r)});class Ir extends Ae{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==le.array)return se(n,{code:X.invalid_type,expected:le.array,received:n.parsedType}),be;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"}),be;!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 Sr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>xt.mergeArray(r,a)):xt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Ir({...this._def,rest:t})}}Ir.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ir({items:e,typeName:B.ZodTuple,rest:null,...Me(t)})};let Ef=class Wd extends Ae{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!==le.object)return se(n,{code:X.invalid_type,expected:le.object,received:n.parsedType}),be;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Sr(n,i,n.path,i)),value:a._parse(new Sr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?xt.mergeObjectAsync(r,o):xt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ae?new Wd({keyType:t,valueType:r,typeName:B.ZodRecord,...Me(n)}):new Wd({keyType:to.create(),valueType:t,typeName:B.ZodRecord,...Me(r)})}};class Qa extends Ae{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!==le.map)return se(n,{code:X.invalid_type,expected:le.map,received:n.parsedType}),be;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Sr(n,i,n.path,[c,"key"])),value:s._parse(new Sr(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 be;(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 be;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}Qa.create=(e,t,r)=>new Qa({valueType:t,keyType:e,typeName:B.ZodMap,...Me(r)});class Rn extends Ae{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==le.set)return se(n,{code:X.invalid_type,expected:le.set,received:n.parsedType}),be;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 be;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 Sr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Rn({...this._def,minSize:{value:t,message:he.toString(r)}})}max(t,r){return new Rn({...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)}}Rn.create=(e,t)=>new Rn({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...Me(t)});class oo extends Ae{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==le.function)return se(r,{code:X.invalid_type,expected:le.function,received:r.parsedType}),be;function n(i,l){return Ga({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wa(),Xn].filter(c=>!!c),issueData:{code:X.invalid_arguments,argumentsError:l}})}function o(i,l){return Ga({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wa(),Xn].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 so){const i=this;return Mt(async function(...l){const c=new Bt([]),u=await i._def.args.parseAsync(l,s).catch(h=>{throw c.addIssue(n(l,h)),c}),f=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(f,s).catch(h=>{throw c.addIssue(o(f,h)),c})})}else{const i=this;return Mt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new Bt([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),f=i._def.returns.safeParse(u,s);if(!f.success)throw new Bt([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new oo({...this._def,args:Ir.create(t).rest(xn.create())})}returns(t){return new oo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new oo({args:t||Ir.create([]).rest(xn.create()),returns:r||xn.create(),typeName:B.ZodFunction,...Me(n)})}}let Vo=class extends Ae{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})}};Vo.create=(e,t)=>new Vo({getter:e,typeName:B.ZodLazy,...Me(t)});let Ho=class extends Ae{_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}),be}return{status:"valid",value:t.data}}get value(){return this._def.value}};Ho.create=(e,t)=>new Ho({value:e,typeName:B.ZodLiteral,...Me(t)});function xf(e,t){return new Bo({values:e,typeName:B.ZodEnum,...Me(t)})}let Bo=class Gd extends Ae{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return se(r,{expected:Ue.joinValues(n),received:r.parsedType,code:X.invalid_type}),be}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}),be}return Mt(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 Gd.create(t,{...this._def,...r})}exclude(t,r=this._def){return Gd.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Bo.create=xf;class Jo extends Ae{_parse(t){const r=Ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==le.string&&n.parsedType!==le.number){const o=Ue.objectValues(r);return se(n,{expected:Ue.joinValues(o),received:n.parsedType,code:X.invalid_type}),be}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ue.objectValues(r);return se(n,{received:n.data,code:X.invalid_enum_value,options:o}),be}return Mt(t.data)}get enum(){return this._def.values}}Jo.create=(e,t)=>new Jo({values:e,typeName:B.ZodNativeEnum,...Me(t)});class so extends Ae{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==le.promise&&r.common.async===!1)return se(r,{code:X.invalid_type,expected:le.promise,received:r.parsedType}),be;const n=r.parsedType===le.promise?r.data:Promise.resolve(r.data);return Mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}so.create=(e,t)=>new so({type:e,typeName:B.ZodPromise,...Me(t)});class lr extends Ae{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 be;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?be:l.status==="dirty"||r.value==="dirty"?eo(l.value):l});{if(r.value==="aborted")return be;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?be:i.status==="dirty"||r.value==="dirty"?eo(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"?be:(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"?be:(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(!In(a))return be;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=>In(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):be);Ue.assertNever(o)}}lr.create=(e,t,r)=>new lr({schema:e,typeName:B.ZodEffects,effect:t,...Me(r)}),lr.createWithPreprocess=(e,t,r)=>new lr({schema:t,effect:{type:"preprocess",transform:e},typeName:B.ZodEffects,...Me(r)});let cr=class extends Ae{_parse(t){return this._getType(t)===le.undefined?Mt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};cr.create=(e,t)=>new cr({innerType:e,typeName:B.ZodOptional,...Me(t)});let nn=class extends Ae{_parse(t){return this._getType(t)===le.null?Mt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};nn.create=(e,t)=>new nn({innerType:e,typeName:B.ZodNullable,...Me(t)});let Wo=class extends Ae{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===le.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Wo.create=(e,t)=>new Wo({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Me(t)});let Go=class extends Ae{_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 Lo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Bt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Go.create=(e,t)=>new Go({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Me(t)});class Xa extends Ae{_parse(t){if(this._getType(t)!==le.nan){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:le.nan,received:n.parsedType}),be}return{status:"valid",value:t.data}}}Xa.create=e=>new Xa({typeName:B.ZodNaN,...Me(e)});const Vw=Symbol("zod_brand");class Ol extends Ae{_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 Ko extends Ae{_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"?be:s.status==="dirty"?(r.dirty(),eo(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"?be: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 Ko({in:t,out:r,typeName:B.ZodPipeline})}}let Yo=class extends Ae{_parse(t){const r=this._def.innerType._parse(t),n=o=>(In(o)&&(o.value=Object.freeze(o.value)),o);return Lo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Yo.create=(e,t)=>new Yo({innerType:e,typeName:B.ZodReadonly,...Me(t)});function $f(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Rf(e,t={},r){return e?ro.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=$f(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=$f(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):ro.create()}const Hw={object:Qt.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 Bw=(e,t={message:`Input not instance of ${e.name}`})=>Rf(r=>r instanceof e,t),Ve=to.create,Xt=jo.create,Jw=Xa.create,Ww=rn.create,Pf=Do.create,Gw=En.create,Kw=Ka.create,Yw=Uo.create,Qw=zo.create,Xw=ro.create,eb=xn.create,tb=Dr.create,rb=Ya.create,zr=$n.create,jt=Qt.create,nb=Qt.strictCreate,ei=Zo.create,ob=If.create,sb=Fo.create,ab=Ir.create,ib=Ef.create,lb=Qa.create,cb=Rn.create,ub=oo.create,db=Vo.create,pb=Ho.create,Qo=Bo.create,fb=Jo.create,hb=so.create,Mf=lr.create,mb=cr.create,gb=nn.create,yb=lr.createWithPreprocess,vb=Ko.create,_b=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Vw,DIRTY:eo,EMPTY_PATH:kw,INVALID:be,NEVER:be,OK:Mt,ParseStatus:xt,Schema:Ae,ZodAny:ro,ZodArray:$n,ZodBigInt:rn,ZodBoolean:Do,ZodBranded:Ol,ZodCatch:Go,ZodDate:En,ZodDefault:Wo,ZodDiscriminatedUnion:If,ZodEffects:lr,ZodEnum:Bo,ZodError:Bt,get ZodFirstPartyTypeKind(){return B},ZodFunction:oo,ZodIntersection:Fo,ZodIssueCode:X,ZodLazy:Vo,ZodLiteral:Ho,ZodMap:Qa,ZodNaN:Xa,ZodNativeEnum:Jo,ZodNever:Dr,ZodNull:zo,ZodNullable:nn,ZodNumber:jo,ZodObject:Qt,ZodOptional:cr,ZodParsedType:le,ZodPipeline:Ko,ZodPromise:so,ZodReadonly:Yo,ZodRecord:Ef,ZodSchema:Ae,ZodSet:Rn,ZodString:to,ZodSymbol:Ka,ZodTransformer:lr,ZodTuple:Ir,ZodType:Ae,ZodUndefined:Uo,ZodUnion:Zo,ZodUnknown:xn,ZodVoid:Ya,addIssueToContext:se,any:Xw,array:zr,bigint:Ww,boolean:Pf,coerce:{string:(e=>to.create({...e,coerce:!0})),number:(e=>jo.create({...e,coerce:!0})),boolean:(e=>Do.create({...e,coerce:!0})),bigint:(e=>rn.create({...e,coerce:!0})),date:(e=>En.create({...e,coerce:!0}))},custom:Rf,date:Gw,datetimeRegex:Sf,defaultErrorMap:Xn,discriminatedUnion:ob,effect:Mf,enum:Qo,function:ub,getErrorMap:Wa,getParsedType:jr,instanceof:Bw,intersection:sb,isAborted:$l,isAsync:Lo,isDirty:Rl,isValid:In,late:Hw,lazy:db,literal:pb,makeIssue:Ga,map:lb,nan:Jw,nativeEnum:fb,never:tb,null:Qw,nullable:gb,number:Xt,object:jt,get objectUtil(){return xl},oboolean:()=>Pf().optional(),onumber:()=>Xt().optional(),optional:mb,ostring:()=>Ve().optional(),pipeline:vb,preprocess:yb,promise:hb,quotelessJson:ww,record:ib,set:cb,setErrorMap:bw,strictObject:nb,string:Ve,symbol:Kw,transformer:Mf,tuple:ab,undefined:Yw,union:ei,unknown:eb,get util(){return Ue},void:rb},Symbol.toStringTag,{value:"Module"})),Of=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 Xo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Af={};function on(e){return Af}function Nf(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 wb(e,t){return typeof t=="bigint"?t.toString():t}function Al(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Nl(e){return e==null}function ql(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function bb(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 He(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 es(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ts(e){return JSON.stringify(e)}const qf=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const kb=Al(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ri(e){if(ti(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(ti(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Tb=new Set(["string","number","symbol"]);function rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sn(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 Cb(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Sb={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 Ib(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 sn(e,{...e._zod.def,shape:r,checks:[]})}function Eb(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 sn(e,{...e._zod.def,shape:r,checks:[]})}function xb(e,t){if(!ri(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 es(this,"shape",n),n},checks:[]};return sn(e,r)}function $b(e,t){return sn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return es(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Rb(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 sn(t,{...t._zod.def,shape:o,checks:[]})}function Pb(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 sn(t,{...t._zod.def,shape:o,checks:[]})}function ns(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Pn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function ni(e){return typeof e=="string"?e:e?.message}function an(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=ni(e.inst?._zod.def?.error?.(e))??ni(t?.error?.(e))??ni(r.customError?.(e))??ni(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Ll(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function os(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Lf=(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,wb,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},jf=W("$ZodError",Lf),oi=W("$ZodError",Lf,{Parent:Error});function Mb(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 Ob(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 Df=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 Xo;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>an(l,s,on())));throw qf(i,o?.callee),i}return a.value},Ab=Df(oi),Uf=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=>an(l,s,on())));throw qf(i,o?.callee),i}return a.value},Nb=Uf(oi),zf=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 Xo;return s.issues.length?{success:!1,error:new(e??jf)(s.issues.map(a=>an(a,o,on())))}:{success:!0,data:s.value}},jl=zf(oi),Zf=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=>an(a,o,on())))}:{success:!0,data:s.value}},Dl=Zf(oi),qb=/^[cC][^\s-]{8,}$/,Lb=/^[0-9a-z]+$/,jb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Db=/^[0-9a-vA-V]{20}$/,Ub=/^[A-Za-z0-9]{27}$/,zb=/^[a-zA-Z0-9_-]{21}$/,Zb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Fb=/^([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})$/,Ff=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)$/,Vb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bb(){return new RegExp(Hb,"u")}const Jb=/^(?:(?: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])$/,Wb=/^(([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})$/,Gb=/^((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])$/,Kb=/^(([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])$/,Yb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vf=/^[A-Za-z0-9_-]*$/,Qb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Xb=/^\+(?:[0-9]){6,14}[0-9]$/,Hf="(?:(?:\\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])))",e3=new RegExp(`^${Hf}$`);function Bf(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 t3(e){return new RegExp(`^${Bf(e)}$`)}function r3(e){const t=Bf({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(`^${Hf}T(?:${n})$`)}const n3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},o3=/^\d+$/,s3=/^-?\d+(?:\.\d+)?/i,a3=/true|false/i,i3=/null/i,l3=/^[^A-Z]*$/,c3=/^[^a-z]*$/,Dt=W("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Jf={number:"number",bigint:"bigint",object:"date"},Wf=W("$ZodCheckLessThan",(e,t)=>{Dt.init(e,t);const r=Jf[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})}}),Gf=W("$ZodCheckGreaterThan",(e,t)=>{Dt.init(e,t);const r=Jf[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})}}),u3=W("$ZodCheckMultipleOf",(e,t)=>{Dt.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):bb(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})}}),d3=W("$ZodCheckNumberFormat",(e,t)=>{Dt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Sb[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=o3)}),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})}}),p3=W("$ZodCheckMaxLength",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Nl(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=Ll(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),f3=W("$ZodCheckMinLength",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Nl(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=Ll(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),h3=W("$ZodCheckLengthEquals",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Nl(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=Ll(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})}}),si=W("$ZodCheckStringFormat",(e,t)=>{var r,n;Dt.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)=>{si.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})}}),g3=W("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=l3),si.init(e,t)}),y3=W("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=c3),si.init(e,t)}),v3=W("$ZodCheckIncludes",(e,t)=>{Dt.init(e,t);const r=rs(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})}}),_3=W("$ZodCheckStartsWith",(e,t)=>{Dt.init(e,t);const r=new RegExp(`^${rs(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})}}),w3=W("$ZodCheckEndsWith",(e,t)=>{Dt.init(e,t);const r=new RegExp(`.*${rs(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})}}),b3=W("$ZodCheckOverwrite",(e,t)=>{Dt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class k3{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(`
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})(Hl)),Hl}var Wa={},yf;function bw(){if(yf)return Wa;yf=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Ne(),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 Wa.default=n,Wa}var Ga={},vf;function _f(){if(vf)return Ga;vf=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=mr(),t=Ne(),r=pn(),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,b=>{!_.length&&!y.length?C(b):i.if(v(b),()=>C(b))})}function v(b){let S;if(_.length>8){const x=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,x,b)}else _.length?S=(0,t.or)(..._.map(x=>(0,t._)`${b} === ${x}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(x=>(0,t._)`${(0,e.usePattern)(a,x)}.test(${b})`))),(0,t.not)(S)}function m(b){i.code((0,t._)`delete ${u}[${b}]`)}function C(b){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){m(b);return}if(l===!1){a.setParams({additionalProperty:b}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");g.removeAdditional==="failing"?(k(b,S,!1),i.if((0,t.not)(S),()=>{a.reset(),m(b)})):(k(b,S),f||i.if((0,t.not)(S),()=>i.break()))}}function k(b,S,x){const I={keyword:"additionalProperties",dataProp:b,dataPropType:n.Type.Str};x===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,S)}}};return Ga.default=s,Ga}var Ka={},wf;function kw(){if(wf)return Ka;wf=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Ta(),t=mr(),r=Ue(),n=_f(),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 Ka.default=o,Ka}var Ya={},bf;function Tw(){if(bf)return Ya;bf=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=mr(),t=Ne(),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(C=>(0,r.alwaysValidSchema)(u,i[C]));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 C of p)g&&v(C),u.allErrors?m(C):(a.var(_,!0),m(C),a.if(_))}function v(C){for(const k in g)new RegExp(C).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${C} (use allowMatchingProperties)`)}function m(C){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,C)}.test(${k})`,()=>{const b=f.includes(C);b||s.subschema({keyword:"patternProperties",schemaProp:C,dataProp:k,dataPropType:n.Type.Str},_),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${k}]`,!0):!b&&!u.allErrors&&a.if((0,t.not)(_),()=>a.break())})})}}};return Ya.default=o,Ya}var Qa={},kf;function Cw(){if(kf)return Qa;kf=1,Object.defineProperty(Qa,"__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 Qa.default=t,Qa}var Xa={},Tf;function Sw(){if(Tf)return Xa;Tf=1,Object.defineProperty(Xa,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mr().validateUnion,error:{message:"must match a schema in anyOf"}};return Xa.default=t,Xa}var ei={},Cf;function Iw(){if(Cf)return ei;Cf=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ne(),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 ei.default=n,ei}var ti={},Sf;function xw(){if(Sf)return ti;Sf=1,Object.defineProperty(ti,"__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 ti.default=t,ti}var ri={},If;function Ew(){if(If)return ri;If=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Ne(),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 ri.default=n,ri}var ni={},xf;function $w(){if(xf)return ni;xf=1,Object.defineProperty(ni,"__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 ni.default=t,ni}var Ef;function Rw(){if(Ef)return Va;Ef=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=uf(),t=yw(),r=pf(),n=vw(),o=_w(),s=ww(),a=bw(),i=_f(),l=kw(),c=Tw(),u=Cw(),h=Sw(),p=Iw(),f=xw(),g=Ew(),_=$w();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 Va.default=y,Va}var oi={},si={},$f;function Pw(){if($f)return si;$f=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Ne(),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"),C=s.let("format");s.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>s.assign(m,(0,e._)`${v}.type || "string"`).assign(C,(0,e._)`${v}.validate`),()=>s.assign(m,(0,e._)`"string"`).assign(C,v)),n.fail$data((0,e.or)(k(),b()));function k(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${C}`}function b(){const S=f.$async?(0,e._)`(${v}.async ? await ${C}(${a}) : ${C}(${a}))`:(0,e._)`${C}(${a})`,x=(0,e._)`(typeof ${C} == "function" ? ${S} : ${C}.test(${a}))`;return(0,e._)`${C} && ${C} !== true && ${m} === ${o} && !${x}`}}function y(){const w=g.formats[l];if(!w){k();return}if(w===!0)return;const[v,m,C]=b(w);v===o&&n.pass(S());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 b(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 S(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${C}(${a})`}return typeof m=="function"?(0,e._)`${C}(${a})`:(0,e._)`${C}.test(${a})`}}}};return si.default=r,si}var Rf;function Mw(){if(Rf)return oi;Rf=1,Object.defineProperty(oi,"__esModule",{value:!0});const t=[Pw().default];return oi.default=t,oi}var An={},Pf;function Ow(){return Pf||(Pf=1,Object.defineProperty(An,"__esModule",{value:!0}),An.contentVocabulary=An.metadataVocabulary=void 0,An.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],An.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),An}var Mf;function Nw(){if(Mf)return Ea;Mf=1,Object.defineProperty(Ea,"__esModule",{value:!0});const e=ow(),t=gw(),r=Rw(),n=Mw(),o=Ow(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Ea.default=s,Ea}var ai={},Bo={},Of;function Aw(){if(Of)return Bo;Of=1,Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Bo.DiscrError=e={})),Bo}var Nf;function qw(){if(Nf)return ai;Nf=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=Ne(),t=Aw(),r=zl(),n=Ia(),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 C=m();l.if(!1);for(const k in C)l.elseIf((0,e._)`${y} === ${k}`),l.assign(_,v(C[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function v(C){const k=l.name("valid"),b=i.subschema({keyword:"oneOf",schemaProp:C},k);return i.mergeEvaluated(b,e.Name),k}function m(){var C;const k={},b=x(h);let S=!0;for(let $=0;$<f.length;$++){let N=f[$];if(N?.$ref&&!(0,o.schemaHasRulesButRef)(N,p.self.RULES)){const U=N.$ref;if(N=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,U),N instanceof r.SchemaEnv&&(N=N.schema),N===void 0)throw new n.default(p.opts.uriResolver,p.baseId,U)}const A=(C=N?.properties)===null||C===void 0?void 0:C[g];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);S=S&&(b||x(N)),I(A,$)}if(!S)throw new Error(`discriminator: "${g}" must be required`);return k;function x({required:$}){return Array.isArray($)&&$.includes(g)}function I($,N){if($.const)L($.const,N);else if($.enum)for(const A of $.enum)L(A,N);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function L($,N){if(typeof $!="string"||$ in k)throw new Error(`discriminator: "${g}" values must be unique strings`);k[$]=N}}}};return ai.default=a,ai}const Lw={$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 Af;function qf(){return Af||(Af=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=tw(),n=Nw(),o=qw(),s=Lw,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=Ta();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ne();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=Ul();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=Ia();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(ya,ya.exports)),ya.exports}var jw=qf();const Lf=Mn(jw);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 Bl;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Bl||(Bl={}));const ce=De.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wr=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"]),Dw=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 io=(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 jf=io;function Uw(e){jf=e}function ii(){return jf}const li=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}},zw=[];function se(e,t){const r=ii(),n=li({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===io?void 0:io].filter(o=>!!o)});e.common.issues.push(n)}class Nt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(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 Nt.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"}),lo=e=>({status:"dirty",value:e}),Dt=e=>({status:"valid",value:e}),Jl=e=>e.status==="aborted",Wl=e=>e.status==="dirty",qn=e=>e.status==="valid",Jo=e=>typeof Promise<"u"&&e instanceof Promise;var fe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(fe||(fe={}));class Ar{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 Df=(e,t)=>{if(qn(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 Wr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Nt,ctx:{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Jo(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:Wr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Df(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return qn(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=>qn(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:Wr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Jo(o)?o:Promise.resolve(o));return Df(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 gr({schema:this,typeName:J.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 yr.create(this,this._def)}nullable(){return mn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dn.create(this)}promise(){return ho.create(this,this._def)}or(t){return Qo.create([this,t],this._def)}and(t){return Xo.create(this,t,this._def)}transform(t){return new gr({...$e(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new os({...$e(this._def),innerType:this,defaultValue:r,typeName:J.ZodDefault})}brand(){return new Yl({typeName:J.ZodBranded,type:this,...$e(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ss({...$e(this._def),innerType:this,catchValue:r,typeName:J.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return as.create(this,t)}readonly(){return is.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Zw=/^c[^\s-]{8,}$/i,Fw=/^[0-9a-z]+$/,Vw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Hw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Bw=/^[a-z0-9_-]{21}$/i,Jw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ww=/^[-+]?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)?)??$/,Gw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Gl;const Yw=/^(?:(?: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])$/,Qw=/^(?:(?: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])$/,Xw=/^(([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]))$/,eb=/^(([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])$/,tb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Uf="((\\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])))",nb=new RegExp(`^${Uf}$`);function zf(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 ob(e){return new RegExp(`^${zf(e)}$`)}function Zf(e){let t=`${Uf}T${zf(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 sb(e,t){return!!((t==="v4"||!t)&&Yw.test(e)||(t==="v6"||!t)&&Xw.test(e))}function ab(e,t){if(!Jw.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 ib(e,t){return!!((t==="v4"||!t)&&Qw.test(e)||(t==="v6"||!t)&&eb.test(e))}let co=class ga 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 Nt;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")Gw.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")Gl||(Gl=new RegExp(Kw,"u")),Gl.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")Hw.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")Bw.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")Zw.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")Fw.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")Vw.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"?nb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?ob(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"?Ww.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"duration",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?sb(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"?ab(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"?ib(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"?tb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?rb.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,...fe.errToObj(n)})}_addCheck(t){return new ga({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...fe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...fe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...fe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...fe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...fe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...fe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...fe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...fe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...fe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...fe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...fe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...fe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...fe.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,...fe.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,...fe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...fe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...fe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...fe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...fe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...fe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...fe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...fe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...fe.errToObj(r)})}nonempty(t){return this.min(1,fe.errToObj(t))}trim(){return new ga({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ga({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ga({...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}};co.create=e=>new co({checks:[],typeName:J.ZodString,coerce:e?.coerce??!1,...$e(e)});function lb(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 Wo=class up 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 Nt;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"?lb(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,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new up({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new up({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:fe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:fe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:fe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:fe.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)}};Wo.create=e=>new Wo({checks:[],typeName:J.ZodNumber,coerce:e?.coerce||!1,...$e(e)});class hn 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 Nt;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,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new hn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new hn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.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}}hn.create=e=>new hn({checks:[],typeName:J.ZodBigInt,coerce:e?.coerce??!1,...$e(e)});let Go=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 Dt(t.data)}};Go.create=e=>new Go({typeName:J.ZodBoolean,coerce:e?.coerce||!1,...$e(e)});class Ln 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 Nt;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 Ln({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:fe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:fe.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}}Ln.create=e=>new Ln({checks:[],coerce:e?.coerce||!1,typeName:J.ZodDate,...$e(e)});class ci 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 Dt(t.data)}}ci.create=e=>new ci({typeName:J.ZodSymbol,...$e(e)});class Ko 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 Dt(t.data)}}Ko.create=e=>new Ko({typeName:J.ZodUndefined,...$e(e)});let Yo=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 Dt(t.data)}};Yo.create=e=>new Yo({typeName:J.ZodNull,...$e(e)});let uo=class extends Pe{constructor(){super(...arguments),this._any=!0}_parse(t){return Dt(t.data)}};uo.create=e=>new uo({typeName:J.ZodAny,...$e(e)});let jn=class extends Pe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Dt(t.data)}};jn.create=e=>new jn({typeName:J.ZodUnknown,...$e(e)});let Gr=class extends Pe{_parse(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:ce.never,received:r.parsedType}),ke}};Gr.create=e=>new Gr({typeName:J.ZodNever,...$e(e)});class ui 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 Dt(t.data)}}ui.create=e=>new ui({typeName:J.ZodVoid,...$e(e)});let Dn=class Ml 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 Ar(r,a,r.path,i)))).then(a=>Nt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Ar(r,a,r.path,i)));return Nt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Ml({...this._def,minLength:{value:t,message:fe.toString(r)}})}max(t,r){return new Ml({...this._def,maxLength:{value:t,message:fe.toString(r)}})}length(t,r){return new Ml({...this._def,exactLength:{value:t,message:fe.toString(r)}})}nonempty(t){return this.min(1,t)}};Dn.create=(e,t)=>new Dn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...$e(t)});function po(e){if(e instanceof or){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=yr.create(po(n))}return new or({...e._def,shape:()=>t})}else return e instanceof Dn?new Dn({...e._def,type:po(e.element)}):e instanceof yr?yr.create(po(e.unwrap())):e instanceof mn?mn.create(po(e.unwrap())):e instanceof qr?qr.create(e.items.map(t=>po(t))):e}let or=class Nr 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 Gr&&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 Ar(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Gr){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 Ar(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=>Nt.mergeObjectSync(n,c)):Nt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return fe.errToObj,new Nr({...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:fe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Nr({...this._def,unknownKeys:"strip"})}passthrough(){return new Nr({...this._def,unknownKeys:"passthrough"})}extend(t){return new Nr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Nr({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:J.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Nr({...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 Nr({...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 Nr({...this._def,shape:()=>r})}deepPartial(){return po(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 Nr({...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 yr;)s=s._def.innerType;r[n]=s}return new Nr({...this._def,shape:()=>r})}keyof(){return Hf(De.objectKeys(this.shape))}};or.create=(e,t)=>new or({shape:()=>e,unknownKeys:"strip",catchall:Gr.create(),typeName:J.ZodObject,...$e(t)}),or.strictCreate=(e,t)=>new or({shape:()=>e,unknownKeys:"strict",catchall:Gr.create(),typeName:J.ZodObject,...$e(t)}),or.lazycreate=(e,t)=>new or({shape:e,unknownKeys:"strip",catchall:Gr.create(),typeName:J.ZodObject,...$e(t)});let Qo=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}};Qo.create=(e,t)=>new Qo({options:e,typeName:J.ZodUnion,...$e(t)});const Kr=e=>e instanceof es?Kr(e.schema):e instanceof gr?Kr(e.innerType()):e instanceof ts?[e.value]:e instanceof rs?e.options:e instanceof ns?De.objectValues(e.enum):e instanceof os?Kr(e._def.innerType):e instanceof Ko?[void 0]:e instanceof Yo?[null]:e instanceof yr?[void 0,...Kr(e.unwrap())]:e instanceof mn?[null,...Kr(e.unwrap())]:e instanceof Yl||e instanceof is?Kr(e.unwrap()):e instanceof ss?Kr(e._def.innerType):[];let Ff=class U1 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=Kr(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 U1({typeName:J.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...$e(n)})}};function Kl(e,t){const r=Wr(e),n=Wr(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=Kl(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=Kl(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 Xo=class extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Jl(s)||Jl(a))return ke;const i=Kl(s.value,a.value);return i.valid?((Wl(s)||Wl(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}))}};Xo.create=(e,t,r)=>new Xo({left:e,right:t,typeName:J.ZodIntersection,...$e(r)});class qr 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 Ar(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Nt.mergeArray(r,a)):Nt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new qr({...this._def,rest:t})}}qr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qr({items:e,typeName:J.ZodTuple,rest:null,...$e(t)})};let Vf=class dp 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 Ar(n,i,n.path,i)),value:a._parse(new Ar(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?Nt.mergeObjectAsync(r,o):Nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Pe?new dp({keyType:t,valueType:r,typeName:J.ZodRecord,...$e(n)}):new dp({keyType:co.create(),valueType:t,typeName:J.ZodRecord,...$e(r)})}};class di 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 Ar(n,i,n.path,[c,"key"])),value:s._parse(new Ar(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}}}}di.create=(e,t,r)=>new di({valueType:t,keyType:e,typeName:J.ZodMap,...$e(r)});class Un 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 Ar(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Un({...this._def,minSize:{value:t,message:fe.toString(r)}})}max(t,r){return new Un({...this._def,maxSize:{value:t,message:fe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Un.create=(e,t)=>new Un({valueType:e,minSize:null,maxSize:null,typeName:J.ZodSet,...$e(t)});class fo 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 li({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ii(),io].filter(c=>!!c),issueData:{code:X.invalid_arguments,argumentsError:l}})}function o(i,l){return li({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ii(),io].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 ho){const i=this;return Dt(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 Dt(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 fo({...this._def,args:qr.create(t).rest(jn.create())})}returns(t){return new fo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new fo({args:t||qr.create([]).rest(jn.create()),returns:r||jn.create(),typeName:J.ZodFunction,...$e(n)})}}let es=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})}};es.create=(e,t)=>new es({getter:e,typeName:J.ZodLazy,...$e(t)});let ts=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}};ts.create=(e,t)=>new ts({value:e,typeName:J.ZodLiteral,...$e(t)});function Hf(e,t){return new rs({values:e,typeName:J.ZodEnum,...$e(t)})}let rs=class pp 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 Dt(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 pp.create(t,{...this._def,...r})}exclude(t,r=this._def){return pp.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};rs.create=Hf;class ns 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 Dt(t.data)}get enum(){return this._def.values}}ns.create=(e,t)=>new ns({values:e,typeName:J.ZodNativeEnum,...$e(t)});class ho 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 Dt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ho.create=(e,t)=>new ho({type:e,typeName:J.ZodPromise,...$e(t)});class gr extends Pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.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"?lo(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"?lo(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(!qn(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=>qn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):ke);De.assertNever(o)}}gr.create=(e,t,r)=>new gr({schema:e,typeName:J.ZodEffects,effect:t,...$e(r)}),gr.createWithPreprocess=(e,t,r)=>new gr({schema:t,effect:{type:"preprocess",transform:e},typeName:J.ZodEffects,...$e(r)});let yr=class extends Pe{_parse(t){return this._getType(t)===ce.undefined?Dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:J.ZodOptional,...$e(t)});let mn=class extends Pe{_parse(t){return this._getType(t)===ce.null?Dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};mn.create=(e,t)=>new mn({innerType:e,typeName:J.ZodNullable,...$e(t)});let os=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}};os.create=(e,t)=>new os({innerType:e,typeName:J.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$e(t)});let ss=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 Jo(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}};ss.create=(e,t)=>new ss({innerType:e,typeName:J.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$e(t)});class pi 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}}}pi.create=e=>new pi({typeName:J.ZodNaN,...$e(e)});const cb=Symbol("zod_brand");class Yl 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 as 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(),lo(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 as({in:t,out:r,typeName:J.ZodPipeline})}}let is=class extends Pe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(qn(o)&&(o.value=Object.freeze(o.value)),o);return Jo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};is.create=(e,t)=>new is({innerType:e,typeName:J.ZodReadonly,...$e(t)});function Bf(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Jf(e,t={},r){return e?uo.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=Bf(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=Bf(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):uo.create()}const ub={object:or.lazycreate};var J;(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"})(J||(J={}));const db=(e,t={message:`Input not instance of ${e.name}`})=>Jf(r=>r instanceof e,t),Fe=co.create,sr=Wo.create,pb=pi.create,fb=hn.create,Wf=Go.create,hb=Ln.create,mb=ci.create,gb=Ko.create,yb=Yo.create,vb=uo.create,_b=jn.create,wb=Gr.create,bb=ui.create,Yr=Dn.create,Vt=or.create,kb=or.strictCreate,fi=Qo.create,Tb=Ff.create,Cb=Xo.create,Sb=qr.create,Ib=Vf.create,xb=di.create,Eb=Un.create,$b=fo.create,Rb=es.create,Pb=ts.create,ls=rs.create,Mb=ns.create,Ob=ho.create,Gf=gr.create,Nb=yr.create,Ab=mn.create,qb=gr.createWithPreprocess,Lb=as.create,jb=Object.freeze(Object.defineProperty({__proto__:null,BRAND:cb,DIRTY:lo,EMPTY_PATH:zw,INVALID:ke,NEVER:ke,OK:Dt,ParseStatus:Nt,Schema:Pe,ZodAny:uo,ZodArray:Dn,ZodBigInt:hn,ZodBoolean:Go,ZodBranded:Yl,ZodCatch:ss,ZodDate:Ln,ZodDefault:os,ZodDiscriminatedUnion:Ff,ZodEffects:gr,ZodEnum:rs,ZodError:Qt,get ZodFirstPartyTypeKind(){return J},ZodFunction:fo,ZodIntersection:Xo,ZodIssueCode:X,ZodLazy:es,ZodLiteral:ts,ZodMap:di,ZodNaN:pi,ZodNativeEnum:ns,ZodNever:Gr,ZodNull:Yo,ZodNullable:mn,ZodNumber:Wo,ZodObject:or,ZodOptional:yr,ZodParsedType:ce,ZodPipeline:as,ZodPromise:ho,ZodReadonly:is,ZodRecord:Vf,ZodSchema:Pe,ZodSet:Un,ZodString:co,ZodSymbol:ci,ZodTransformer:gr,ZodTuple:qr,ZodType:Pe,ZodUndefined:Ko,ZodUnion:Qo,ZodUnknown:jn,ZodVoid:ui,addIssueToContext:se,any:vb,array:Yr,bigint:fb,boolean:Wf,coerce:{string:(e=>co.create({...e,coerce:!0})),number:(e=>Wo.create({...e,coerce:!0})),boolean:(e=>Go.create({...e,coerce:!0})),bigint:(e=>hn.create({...e,coerce:!0})),date:(e=>Ln.create({...e,coerce:!0}))},custom:Jf,date:hb,datetimeRegex:Zf,defaultErrorMap:io,discriminatedUnion:Tb,effect:Gf,enum:ls,function:$b,getErrorMap:ii,getParsedType:Wr,instanceof:db,intersection:Cb,isAborted:Jl,isAsync:Jo,isDirty:Wl,isValid:qn,late:ub,lazy:Rb,literal:Pb,makeIssue:li,map:xb,nan:pb,nativeEnum:Mb,never:wb,null:yb,nullable:Ab,number:sr,object:Vt,get objectUtil(){return Bl},oboolean:()=>Wf().optional(),onumber:()=>sr().optional(),optional:Nb,ostring:()=>Fe().optional(),pipeline:Lb,preprocess:qb,promise:Ob,quotelessJson:Dw,record:Ib,set:Eb,setErrorMap:Uw,strictObject:kb,string:Fe,symbol:mb,transformer:Gf,tuple:Sb,undefined:gb,union:fi,unknown:_b,get util(){return De},void:bb},Symbol.toStringTag,{value:"Module"})),Kf=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 cs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Yf={};function gn(e){return Yf}function Qf(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 Db(e,t){return typeof t=="bigint"?t.toString():t}function Ql(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Xl(e){return e==null}function ec(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ub(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 us(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ds(e){return JSON.stringify(e)}const Xf=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const zb=Ql(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function mi(e){if(hi(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(hi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Zb=new Set(["string","number","symbol"]);function ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function pe(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 Fb(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Vb={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 Hb(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 yn(e,{...e._zod.def,shape:r,checks:[]})}function Bb(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 yn(e,{...e._zod.def,shape:r,checks:[]})}function Jb(e,t){if(!mi(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 us(this,"shape",n),n},checks:[]};return yn(e,r)}function Wb(e,t){return yn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return us(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Gb(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 yn(t,{...t._zod.def,shape:o,checks:[]})}function Kb(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 yn(t,{...t._zod.def,shape:o,checks:[]})}function fs(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function zn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function gi(e){return typeof e=="string"?e:e?.message}function vn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=gi(e.inst?._zod.def?.error?.(e))??gi(t?.error?.(e))??gi(r.customError?.(e))??gi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function tc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function hs(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const eh=(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,Db,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},th=W("$ZodError",eh),yi=W("$ZodError",eh,{Parent:Error});function Yb(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 Qb(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 rh=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 cs;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>vn(l,s,gn())));throw Xf(i,o?.callee),i}return a.value},Xb=rh(yi),nh=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=>vn(l,s,gn())));throw Xf(i,o?.callee),i}return a.value},e3=nh(yi),oh=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 cs;return s.issues.length?{success:!1,error:new(e??th)(s.issues.map(a=>vn(a,o,gn())))}:{success:!0,data:s.value}},rc=oh(yi),sh=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=>vn(a,o,gn())))}:{success:!0,data:s.value}},nc=sh(yi),t3=/^[cC][^\s-]{8,}$/,r3=/^[0-9a-z]+$/,n3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,o3=/^[0-9a-vA-V]{20}$/,s3=/^[A-Za-z0-9]{27}$/,a3=/^[a-zA-Z0-9_-]{21}$/,i3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,l3=/^([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})$/,ah=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)$/,c3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,u3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function d3(){return new RegExp(u3,"u")}const 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])$/,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})$/,h3=/^((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])$/,m3=/^(([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])$/,g3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ih=/^[A-Za-z0-9_-]*$/,y3=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,v3=/^\+(?:[0-9]){6,14}[0-9]$/,lh="(?:(?:\\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])))",_3=new RegExp(`^${lh}$`);function ch(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 w3(e){return new RegExp(`^${ch(e)}$`)}function b3(e){const t=ch({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(`^${lh}T(?:${n})$`)}const k3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},T3=/^\d+$/,C3=/^-?\d+(?:\.\d+)?/i,S3=/true|false/i,I3=/null/i,x3=/^[^A-Z]*$/,E3=/^[^a-z]*$/,Ht=W("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),uh={number:"number",bigint:"bigint",object:"date"},dh=W("$ZodCheckLessThan",(e,t)=>{Ht.init(e,t);const r=uh[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})}}),ph=W("$ZodCheckGreaterThan",(e,t)=>{Ht.init(e,t);const r=uh[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})}}),$3=W("$ZodCheckMultipleOf",(e,t)=>{Ht.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):Ub(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})}}),R3=W("$ZodCheckNumberFormat",(e,t)=>{Ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Vb[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=T3)}),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})}}),P3=W("$ZodCheckMaxLength",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xl(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=tc(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),M3=W("$ZodCheckMinLength",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xl(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=tc(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),O3=W("$ZodCheckLengthEquals",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xl(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=tc(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})}}),vi=W("$ZodCheckStringFormat",(e,t)=>{var r,n;Ht.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=()=>{})}),N3=W("$ZodCheckRegex",(e,t)=>{vi.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})}}),A3=W("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=x3),vi.init(e,t)}),q3=W("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=E3),vi.init(e,t)}),L3=W("$ZodCheckIncludes",(e,t)=>{Ht.init(e,t);const r=ps(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})}}),j3=W("$ZodCheckStartsWith",(e,t)=>{Ht.init(e,t);const r=new RegExp(`^${ps(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})}}),D3=W("$ZodCheckEndsWith",(e,t)=>{Ht.init(e,t);const r=new RegExp(`.*${ps(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})}}),U3=W("$ZodCheckOverwrite",(e,t)=>{Ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class z3{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
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 T3={major:4,minor:0,patch:0},Ye=W("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=T3;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=ns(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new Xo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=ns(s,f)))});else{if(s.issues.length===f)continue;l||(l=ns(s,f))}}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 Xo;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=jl(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Dl(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ul=W("$ZodString",(e,t)=>{Ye.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??n3(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}}),nt=W("$ZodStringFormat",(e,t)=>{si.init(e,t),Ul.init(e,t)}),C3=W("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Fb),nt.init(e,t)}),S3=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=Ff(n))}else t.pattern??(t.pattern=Ff());nt.init(e,t)}),I3=W("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Vb),nt.init(e,t)}),E3=W("$ZodURL",(e,t)=>{nt.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:Qb.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})}}}),x3=W("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Bb()),nt.init(e,t)}),$3=W("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=zb),nt.init(e,t)}),R3=W("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=qb),nt.init(e,t)}),P3=W("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Lb),nt.init(e,t)}),M3=W("$ZodULID",(e,t)=>{t.pattern??(t.pattern=jb),nt.init(e,t)}),O3=W("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Db),nt.init(e,t)}),A3=W("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ub),nt.init(e,t)}),N3=W("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=r3(t)),nt.init(e,t)}),q3=W("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=e3),nt.init(e,t)}),L3=W("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=t3(t)),nt.init(e,t)}),j3=W("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Zb),nt.init(e,t)}),D3=W("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Jb),nt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),U3=W("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Wb),nt.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})}}}),z3=W("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Gb),nt.init(e,t)}),Z3=W("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Kb),nt.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 Kf(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const F3=W("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Yb),nt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Kf(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function V3(e){if(!Vf.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Kf(r)}const H3=W("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Vf),nt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{V3(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),B3=W("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Xb),nt.init(e,t)});function J3(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 W3=W("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=r=>{J3(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Yf=W("$ZodNumber",(e,t)=>{Ye.init(e,t),e._zod.pattern=e._zod.bag.pattern??s3,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}}),G3=W("$ZodNumber",(e,t)=>{d3.init(e,t),Yf.init(e,t)}),K3=W("$ZodBoolean",(e,t)=>{Ye.init(e,t),e._zod.pattern=a3,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}}),Y3=W("$ZodNull",(e,t)=>{Ye.init(e,t),e._zod.pattern=i3,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}}),Q3=W("$ZodAny",(e,t)=>{Ye.init(e,t),e._zod.parse=r=>r}),X3=W("$ZodUnknown",(e,t)=>{Ye.init(e,t),e._zod.parse=r=>r}),e9=W("$ZodNever",(e,t)=>{Ye.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Qf(e,t,r){e.issues.length&&t.issues.push(...Pn(r,e.issues)),t.value[r]=e.value}const t9=W("$ZodArray",(e,t)=>{Ye.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=>Qf(c,r,a))):Qf(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function ai(e,t,r){e.issues.length&&t.issues.push(...Pn(r,e.issues)),t.value[r]=e.value}function Xf(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(...Pn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const eh=W("$ZodObject",(e,t)=>{Ye.init(e,t);const r=Al(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof Ye))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=Cb(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});He(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const y=f[h]._zod;if(y.values){p[h]??(p[h]=new Set);for(const w of y.values)p[h].add(w)}}return p});const n=f=>{const p=new k3(["shape","payload","ctx"]),h=r.value,y=v=>{const m=ts(v);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const w=Object.create(null);let g=0;for(const v of h.keys)w[v]=`key_${g++}`;p.write("const newResult = {}");for(const v of h.keys)if(h.optionalKeys.has(v)){const m=w[v];p.write(`const ${m} = ${y(v)};`);const T=ts(v);p.write(`
10
+ `))}}const Z3={major:4,minor:0,patch:0},Ge=W("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Z3;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=fs(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 cs;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==h&&(l||(l=fs(s,h)))});else{if(s.issues.length===h)continue;l||(l=fs(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 cs;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=rc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return nc(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),oc=W("$ZodString",(e,t)=>{Ge.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??k3(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}}),nt=W("$ZodStringFormat",(e,t)=>{vi.init(e,t),oc.init(e,t)}),F3=W("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=l3),nt.init(e,t)}),V3=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=ah(n))}else t.pattern??(t.pattern=ah());nt.init(e,t)}),H3=W("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=c3),nt.init(e,t)}),B3=W("$ZodURL",(e,t)=>{nt.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:y3.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})}}}),J3=W("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=d3()),nt.init(e,t)}),W3=W("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=a3),nt.init(e,t)}),G3=W("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=t3),nt.init(e,t)}),K3=W("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=r3),nt.init(e,t)}),Y3=W("$ZodULID",(e,t)=>{t.pattern??(t.pattern=n3),nt.init(e,t)}),Q3=W("$ZodXID",(e,t)=>{t.pattern??(t.pattern=o3),nt.init(e,t)}),X3=W("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=s3),nt.init(e,t)}),e9=W("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=b3(t)),nt.init(e,t)}),t9=W("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=_3),nt.init(e,t)}),r9=W("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=w3(t)),nt.init(e,t)}),n9=W("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=i3),nt.init(e,t)}),o9=W("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=p3),nt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),s9=W("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=f3),nt.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})}}}),a9=W("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=h3),nt.init(e,t)}),i9=W("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=m3),nt.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 fh(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const l9=W("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=g3),nt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{fh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function c9(e){if(!ih.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return fh(r)}const u9=W("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ih),nt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{c9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),d9=W("$ZodE164",(e,t)=>{t.pattern??(t.pattern=v3),nt.init(e,t)});function p9(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 f9=W("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=r=>{p9(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),hh=W("$ZodNumber",(e,t)=>{Ge.init(e,t),e._zod.pattern=e._zod.bag.pattern??C3,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}}),h9=W("$ZodNumber",(e,t)=>{R3.init(e,t),hh.init(e,t)}),m9=W("$ZodBoolean",(e,t)=>{Ge.init(e,t),e._zod.pattern=S3,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}}),g9=W("$ZodNull",(e,t)=>{Ge.init(e,t),e._zod.pattern=I3,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}}),y9=W("$ZodAny",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),v9=W("$ZodUnknown",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),_9=W("$ZodNever",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function mh(e,t,r){e.issues.length&&t.issues.push(...zn(r,e.issues)),t.value[r]=e.value}const w9=W("$ZodArray",(e,t)=>{Ge.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=>mh(c,r,a))):mh(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function _i(e,t,r){e.issues.length&&t.issues.push(...zn(r,e.issues)),t.value[r]=e.value}function gh(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(...zn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const yh=W("$ZodObject",(e,t)=>{Ge.init(e,t);const r=Ql(()=>{const h=Object.keys(t.shape);for(const f of h)if(!(t.shape[f]instanceof Ge))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=Fb(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 z3(["shape","payload","ctx"]),f=r.value,g=v=>{const m=ds(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 C=ds(v);p.write(`
11
11
  if (${m}.issues.length) {
12
- if (input[${T}] === undefined) {
13
- if (${T} in input) {
14
- newResult[${T}] = undefined;
12
+ if (input[${C}] === undefined) {
13
+ if (${C} in input) {
14
+ newResult[${C}] = undefined;
15
15
  }
16
16
  } else {
17
17
  payload.issues = payload.issues.concat(
18
18
  ${m}.issues.map((iss) => ({
19
19
  ...iss,
20
- path: iss.path ? [${T}, ...iss.path] : [${T}],
20
+ path: iss.path ? [${C}, ...iss.path] : [${C}],
21
21
  }))
22
22
  );
23
23
  }
24
24
  } else if (${m}.value === undefined) {
25
- if (${T} in input) newResult[${T}] = undefined;
25
+ if (${C} in input) newResult[${C}] = undefined;
26
26
  } else {
27
- newResult[${T}] = ${m}.value;
27
+ newResult[${C}] = ${m}.value;
28
28
  }
29
- `)}else{const m=w[v];p.write(`const ${m} = ${y(v)};`),p.write(`
29
+ `)}else{const m=_[v];p.write(`const ${m} = ${g(v)};`),p.write(`
30
30
  if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
31
31
  ...iss,
32
- path: iss.path ? [${ts(v)}, ...iss.path] : [${ts(v)}]
33
- })));`),p.write(`newResult[${ts(v)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const b=p.compile();return(v,m)=>b(f,v,m)};let o;const s=ti,a=!Af.jitless,l=a&&kb.value,c=t.catchall;let u;e._zod.parse=(f,p)=>{u??(u=r.value);const h=f.value;if(!s(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;const y=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),f=o(f,p);else{f.value={};const m=u.shape;for(const T of u.keys){const k=m[T],_=k._zod.run({value:h[T],issues:[]},p),S=k._zod.optin==="optional"&&k._zod.optout==="optional";_ instanceof Promise?y.push(_.then($=>S?Xf($,f,T,h):ai($,f,T))):S?Xf(_,f,T,h):ai(_,f,T)}}if(!c)return y.length?Promise.all(y).then(()=>f):f;const w=[],g=u.keySet,b=c._zod,v=b.def.type;for(const m of Object.keys(h)){if(g.has(m))continue;if(v==="never"){w.push(m);continue}const T=b.run({value:h[m],issues:[]},p);T instanceof Promise?y.push(T.then(k=>ai(k,f,m))):ai(T,f,m)}return w.length&&f.issues.push({code:"unrecognized_keys",keys:w,input:h,inst:e}),y.length?Promise.all(y).then(()=>f):f}});function th(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=>an(s,n,on())))}),t}const rh=W("$ZodUnion",(e,t)=>{Ye.init(e,t),He(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),He(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),He(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),He(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=>ql(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=>th(a,r,e,n)):th(s,r,e,n)}}),r9=W("$ZodDiscriminatedUnion",(e,t)=>{rh.init(e,t);const r=e._zod.parse;He(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=Al(()=>{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(!ti(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)}}),n9=W("$ZodIntersection",(e,t)=>{Ye.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])=>nh(r,l,c)):nh(r,s,a)}});function zl(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(ri(e)&&ri(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=zl(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=zl(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 nh(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),ns(e))return e;const n=zl(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 o9=W("$ZodRecord",(e,t)=>{Ye.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!ri(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(...Pn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Pn(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=>an(c,n,on())),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(...Pn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Pn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),s9=W("$ZodEnum",(e,t)=>{Ye.init(e,t);const r=Nf(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Tb.has(typeof n)).map(n=>typeof n=="string"?rs(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}}),a9=W("$ZodLiteral",(e,t)=>{Ye.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?rs(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}}),i9=W("$ZodTransform",(e,t)=>{Ye.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 Xo;return r.value=o,r}}),l9=W("$ZodOptional",(e,t)=>{Ye.init(e,t),e._zod.optin="optional",e._zod.optout="optional",He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${ql(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)}),c9=W("$ZodNullable",(e,t)=>{Ye.init(e,t),He(e._zod,"optin",()=>t.innerType._zod.optin),He(e._zod,"optout",()=>t.innerType._zod.optout),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${ql(r.source)}|null)$`):void 0}),He(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)}),u9=W("$ZodDefault",(e,t)=>{Ye.init(e,t),e._zod.optin="optional",He(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=>oh(s,t)):oh(o,t)}});function oh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const d9=W("$ZodPrefault",(e,t)=>{Ye.init(e,t),e._zod.optin="optional",He(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))}),p9=W("$ZodNonOptional",(e,t)=>{Ye.init(e,t),He(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=>sh(s,e)):sh(o,e)}});function sh(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 f9=W("$ZodCatch",(e,t)=>{Ye.init(e,t),e._zod.optin="optional",He(e._zod,"optout",()=>t.innerType._zod.optout),He(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=>an(a,n,on()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>an(s,n,on()))},input:r.value}),r.issues=[]),r)}}),h9=W("$ZodPipe",(e,t)=>{Ye.init(e,t),He(e._zod,"values",()=>t.in._zod.values),He(e._zod,"optin",()=>t.in._zod.optin),He(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=>ah(s,t,n)):ah(o,t,n)}});function ah(e,t,r){return ns(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const m9=W("$ZodReadonly",(e,t)=>{Ye.init(e,t),He(e._zod,"propValues",()=>t.innerType._zod.propValues),He(e._zod,"values",()=>t.innerType._zod.values),He(e._zod,"optin",()=>t.innerType._zod.optin),He(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(ih):ih(o)}});function ih(e){return e.value=Object.freeze(e.value),e}const g9=W("$ZodLazy",(e,t)=>{Ye.init(e,t),He(e._zod,"innerType",()=>t.getter()),He(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),He(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),He(e._zod,"optin",()=>e._zod.innerType._zod.optin),He(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),y9=W("$ZodCustom",(e,t)=>{Dt.init(e,t),Ye.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=>lh(s,r,n,e));lh(o,r,n,e)}});function lh(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(os(o))}}class ch{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 v9(){return new ch}const ss=v9();function _9(e,t){return new e({type:"string",...fe(t)})}function w9(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function uh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function b9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function k9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function T9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function C9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function dh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function S9(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function I9(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function E9(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function x9(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function $9(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function R9(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function P9(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function M9(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function O9(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function A9(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(t)})}function N9(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function ph(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function q9(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function L9(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function j9(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function D9(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function U9(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function z9(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function Z9(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function F9(e,t){return new e({type:"number",checks:[],...fe(t)})}function V9(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function H9(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function B9(e,t){return new e({type:"boolean",...fe(t)})}function J9(e,t){return new e({type:"null",...fe(t)})}function W9(e){return new e({type:"any"})}function G9(e){return new e({type:"unknown"})}function K9(e,t){return new e({type:"never",...fe(t)})}function fh(e,t){return new Wf({check:"less_than",...fe(t),value:e,inclusive:!1})}function Zl(e,t){return new Wf({check:"less_than",...fe(t),value:e,inclusive:!0})}function hh(e,t){return new Gf({check:"greater_than",...fe(t),value:e,inclusive:!1})}function Fl(e,t){return new Gf({check:"greater_than",...fe(t),value:e,inclusive:!0})}function mh(e,t){return new u3({check:"multiple_of",...fe(t),value:e})}function gh(e,t){return new p3({check:"max_length",...fe(t),maximum:e})}function ii(e,t){return new f3({check:"min_length",...fe(t),minimum:e})}function yh(e,t){return new h3({check:"length_equals",...fe(t),length:e})}function Y9(e,t){return new m3({check:"string_format",format:"regex",...fe(t),pattern:e})}function Q9(e){return new g3({check:"string_format",format:"lowercase",...fe(e)})}function X9(e){return new y3({check:"string_format",format:"uppercase",...fe(e)})}function e4(e,t){return new v3({check:"string_format",format:"includes",...fe(t),includes:e})}function t4(e,t){return new _3({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function r4(e,t){return new w3({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function as(e){return new b3({check:"overwrite",tx:e})}function n4(e){return as(t=>t.normalize(e))}function o4(){return as(e=>e.trim())}function s4(){return as(e=>e.toLowerCase())}function a4(){return as(e=>e.toUpperCase())}function i4(e,t,r){return new e({type:"array",element:t,...fe(r)})}function l4(e,t,r){const n=fe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function c4(e,t,r){return new e({type:"custom",check:"custom",fn:t,...fe(r)})}class vh{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??ss,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 f={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,f),this.seen.get(p).isParent=!0;else{const h=i.schema;switch(o.type){case"string":{const y=h;y.type="string";const{minimum:w,maximum:g,format:b,patterns:v,contentEncoding:m}=t._zod.bag;if(typeof w=="number"&&(y.minLength=w),typeof g=="number"&&(y.maxLength=g),b&&(y.format=s[b]??b,y.format===""&&delete y.format),m&&(y.contentEncoding=m),v&&v.size>0){const T=[...v];T.length===1?y.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const y=h,{minimum:w,maximum:g,format:b,multipleOf:v,exclusiveMaximum:m,exclusiveMinimum:T}=t._zod.bag;typeof b=="string"&&b.includes("int")?y.type="integer":y.type="number",typeof T=="number"&&(y.exclusiveMinimum=T),typeof w=="number"&&(y.minimum=w,typeof T=="number"&&(T>=w?delete y.minimum:delete y.exclusiveMinimum)),typeof m=="number"&&(y.exclusiveMaximum=m),typeof g=="number"&&(y.maximum=g,typeof m=="number"&&(m<=g?delete y.maximum:delete y.exclusiveMaximum)),typeof v=="number"&&(y.multipleOf=v);break}case"boolean":{const y=h;y.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const y=h,{minimum:w,maximum:g}=t._zod.bag;typeof w=="number"&&(y.minItems=w),typeof g=="number"&&(y.maxItems=g),y.type="array",y.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const y=h;y.type="object",y.properties={};const w=o.shape;for(const v in w)y.properties[v]=this.process(w[v],{...f,path:[...f.path,"properties",v]});const g=new Set(Object.keys(w)),b=new Set([...g].filter(v=>{const m=o.shape[v]._zod;return this.io==="input"?m.optin===void 0:m.optout===void 0}));b.size>0&&(y.required=Array.from(b)),o.catchall?._zod.def.type==="never"?y.additionalProperties=!1:o.catchall?o.catchall&&(y.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(y.additionalProperties=!1);break}case"union":{const y=h;y.anyOf=o.options.map((w,g)=>this.process(w,{...f,path:[...f.path,"anyOf",g]}));break}case"intersection":{const y=h,w=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),g=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),b=m=>"allOf"in m&&Object.keys(m).length===1,v=[...b(w)?w.allOf:[w],...b(g)?g.allOf:[g]];y.allOf=v;break}case"tuple":{const y=h;y.type="array";const w=o.items.map((v,m)=>this.process(v,{...f,path:[...f.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?y.prefixItems=w:y.items=w,o.rest){const v=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?y.items=v:y.additionalItems=v}o.rest&&(y.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:g,maximum:b}=t._zod.bag;typeof g=="number"&&(y.minItems=g),typeof b=="number"&&(y.maxItems=b);break}case"record":{const y=h;y.type="object",y.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),y.additionalProperties=this.process(o.valueType,{...f,path:[...f.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 y=h,w=Nf(o.entries);w.every(g=>typeof g=="number")&&(y.type="number"),w.every(g=>typeof g=="string")&&(y.type="string"),y.enum=w;break}case"literal":{const y=h,w=[];for(const g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(g))}else w.push(g);if(w.length!==0)if(w.length===1){const g=w[0];y.type=g===null?"null":typeof g,y.const=g}else w.every(g=>typeof g=="number")&&(y.type="number"),w.every(g=>typeof g=="string")&&(y.type="string"),w.every(g=>typeof g=="boolean")&&(y.type="string"),w.every(g=>g===null)&&(y.type="null"),y.enum=w;break}case"file":{const y=h,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:b,mime:v}=t._zod.bag;g!==void 0&&(w.minLength=g),b!==void 0&&(w.maxLength=b),v?v.length===1?(w.contentMediaType=v[0],Object.assign(y,w)):y.anyOf=v.map(m=>({...w,contentMediaType:m})):Object.assign(y,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const y=this.process(o.innerType,f);h.anyOf=[y,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const y=h;y.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let y;try{y=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=y;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const y=h,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");y.type="string",y.pattern=w.source;break}case"pipe":{const y=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(y,f),i.ref=y;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const y=t._zod.innerType;this.process(y,f),i.ref=y;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"&&pt(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 f=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(u[0])?.id,g=n.external.uri??(v=>v);if(w)return{ref:g(w)};const b=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=b,{defId:b,ref:`${g("__shared")}#/${f}/${b}`}}if(u[1]===o)return{ref:"#"};const h=`#/${f}/`,y=u[1].schema.id??`__schema${this.counter++}`;return{defId:y,ref:h+y}},a=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:p,defId:h}=s(u);f.def={...f.schema},h&&(f.defId=h);const y=f.schema;for(const w in y)delete y[w];y.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
32
+ path: iss.path ? [${ds(v)}, ...iss.path] : [${ds(v)}]
33
+ })));`),p.write(`newResult[${ds(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=hi,a=!Yf.jitless,l=a&&zb.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 C of u.keys){const k=m[C],b=k._zod.run({value:f[C],issues:[]},p),S=k._zod.optin==="optional"&&k._zod.optout==="optional";b instanceof Promise?g.push(b.then(x=>S?gh(x,h,C,f):_i(x,h,C))):S?gh(b,h,C,f):_i(b,h,C)}}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 C=w.run({value:f[m],issues:[]},p);C instanceof Promise?g.push(C.then(k=>_i(k,h,m))):_i(C,h,m)}return _.length&&h.issues.push({code:"unrecognized_keys",keys:_,input:f,inst:e}),g.length?Promise.all(g).then(()=>h):h}});function vh(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=>vn(s,n,gn())))}),t}const _h=W("$ZodUnion",(e,t)=>{Ge.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=>ec(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=>vh(a,r,e,n)):vh(s,r,e,n)}}),b9=W("$ZodDiscriminatedUnion",(e,t)=>{_h.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=Ql(()=>{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(!hi(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)}}),k9=W("$ZodIntersection",(e,t)=>{Ge.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])=>wh(r,l,c)):wh(r,s,a)}});function sc(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(mi(e)&&mi(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=sc(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=sc(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 wh(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),fs(e))return e;const n=sc(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 T9=W("$ZodRecord",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!mi(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(...zn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...zn(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=>vn(c,n,gn())),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(...zn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...zn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),C9=W("$ZodEnum",(e,t)=>{Ge.init(e,t);const r=Qf(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Zb.has(typeof n)).map(n=>typeof n=="string"?ps(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}}),S9=W("$ZodLiteral",(e,t)=>{Ge.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ps(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}}),I9=W("$ZodTransform",(e,t)=>{Ge.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 cs;return r.value=o,r}}),x9=W("$ZodOptional",(e,t)=>{Ge.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(`^(${ec(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)}),E9=W("$ZodNullable",(e,t)=>{Ge.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(`^(${ec(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)}),$9=W("$ZodDefault",(e,t)=>{Ge.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=>bh(s,t)):bh(o,t)}});function bh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const R9=W("$ZodPrefault",(e,t)=>{Ge.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))}),P9=W("$ZodNonOptional",(e,t)=>{Ge.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=>kh(s,e)):kh(o,e)}});function kh(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 M9=W("$ZodCatch",(e,t)=>{Ge.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=>vn(a,n,gn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>vn(s,n,gn()))},input:r.value}),r.issues=[]),r)}}),O9=W("$ZodPipe",(e,t)=>{Ge.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=>Th(s,t,n)):Th(o,t,n)}});function Th(e,t,r){return fs(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const N9=W("$ZodReadonly",(e,t)=>{Ge.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(Ch):Ch(o)}});function Ch(e){return e.value=Object.freeze(e.value),e}const A9=W("$ZodLazy",(e,t)=>{Ge.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)}),q9=W("$ZodCustom",(e,t)=>{Ht.init(e,t),Ge.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=>Sh(s,r,n,e));Sh(o,r,n,e)}});function Sh(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(hs(o))}}class Ih{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 L9(){return new Ih}const ms=L9();function j9(e,t){return new e({type:"string",...pe(t)})}function D9(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...pe(t)})}function xh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...pe(t)})}function U9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...pe(t)})}function z9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...pe(t)})}function Z9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...pe(t)})}function F9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...pe(t)})}function Eh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...pe(t)})}function V9(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...pe(t)})}function H9(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...pe(t)})}function B9(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...pe(t)})}function J9(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...pe(t)})}function W9(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...pe(t)})}function G9(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...pe(t)})}function K9(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...pe(t)})}function Y9(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...pe(t)})}function Q9(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...pe(t)})}function X9(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...pe(t)})}function e4(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...pe(t)})}function $h(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...pe(t)})}function t4(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...pe(t)})}function r4(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...pe(t)})}function n4(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...pe(t)})}function o4(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...pe(t)})}function s4(e,t){return new e({type:"string",format:"date",check:"string_format",...pe(t)})}function a4(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...pe(t)})}function i4(e,t){return new e({type:"string",format:"duration",check:"string_format",...pe(t)})}function l4(e,t){return new e({type:"number",checks:[],...pe(t)})}function c4(e,t){return new e({type:"number",coerce:!0,checks:[],...pe(t)})}function u4(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...pe(t)})}function d4(e,t){return new e({type:"boolean",...pe(t)})}function p4(e,t){return new e({type:"null",...pe(t)})}function f4(e){return new e({type:"any"})}function h4(e){return new e({type:"unknown"})}function m4(e,t){return new e({type:"never",...pe(t)})}function Rh(e,t){return new dh({check:"less_than",...pe(t),value:e,inclusive:!1})}function ac(e,t){return new dh({check:"less_than",...pe(t),value:e,inclusive:!0})}function Ph(e,t){return new ph({check:"greater_than",...pe(t),value:e,inclusive:!1})}function ic(e,t){return new ph({check:"greater_than",...pe(t),value:e,inclusive:!0})}function Mh(e,t){return new $3({check:"multiple_of",...pe(t),value:e})}function Oh(e,t){return new P3({check:"max_length",...pe(t),maximum:e})}function wi(e,t){return new M3({check:"min_length",...pe(t),minimum:e})}function Nh(e,t){return new O3({check:"length_equals",...pe(t),length:e})}function g4(e,t){return new N3({check:"string_format",format:"regex",...pe(t),pattern:e})}function y4(e){return new A3({check:"string_format",format:"lowercase",...pe(e)})}function v4(e){return new q3({check:"string_format",format:"uppercase",...pe(e)})}function _4(e,t){return new L3({check:"string_format",format:"includes",...pe(t),includes:e})}function w4(e,t){return new j3({check:"string_format",format:"starts_with",...pe(t),prefix:e})}function b4(e,t){return new D3({check:"string_format",format:"ends_with",...pe(t),suffix:e})}function gs(e){return new U3({check:"overwrite",tx:e})}function k4(e){return gs(t=>t.normalize(e))}function T4(){return gs(e=>e.trim())}function C4(){return gs(e=>e.toLowerCase())}function S4(){return gs(e=>e.toUpperCase())}function I4(e,t,r){return new e({type:"array",element:t,...pe(r)})}function x4(e,t,r){const n=pe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function E4(e,t,r){return new e({type:"custom",check:"custom",fn:t,...pe(r)})}class Ah{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??ms,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 C=[...v];C.length===1?g.pattern=C[0].source:C.length>1&&(i.schema.allOf=[...C.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:C}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof C=="number"&&(g.exclusiveMinimum=C),typeof _=="number"&&(g.minimum=_,typeof C=="number"&&(C>=_?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,_=Qf(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"&&wt(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
34
 
35
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const f=u[1];if(t===u[0]){a(u);continue}if(n.external){const h=n.external.registry.get(u[0])?.id;if(t!==u[0]&&h){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(f.cycle){a(u);continue}if(f.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,f)=>{const p=this.seen.get(u),h=p.def??p.schema,y={...h};if(p.ref===null)return;const w=p.ref;if(p.ref=null,w){i(w,f);const g=this.seen.get(w).schema;g.$ref&&f.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,y))}p.isParent||this.override({zodSchema:u,jsonSchema:h,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 f=u[1];f.def&&f.defId&&(c[f.defId]=f.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 _h(e,t){if(e instanceof ch){const n=new vh(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 vh(t);return r.process(e),r.emit(e,t)}function pt(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 pt(o.element,r);case"object":{for(const s in o.shape)if(pt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(pt(s,r))return!0;return!1}case"intersection":return pt(o.left,r)||pt(o.right,r);case"tuple":{for(const s of o.items)if(pt(s,r))return!0;return!!(o.rest&&pt(o.rest,r))}case"record":return pt(o.keyType,r)||pt(o.valueType,r);case"map":return pt(o.keyType,r)||pt(o.valueType,r);case"set":return pt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return pt(o.innerType,r);case"lazy":return pt(o.getter(),r);case"default":return pt(o.innerType,r);case"prefault":return pt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return pt(o.in,r)||pt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const u4=W("ZodISODateTime",(e,t)=>{N3.init(e,t),st.init(e,t)});function wh(e){return D9(u4,e)}const d4=W("ZodISODate",(e,t)=>{q3.init(e,t),st.init(e,t)});function p4(e){return U9(d4,e)}const f4=W("ZodISOTime",(e,t)=>{L3.init(e,t),st.init(e,t)});function h4(e){return z9(f4,e)}const m4=W("ZodISODuration",(e,t)=>{j3.init(e,t),st.init(e,t)});function g4(e){return Z9(m4,e)}const li=W("ZodError",(e,t)=>{jf.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Ob(e,r)},flatten:{value:r=>Mb(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}),y4=Df(li),v4=Uf(li),_4=zf(li),bh=Zf(li),rt=W("ZodType",(e,t)=>(Ye.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)=>sn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>y4(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>_4(e,r,n),e.parseAsync=async(r,n)=>v4(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>bh(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(ck(r,n)),e.superRefine=r=>e.check(uk(r)),e.overwrite=r=>e.check(as(r)),e.optional=()=>ue(e),e.nullable=()=>Mh(e),e.nullish=()=>ue(Mh(e)),e.nonoptional=r=>tk(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>Hl(e,r),e.transform=r=>Jl(e,Rh(r)),e.default=r=>Q4(e,r),e.prefault=r=>ek(e,r),e.catch=r=>nk(e,r),e.pipe=r=>Jl(e,r),e.readonly=()=>ak(e),e.describe=r=>{const n=e.clone();return ss.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ss.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ss.get(e);const n=e.clone();return ss.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),kh=W("_ZodString",(e,t)=>{Ul.init(e,t),rt.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(Y9(...n)),e.includes=(...n)=>e.check(e4(...n)),e.startsWith=(...n)=>e.check(t4(...n)),e.endsWith=(...n)=>e.check(r4(...n)),e.min=(...n)=>e.check(ii(...n)),e.max=(...n)=>e.check(gh(...n)),e.length=(...n)=>e.check(yh(...n)),e.nonempty=(...n)=>e.check(ii(1,...n)),e.lowercase=n=>e.check(Q9(n)),e.uppercase=n=>e.check(X9(n)),e.trim=()=>e.check(o4()),e.normalize=(...n)=>e.check(n4(...n)),e.toLowerCase=()=>e.check(s4()),e.toUpperCase=()=>e.check(a4())}),w4=W("ZodString",(e,t)=>{Ul.init(e,t),kh.init(e,t),e.email=r=>e.check(w9(b4,r)),e.url=r=>e.check(dh(Ch,r)),e.jwt=r=>e.check(j9(q4,r)),e.emoji=r=>e.check(S9(T4,r)),e.guid=r=>e.check(uh(Th,r)),e.uuid=r=>e.check(b9(ci,r)),e.uuidv4=r=>e.check(k9(ci,r)),e.uuidv6=r=>e.check(T9(ci,r)),e.uuidv7=r=>e.check(C9(ci,r)),e.nanoid=r=>e.check(I9(C4,r)),e.guid=r=>e.check(uh(Th,r)),e.cuid=r=>e.check(E9(S4,r)),e.cuid2=r=>e.check(x9(I4,r)),e.ulid=r=>e.check($9(E4,r)),e.base64=r=>e.check(ph(Sh,r)),e.base64url=r=>e.check(q9(A4,r)),e.xid=r=>e.check(R9(x4,r)),e.ksuid=r=>e.check(P9($4,r)),e.ipv4=r=>e.check(M9(R4,r)),e.ipv6=r=>e.check(O9(P4,r)),e.cidrv4=r=>e.check(A9(M4,r)),e.cidrv6=r=>e.check(N9(O4,r)),e.e164=r=>e.check(L9(N4,r)),e.datetime=r=>e.check(wh(r)),e.date=r=>e.check(p4(r)),e.time=r=>e.check(h4(r)),e.duration=r=>e.check(g4(r))});function d(e){return _9(w4,e)}const st=W("ZodStringFormat",(e,t)=>{nt.init(e,t),kh.init(e,t)}),b4=W("ZodEmail",(e,t)=>{I3.init(e,t),st.init(e,t)}),Th=W("ZodGUID",(e,t)=>{C3.init(e,t),st.init(e,t)}),ci=W("ZodUUID",(e,t)=>{S3.init(e,t),st.init(e,t)}),Ch=W("ZodURL",(e,t)=>{E3.init(e,t),st.init(e,t)});function k4(e){return dh(Ch,e)}const T4=W("ZodEmoji",(e,t)=>{x3.init(e,t),st.init(e,t)}),C4=W("ZodNanoID",(e,t)=>{$3.init(e,t),st.init(e,t)}),S4=W("ZodCUID",(e,t)=>{R3.init(e,t),st.init(e,t)}),I4=W("ZodCUID2",(e,t)=>{P3.init(e,t),st.init(e,t)}),E4=W("ZodULID",(e,t)=>{M3.init(e,t),st.init(e,t)}),x4=W("ZodXID",(e,t)=>{O3.init(e,t),st.init(e,t)}),$4=W("ZodKSUID",(e,t)=>{A3.init(e,t),st.init(e,t)}),R4=W("ZodIPv4",(e,t)=>{D3.init(e,t),st.init(e,t)}),P4=W("ZodIPv6",(e,t)=>{U3.init(e,t),st.init(e,t)}),M4=W("ZodCIDRv4",(e,t)=>{z3.init(e,t),st.init(e,t)}),O4=W("ZodCIDRv6",(e,t)=>{Z3.init(e,t),st.init(e,t)}),Sh=W("ZodBase64",(e,t)=>{F3.init(e,t),st.init(e,t)});function Ih(e){return ph(Sh,e)}const A4=W("ZodBase64URL",(e,t)=>{H3.init(e,t),st.init(e,t)}),N4=W("ZodE164",(e,t)=>{B3.init(e,t),st.init(e,t)}),q4=W("ZodJWT",(e,t)=>{W3.init(e,t),st.init(e,t)}),Vl=W("ZodNumber",(e,t)=>{Yf.init(e,t),rt.init(e,t),e.gt=(n,o)=>e.check(hh(n,o)),e.gte=(n,o)=>e.check(Fl(n,o)),e.min=(n,o)=>e.check(Fl(n,o)),e.lt=(n,o)=>e.check(fh(n,o)),e.lte=(n,o)=>e.check(Zl(n,o)),e.max=(n,o)=>e.check(Zl(n,o)),e.int=n=>e.check(Eh(n)),e.safe=n=>e.check(Eh(n)),e.positive=n=>e.check(hh(0,n)),e.nonnegative=n=>e.check(Fl(0,n)),e.negative=n=>e.check(fh(0,n)),e.nonpositive=n=>e.check(Zl(0,n)),e.multipleOf=(n,o)=>e.check(mh(n,o)),e.step=(n,o)=>e.check(mh(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 F9(Vl,e)}const L4=W("ZodNumberFormat",(e,t)=>{G3.init(e,t),Vl.init(e,t)});function Eh(e){return H9(L4,e)}const j4=W("ZodBoolean",(e,t)=>{K3.init(e,t),rt.init(e,t)});function me(e){return B9(j4,e)}const D4=W("ZodNull",(e,t)=>{Y3.init(e,t),rt.init(e,t)});function ui(e){return J9(D4,e)}const U4=W("ZodAny",(e,t)=>{Q3.init(e,t),rt.init(e,t)});function mt(){return W9(U4)}const z4=W("ZodUnknown",(e,t)=>{X3.init(e,t),rt.init(e,t)});function Le(){return G9(z4)}const Z4=W("ZodNever",(e,t)=>{e9.init(e,t),rt.init(e,t)});function F4(e){return K9(Z4,e)}const V4=W("ZodArray",(e,t)=>{t9.init(e,t),rt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ii(r,n)),e.nonempty=r=>e.check(ii(1,r)),e.max=(r,n)=>e.check(gh(r,n)),e.length=(r,n)=>e.check(yh(r,n)),e.unwrap=()=>e.element});function q(e,t){return i4(V4,e,t)}const xh=W("ZodObject",(e,t)=>{eh.init(e,t),rt.init(e,t),He(e,"shape",()=>t.shape),e.keyof=()=>Ee(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Le()}),e.loose=()=>e.clone({...e._zod.def,catchall:Le()}),e.strict=()=>e.clone({...e._zod.def,catchall:F4()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>xb(e,r),e.merge=r=>$b(e,r),e.pick=r=>Ib(e,r),e.omit=r=>Eb(e,r),e.partial=(...r)=>Rb(Ph,e,r[0]),e.required=(...r)=>Pb(Oh,e,r[0])});function C(e,t){const r={type:"object",get shape(){return es(this,"shape",{...e}),this.shape},...fe(t)};return new xh(r)}function at(e,t){return new xh({type:"object",get shape(){return es(this,"shape",{...e}),this.shape},catchall:Le(),...fe(t)})}const $h=W("ZodUnion",(e,t)=>{rh.init(e,t),rt.init(e,t),e.options=t.options});function oe(e,t){return new $h({type:"union",options:e,...fe(t)})}const H4=W("ZodDiscriminatedUnion",(e,t)=>{$h.init(e,t),r9.init(e,t)});function tt(e,t,r){return new H4({type:"union",options:t,discriminator:e,...fe(r)})}const B4=W("ZodIntersection",(e,t)=>{n9.init(e,t),rt.init(e,t)});function Hl(e,t){return new B4({type:"intersection",left:e,right:t})}const J4=W("ZodRecord",(e,t)=>{o9.init(e,t),rt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ge(e,t,r){return new J4({type:"record",keyType:e,valueType:t,...fe(r)})}const Bl=W("ZodEnum",(e,t)=>{s9.init(e,t),rt.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 Bl({...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 Bl({...t,checks:[],...fe(o),entries:s})}});function Ee(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Bl({type:"enum",entries:r,...fe(t)})}const W4=W("ZodLiteral",(e,t)=>{a9.init(e,t),rt.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 P(e,t){return new W4({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const G4=W("ZodTransform",(e,t)=>{i9.init(e,t),rt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(os(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(os(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Rh(e){return new G4({type:"transform",transform:e})}const Ph=W("ZodOptional",(e,t)=>{l9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ue(e){return new Ph({type:"optional",innerType:e})}const K4=W("ZodNullable",(e,t)=>{c9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Mh(e){return new K4({type:"nullable",innerType:e})}const Y4=W("ZodDefault",(e,t)=>{u9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q4(e,t){return new Y4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const X4=W("ZodPrefault",(e,t)=>{d9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ek(e,t){return new X4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Oh=W("ZodNonOptional",(e,t)=>{p9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tk(e,t){return new Oh({type:"nonoptional",innerType:e,...fe(t)})}const rk=W("ZodCatch",(e,t)=>{f9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nk(e,t){return new rk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const ok=W("ZodPipe",(e,t)=>{h9.init(e,t),rt.init(e,t),e.in=t.in,e.out=t.out});function Jl(e,t){return new ok({type:"pipe",in:e,out:t})}const sk=W("ZodReadonly",(e,t)=>{m9.init(e,t),rt.init(e,t)});function ak(e){return new sk({type:"readonly",innerType:e})}const ik=W("ZodLazy",(e,t)=>{g9.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Wl(e){return new ik({type:"lazy",getter:e})}const Gl=W("ZodCustom",(e,t)=>{y9.init(e,t),rt.init(e,t)});function lk(e){const t=new Dt({check:"custom"});return t._zod.check=e,t}function Ah(e,t){return l4(Gl,e??(()=>!0),t)}function ck(e,t={}){return c4(Gl,e,t)}function uk(e){const t=lk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(os(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(os(o))}},e(r.value,r)));return t}function di(e,t={error:`Input not instance of ${e.name}`}){const r=new Gl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...fe(t)});return r._zod.bag.Class=e,r}function Nh(e,t){return Jl(Rh(e),t)}const qh={custom:"custom"};function Lh(e){return V9(Vl,e)}const is="2025-11-25",jh=[is,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mn="io.modelcontextprotocol/related-task",pi="2.0",wt=Ah(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Dh=oe([d(),j().int()]),Uh=d();at({ttl:oe([j(),ui()]).optional(),pollInterval:j().optional()});const dk=C({ttl:j().optional()}),pk=C({taskId:d()}),Kl=at({progressToken:Dh.optional(),[Mn]:pk.optional()}),Jt=C({_meta:Kl.optional()}),ls=Jt.extend({task:dk.optional()}),fk=e=>ls.safeParse(e).success,bt=C({method:d(),params:Jt.loose().optional()}),er=C({_meta:Kl.optional()}),tr=C({method:d(),params:er.loose().optional()}),kt=at({_meta:Kl.optional()}),fi=oe([d(),j().int()]),zh=C({jsonrpc:P(pi),id:fi,...bt.shape}).strict(),Yl=e=>zh.safeParse(e).success,Zh=C({jsonrpc:P(pi),...tr.shape}).strict(),hk=e=>Zh.safeParse(e).success,Ql=C({jsonrpc:P(pi),id:fi,result:kt}).strict(),cs=e=>Ql.safeParse(e).success;var ce;(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"})(ce||(ce={}));const Xl=C({jsonrpc:P(pi),id:fi.optional(),error:C({code:j().int(),message:d(),data:Le().optional()})}).strict(),mk=e=>Xl.safeParse(e).success,Zr=oe([zh,Zh,Ql,Xl]);oe([Ql,Xl]);const ln=kt.strict(),gk=er.extend({requestId:fi.optional(),reason:d().optional()}),ec=tr.extend({method:P("notifications/cancelled"),params:gk}),yk=C({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:Ee(["light","dark"]).optional()}),us=C({icons:q(yk).optional()}),ao=C({name:d(),title:d().optional()}),Fh=ao.extend({...ao.shape,...us.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),vk=Hl(C({applyDefaults:me().optional()}),ge(d(),Le())),_k=Nh(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Hl(C({form:vk.optional(),url:wt.optional()}),ge(d(),Le()).optional())),wk=at({list:wt.optional(),cancel:wt.optional(),requests:at({sampling:at({createMessage:wt.optional()}).optional(),elicitation:at({create:wt.optional()}).optional()}).optional()}),bk=at({list:wt.optional(),cancel:wt.optional(),requests:at({tools:at({call:wt.optional()}).optional()}).optional()}),kk=C({experimental:ge(d(),wt).optional(),sampling:C({context:wt.optional(),tools:wt.optional()}).optional(),elicitation:_k.optional(),roots:C({listChanged:me().optional()}).optional(),tasks:wk.optional()}),Tk=Jt.extend({protocolVersion:d(),capabilities:kk,clientInfo:Fh}),Vh=bt.extend({method:P("initialize"),params:Tk}),Ck=C({experimental:ge(d(),wt).optional(),logging:wt.optional(),completions:wt.optional(),prompts:C({listChanged:me().optional()}).optional(),resources:C({subscribe:me().optional(),listChanged:me().optional()}).optional(),tools:C({listChanged:me().optional()}).optional(),tasks:bk.optional()}),Hh=kt.extend({protocolVersion:d(),capabilities:Ck,serverInfo:Fh,instructions:d().optional()}),tc=tr.extend({method:P("notifications/initialized"),params:er.optional()}),Sk=e=>tc.safeParse(e).success,rc=bt.extend({method:P("ping"),params:Jt.optional()}),Ik=C({progress:j(),total:ue(j()),message:ue(d())}),Ek=C({...er.shape,...Ik.shape,progressToken:Dh}),nc=tr.extend({method:P("notifications/progress"),params:Ek}),xk=Jt.extend({cursor:Uh.optional()}),ds=bt.extend({params:xk.optional()}),ps=kt.extend({nextCursor:Uh.optional()}),$k=Ee(["working","input_required","completed","failed","cancelled"]),fs=C({taskId:d(),status:$k,ttl:oe([j(),ui()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ue(j()),statusMessage:ue(d())}),io=kt.extend({task:fs}),Rk=er.merge(fs),hi=tr.extend({method:P("notifications/tasks/status"),params:Rk}),oc=bt.extend({method:P("tasks/get"),params:Jt.extend({taskId:d()})}),sc=kt.merge(fs),ac=bt.extend({method:P("tasks/result"),params:Jt.extend({taskId:d()})});kt.loose();const ic=ds.extend({method:P("tasks/list")}),lc=ps.extend({tasks:q(fs)}),cc=bt.extend({method:P("tasks/cancel"),params:Jt.extend({taskId:d()})}),Pk=kt.merge(fs),Bh=C({uri:d(),mimeType:ue(d()),_meta:ge(d(),Le()).optional()}),Jh=Bh.extend({text:d()}),uc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wh=Bh.extend({blob:uc}),hs=Ee(["user","assistant"]),lo=C({audience:q(hs).optional(),priority:j().min(0).max(1).optional(),lastModified:wh({offset:!0}).optional()}),Gh=C({...ao.shape,...us.shape,uri:d(),description:ue(d()),mimeType:ue(d()),annotations:lo.optional(),_meta:ue(at({}))}),Mk=C({...ao.shape,...us.shape,uriTemplate:d(),description:ue(d()),mimeType:ue(d()),annotations:lo.optional(),_meta:ue(at({}))}),mi=ds.extend({method:P("resources/list")}),Kh=ps.extend({resources:q(Gh)}),dc=ds.extend({method:P("resources/templates/list")}),Yh=ps.extend({resourceTemplates:q(Mk)}),pc=Jt.extend({uri:d()}),Ok=pc,fc=bt.extend({method:P("resources/read"),params:Ok}),Qh=kt.extend({contents:q(oe([Jh,Wh]))}),hc=tr.extend({method:P("notifications/resources/list_changed"),params:er.optional()}),Ak=pc,Xh=bt.extend({method:P("resources/subscribe"),params:Ak}),Nk=pc,em=bt.extend({method:P("resources/unsubscribe"),params:Nk}),qk=er.extend({uri:d()}),tm=tr.extend({method:P("notifications/resources/updated"),params:qk}),Lk=C({name:d(),description:ue(d()),required:ue(me())}),jk=C({...ao.shape,...us.shape,description:ue(d()),arguments:ue(q(Lk)),_meta:ue(at({}))}),mc=ds.extend({method:P("prompts/list")}),rm=ps.extend({prompts:q(jk)}),Dk=Jt.extend({name:d(),arguments:ge(d(),d()).optional()}),gc=bt.extend({method:P("prompts/get"),params:Dk}),yc=C({type:P("text"),text:d(),annotations:lo.optional(),_meta:ge(d(),Le()).optional()}),vc=C({type:P("image"),data:uc,mimeType:d(),annotations:lo.optional(),_meta:ge(d(),Le()).optional()}),_c=C({type:P("audio"),data:uc,mimeType:d(),annotations:lo.optional(),_meta:ge(d(),Le()).optional()}),Uk=C({type:P("tool_use"),name:d(),id:d(),input:ge(d(),Le()),_meta:ge(d(),Le()).optional()}),zk=C({type:P("resource"),resource:oe([Jh,Wh]),annotations:lo.optional(),_meta:ge(d(),Le()).optional()}),Zk=Gh.extend({type:P("resource_link")}),wc=oe([yc,vc,_c,Zk,zk]),Fk=C({role:hs,content:wc}),nm=kt.extend({description:d().optional(),messages:q(Fk)}),bc=tr.extend({method:P("notifications/prompts/list_changed"),params:er.optional()}),Vk=C({title:d().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),Hk=C({taskSupport:Ee(["required","optional","forbidden"]).optional()}),om=C({...ao.shape,...us.shape,description:d().optional(),inputSchema:C({type:P("object"),properties:ge(d(),wt).optional(),required:q(d()).optional()}).catchall(Le()),outputSchema:C({type:P("object"),properties:ge(d(),wt).optional(),required:q(d()).optional()}).catchall(Le()).optional(),annotations:Vk.optional(),execution:Hk.optional(),_meta:ge(d(),Le()).optional()}),kc=ds.extend({method:P("tools/list")}),sm=ps.extend({tools:q(om)}),co=kt.extend({content:q(wc).default([]),structuredContent:ge(d(),Le()).optional(),isError:me().optional()});co.or(kt.extend({toolResult:Le()}));const Bk=ls.extend({name:d(),arguments:ge(d(),Le()).optional()}),gi=bt.extend({method:P("tools/call"),params:Bk}),Tc=tr.extend({method:P("notifications/tools/list_changed"),params:er.optional()}),Jk=C({autoRefresh:me().default(!0),debounceMs:j().int().nonnegative().default(300)}),yi=Ee(["debug","info","notice","warning","error","critical","alert","emergency"]),Wk=Jt.extend({level:yi}),vi=bt.extend({method:P("logging/setLevel"),params:Wk}),Gk=er.extend({level:yi,logger:d().optional(),data:Le()}),am=tr.extend({method:P("notifications/message"),params:Gk}),Kk=C({name:d().optional()}),Yk=C({hints:q(Kk).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),Qk=C({mode:Ee(["auto","required","none"]).optional()}),Xk=C({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(wc).default([]),structuredContent:C({}).loose().optional(),isError:me().optional(),_meta:ge(d(),Le()).optional()}),eT=tt("type",[yc,vc,_c]),_i=tt("type",[yc,vc,_c,Uk,Xk]),tT=C({role:hs,content:oe([_i,q(_i)]),_meta:ge(d(),Le()).optional()}),rT=ls.extend({messages:q(tT),modelPreferences:Yk.optional(),systemPrompt:d().optional(),includeContext:Ee(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:wt.optional(),tools:q(om).optional(),toolChoice:Qk.optional()}),Cc=bt.extend({method:P("sampling/createMessage"),params:rT}),wi=kt.extend({model:d(),stopReason:ue(Ee(["endTurn","stopSequence","maxTokens"]).or(d())),role:hs,content:eT}),Sc=kt.extend({model:d(),stopReason:ue(Ee(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:hs,content:oe([_i,q(_i)])}),nT=C({type:P("boolean"),title:d().optional(),description:d().optional(),default:me().optional()}),oT=C({type:P("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:Ee(["email","uri","date","date-time"]).optional(),default:d().optional()}),sT=C({type:Ee(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),aT=C({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),iT=C({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(C({const:d(),title:d()})),default:d().optional()}),lT=C({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),cT=oe([aT,iT]),uT=C({type:P("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:C({type:P("string"),enum:q(d())}),default:q(d()).optional()}),dT=C({type:P("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()}),pT=oe([uT,dT]),fT=oe([lT,cT,pT]),hT=oe([fT,nT,oT,sT]),mT=ls.extend({mode:P("form").optional(),message:d(),requestedSchema:C({type:P("object"),properties:ge(d(),hT),required:q(d()).optional()})}),gT=ls.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),yT=oe([mT,gT]),Ic=bt.extend({method:P("elicitation/create"),params:yT}),vT=er.extend({elicitationId:d()}),_T=tr.extend({method:P("notifications/elicitation/complete"),params:vT}),ms=kt.extend({action:Ee(["accept","decline","cancel"]),content:Nh(e=>e===null?void 0:e,ge(d(),oe([d(),j(),me(),q(d())])).optional())}),wT=C({type:P("ref/resource"),uri:d()}),bT=C({type:P("ref/prompt"),name:d()}),kT=Jt.extend({ref:oe([bT,wT]),argument:C({name:d(),value:d()}),context:C({arguments:ge(d(),d()).optional()}).optional()}),Ec=bt.extend({method:P("completion/complete"),params:kT});function TT(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function CT(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const im=kt.extend({completion:at({values:q(d()).max(100),total:ue(j().int()),hasMore:ue(me())})}),ST=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ge(d(),Le()).optional()}),lm=bt.extend({method:P("roots/list"),params:Jt.optional()}),xc=kt.extend({roots:q(ST)}),cm=tr.extend({method:P("notifications/roots/list_changed"),params:er.optional()});oe([rc,Vh,Ec,vi,gc,mc,mi,dc,fc,Xh,em,gi,kc,oc,ac,ic,cc]),oe([ec,nc,tc,cm,hi]),oe([ln,wi,Sc,ms,xc,sc,lc,io]),oe([rc,Cc,Ic,lm,oc,ac,ic,cc]),oe([ec,nc,am,tm,hc,Tc,bc,hi,_T]),oe([ln,Hh,im,nm,rm,Kh,Yh,Qh,co,sm,sc,lc,io]);class ae 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===ce.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new IT(o.elicitations,r)}return new ae(t,r,n)}}class IT extends ae{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ce.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const ET=W("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ye.init(e,t),e.def=t,e.parse=(r,n)=>Ab(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>jl(e,r,n),e.parseAsync=async(r,n)=>Nb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Dl(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)=>sn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),xT=W("ZodMiniObject",(e,t)=>{eh.init(e,t),ET.init(e,t),He(e,"shape",()=>t.shape)});function um(e,t){const r={type:"object",get shape(){return es(this,"shape",{...e}),this.shape},...fe(t)};return new xT(r)}function ur(e){return!!e._zod}function uo(e){const t=Object.values(e);if(t.length===0)return um({});const r=t.every(ur),n=t.every(o=>!ur(o));if(r)return um(e);if(n)return jt(e);throw new Error("Mixed Zod versions detected in object shape.")}function dr(e,t){return ur(e)?jl(e,t):e.safeParse(t)}async function $c(e,t){return ur(e)?await Dl(e,t):await e.safeParseAsync(t)}function po(e){if(!e)return;let t;if(ur(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function gs(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 uo(e)}}if(ur(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 Rc(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 $T(e){return e.description}function RT(e){if(ur(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function dm(e){if(ur(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 On(e){return e==="completed"||e==="failed"||e==="cancelled"}const PT=Symbol("Let zodToJsonSchema decide on which parser to use"),pm={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"},MT=e=>typeof e=="string"?{...pm,name:e}:{...pm,...e},OT=e=>{const t=MT(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 fm(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Ge(e,t,r,n,o){e[t]=r,fm(e,t,n,o)}const hm=(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 Ut(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?hm(t,e.currentPath):t.join("/")}}function AT(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(r.items=Be(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ge(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ge(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ge(r,"minItems",e.exactLength.value,e.exactLength.message,t),Ge(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function NT(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?Ge(r,"minimum",n.value,n.message,t):Ge(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ge(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ge(r,"maximum",n.value,n.message,t):Ge(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ge(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ge(r,"multipleOf",n.value,n.message,t);break}return r}function qT(){return{type:"boolean"}}function mm(e,t){return Be(e.type._def,t)}const LT=(e,t)=>Be(e.innerType._def,t);function gm(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>gm(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 jT(e,t)}}const jT=(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":Ge(r,"minimum",n.value,n.message,t);break;case"max":Ge(r,"maximum",n.value,n.message,t);break}return r};function DT(e,t){return{...Be(e.innerType._def,t),default:e.defaultValue()}}function UT(e,t){return t.effectStrategy==="input"?Be(e.schema._def,t):Ut(t)}function zT(e){return{type:"string",enum:Array.from(e.values)}}const ZT=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function FT(e,t){const r=[Be(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Be(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(ZT(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 VT(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 Pc;const pr={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:()=>(Pc===void 0&&(Pc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Pc),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 ym(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":Ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Ge(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":fr(r,"email",n.message,t);break;case"format:idn-email":fr(r,"idn-email",n.message,t);break;case"pattern:zod":Ot(r,pr.email,n.message,t);break}break;case"url":fr(r,"uri",n.message,t);break;case"uuid":fr(r,"uuid",n.message,t);break;case"regex":Ot(r,n.regex,n.message,t);break;case"cuid":Ot(r,pr.cuid,n.message,t);break;case"cuid2":Ot(r,pr.cuid2,n.message,t);break;case"startsWith":Ot(r,RegExp(`^${Mc(n.value,t)}`),n.message,t);break;case"endsWith":Ot(r,RegExp(`${Mc(n.value,t)}$`),n.message,t);break;case"datetime":fr(r,"date-time",n.message,t);break;case"date":fr(r,"date",n.message,t);break;case"time":fr(r,"time",n.message,t);break;case"duration":fr(r,"duration",n.message,t);break;case"length":Ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Ge(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Ot(r,RegExp(Mc(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&fr(r,"ipv4",n.message,t),n.version!=="v4"&&fr(r,"ipv6",n.message,t);break}case"base64url":Ot(r,pr.base64url,n.message,t);break;case"jwt":Ot(r,pr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ot(r,pr.ipv4Cidr,n.message,t),n.version!=="v4"&&Ot(r,pr.ipv6Cidr,n.message,t);break}case"emoji":Ot(r,pr.emoji(),n.message,t);break;case"ulid":{Ot(r,pr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{fr(r,"binary",n.message,t);break}case"contentEncoding:base64":{Ge(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ot(r,pr.base64,n.message,t);break}}break}case"nanoid":Ot(r,pr.nanoid,n.message,t)}return r}function Mc(e,t){return t.patternStrategy==="escape"?BT(e):e}const HT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function BT(e){let t="";for(let r=0;r<e.length;r++)HT.has(e[r])||(t+="\\"),t+=e[r];return t}function fr(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}}})):Ge(e,"format",t,r,n)}function Ot(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:vm(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ge(e,"pattern",vm(t,n),r,n)}function vm(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
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 qh(e,t){if(e instanceof Ih){const n=new Ah(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 Ah(t);return r.process(e),r.emit(e,t)}function wt(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 wt(o.element,r);case"object":{for(const s in o.shape)if(wt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(wt(s,r))return!0;return!1}case"intersection":return wt(o.left,r)||wt(o.right,r);case"tuple":{for(const s of o.items)if(wt(s,r))return!0;return!!(o.rest&&wt(o.rest,r))}case"record":return wt(o.keyType,r)||wt(o.valueType,r);case"map":return wt(o.keyType,r)||wt(o.valueType,r);case"set":return wt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return wt(o.innerType,r);case"lazy":return wt(o.getter(),r);case"default":return wt(o.innerType,r);case"prefault":return wt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return wt(o.in,r)||wt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const $4=W("ZodISODateTime",(e,t)=>{e9.init(e,t),lt.init(e,t)});function Lh(e){return o4($4,e)}const R4=W("ZodISODate",(e,t)=>{t9.init(e,t),lt.init(e,t)});function P4(e){return s4(R4,e)}const M4=W("ZodISOTime",(e,t)=>{r9.init(e,t),lt.init(e,t)});function O4(e){return a4(M4,e)}const N4=W("ZodISODuration",(e,t)=>{n9.init(e,t),lt.init(e,t)});function A4(e){return i4(N4,e)}const bi=W("ZodError",(e,t)=>{th.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Qb(e,r)},flatten:{value:r=>Yb(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}),q4=rh(bi),L4=nh(bi),j4=oh(bi),jh=sh(bi),Xe=W("ZodType",(e,t)=>(Ge.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)=>yn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>q4(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>j4(e,r,n),e.parseAsync=async(r,n)=>L4(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>jh(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Ek(r,n)),e.superRefine=r=>e.check($k(r)),e.overwrite=r=>e.check(gs(r)),e.optional=()=>de(e),e.nullable=()=>Gh(e),e.nullish=()=>de(Gh(e)),e.nonoptional=r=>wk(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>cc(e,r),e.transform=r=>dc(e,Jh(r)),e.default=r=>yk(e,r),e.prefault=r=>_k(e,r),e.catch=r=>kk(e,r),e.pipe=r=>dc(e,r),e.readonly=()=>Sk(e),e.describe=r=>{const n=e.clone();return ms.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ms.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ms.get(e);const n=e.clone();return ms.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Dh=W("_ZodString",(e,t)=>{oc.init(e,t),Xe.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(g4(...n)),e.includes=(...n)=>e.check(_4(...n)),e.startsWith=(...n)=>e.check(w4(...n)),e.endsWith=(...n)=>e.check(b4(...n)),e.min=(...n)=>e.check(wi(...n)),e.max=(...n)=>e.check(Oh(...n)),e.length=(...n)=>e.check(Nh(...n)),e.nonempty=(...n)=>e.check(wi(1,...n)),e.lowercase=n=>e.check(y4(n)),e.uppercase=n=>e.check(v4(n)),e.trim=()=>e.check(T4()),e.normalize=(...n)=>e.check(k4(...n)),e.toLowerCase=()=>e.check(C4()),e.toUpperCase=()=>e.check(S4())}),D4=W("ZodString",(e,t)=>{oc.init(e,t),Dh.init(e,t),e.email=r=>e.check(D9(U4,r)),e.url=r=>e.check(Eh(zh,r)),e.jwt=r=>e.check(n4(tk,r)),e.emoji=r=>e.check(V9(Z4,r)),e.guid=r=>e.check(xh(Uh,r)),e.uuid=r=>e.check(U9(ki,r)),e.uuidv4=r=>e.check(z9(ki,r)),e.uuidv6=r=>e.check(Z9(ki,r)),e.uuidv7=r=>e.check(F9(ki,r)),e.nanoid=r=>e.check(H9(F4,r)),e.guid=r=>e.check(xh(Uh,r)),e.cuid=r=>e.check(B9(V4,r)),e.cuid2=r=>e.check(J9(H4,r)),e.ulid=r=>e.check(W9(B4,r)),e.base64=r=>e.check($h(Zh,r)),e.base64url=r=>e.check(t4(X4,r)),e.xid=r=>e.check(G9(J4,r)),e.ksuid=r=>e.check(K9(W4,r)),e.ipv4=r=>e.check(Y9(G4,r)),e.ipv6=r=>e.check(Q9(K4,r)),e.cidrv4=r=>e.check(X9(Y4,r)),e.cidrv6=r=>e.check(e4(Q4,r)),e.e164=r=>e.check(r4(ek,r)),e.datetime=r=>e.check(Lh(r)),e.date=r=>e.check(P4(r)),e.time=r=>e.check(O4(r)),e.duration=r=>e.check(A4(r))});function d(e){return j9(D4,e)}const lt=W("ZodStringFormat",(e,t)=>{nt.init(e,t),Dh.init(e,t)}),U4=W("ZodEmail",(e,t)=>{H3.init(e,t),lt.init(e,t)}),Uh=W("ZodGUID",(e,t)=>{F3.init(e,t),lt.init(e,t)}),ki=W("ZodUUID",(e,t)=>{V3.init(e,t),lt.init(e,t)}),zh=W("ZodURL",(e,t)=>{B3.init(e,t),lt.init(e,t)});function z4(e){return Eh(zh,e)}const Z4=W("ZodEmoji",(e,t)=>{J3.init(e,t),lt.init(e,t)}),F4=W("ZodNanoID",(e,t)=>{W3.init(e,t),lt.init(e,t)}),V4=W("ZodCUID",(e,t)=>{G3.init(e,t),lt.init(e,t)}),H4=W("ZodCUID2",(e,t)=>{K3.init(e,t),lt.init(e,t)}),B4=W("ZodULID",(e,t)=>{Y3.init(e,t),lt.init(e,t)}),J4=W("ZodXID",(e,t)=>{Q3.init(e,t),lt.init(e,t)}),W4=W("ZodKSUID",(e,t)=>{X3.init(e,t),lt.init(e,t)}),G4=W("ZodIPv4",(e,t)=>{o9.init(e,t),lt.init(e,t)}),K4=W("ZodIPv6",(e,t)=>{s9.init(e,t),lt.init(e,t)}),Y4=W("ZodCIDRv4",(e,t)=>{a9.init(e,t),lt.init(e,t)}),Q4=W("ZodCIDRv6",(e,t)=>{i9.init(e,t),lt.init(e,t)}),Zh=W("ZodBase64",(e,t)=>{l9.init(e,t),lt.init(e,t)});function Fh(e){return $h(Zh,e)}const X4=W("ZodBase64URL",(e,t)=>{u9.init(e,t),lt.init(e,t)}),ek=W("ZodE164",(e,t)=>{d9.init(e,t),lt.init(e,t)}),tk=W("ZodJWT",(e,t)=>{f9.init(e,t),lt.init(e,t)}),lc=W("ZodNumber",(e,t)=>{hh.init(e,t),Xe.init(e,t),e.gt=(n,o)=>e.check(Ph(n,o)),e.gte=(n,o)=>e.check(ic(n,o)),e.min=(n,o)=>e.check(ic(n,o)),e.lt=(n,o)=>e.check(Rh(n,o)),e.lte=(n,o)=>e.check(ac(n,o)),e.max=(n,o)=>e.check(ac(n,o)),e.int=n=>e.check(Vh(n)),e.safe=n=>e.check(Vh(n)),e.positive=n=>e.check(Ph(0,n)),e.nonnegative=n=>e.check(ic(0,n)),e.negative=n=>e.check(Rh(0,n)),e.nonpositive=n=>e.check(ac(0,n)),e.multipleOf=(n,o)=>e.check(Mh(n,o)),e.step=(n,o)=>e.check(Mh(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 l4(lc,e)}const rk=W("ZodNumberFormat",(e,t)=>{h9.init(e,t),lc.init(e,t)});function Vh(e){return u4(rk,e)}const nk=W("ZodBoolean",(e,t)=>{m9.init(e,t),Xe.init(e,t)});function he(e){return d4(nk,e)}const ok=W("ZodNull",(e,t)=>{g9.init(e,t),Xe.init(e,t)});function Ti(e){return p4(ok,e)}const sk=W("ZodAny",(e,t)=>{y9.init(e,t),Xe.init(e,t)});function kt(){return f4(sk)}const ak=W("ZodUnknown",(e,t)=>{v9.init(e,t),Xe.init(e,t)});function Me(){return h4(ak)}const ik=W("ZodNever",(e,t)=>{_9.init(e,t),Xe.init(e,t)});function lk(e){return m4(ik,e)}const ck=W("ZodArray",(e,t)=>{w9.init(e,t),Xe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(wi(r,n)),e.nonempty=r=>e.check(wi(1,r)),e.max=(r,n)=>e.check(Oh(r,n)),e.length=(r,n)=>e.check(Nh(r,n)),e.unwrap=()=>e.element});function q(e,t){return I4(ck,e,t)}const Hh=W("ZodObject",(e,t)=>{yh.init(e,t),Xe.init(e,t),Ve(e,"shape",()=>t.shape),e.keyof=()=>me(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:lk()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Jb(e,r),e.merge=r=>Wb(e,r),e.pick=r=>Hb(e,r),e.omit=r=>Bb(e,r),e.partial=(...r)=>Gb(Wh,e,r[0]),e.required=(...r)=>Kb(Kh,e,r[0])});function T(e,t){const r={type:"object",get shape(){return us(this,"shape",{...e}),this.shape},...pe(t)};return new Hh(r)}function ct(e,t){return new Hh({type:"object",get shape(){return us(this,"shape",{...e}),this.shape},catchall:Me(),...pe(t)})}const Bh=W("ZodUnion",(e,t)=>{_h.init(e,t),Xe.init(e,t),e.options=t.options});function oe(e,t){return new Bh({type:"union",options:e,...pe(t)})}const uk=W("ZodDiscriminatedUnion",(e,t)=>{Bh.init(e,t),b9.init(e,t)});function ze(e,t,r){return new uk({type:"union",options:t,discriminator:e,...pe(r)})}const dk=W("ZodIntersection",(e,t)=>{k9.init(e,t),Xe.init(e,t)});function cc(e,t){return new dk({type:"intersection",left:e,right:t})}const pk=W("ZodRecord",(e,t)=>{T9.init(e,t),Xe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ye(e,t,r){return new pk({type:"record",keyType:e,valueType:t,...pe(r)})}const uc=W("ZodEnum",(e,t)=>{C9.init(e,t),Xe.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 uc({...t,checks:[],...pe(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 uc({...t,checks:[],...pe(o),entries:s})}});function me(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new uc({type:"enum",entries:r,...pe(t)})}const fk=W("ZodLiteral",(e,t)=>{S9.init(e,t),Xe.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 R(e,t){return new fk({type:"literal",values:Array.isArray(e)?e:[e],...pe(t)})}const hk=W("ZodTransform",(e,t)=>{I9.init(e,t),Xe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(hs(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(hs(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Jh(e){return new hk({type:"transform",transform:e})}const Wh=W("ZodOptional",(e,t)=>{x9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function de(e){return new Wh({type:"optional",innerType:e})}const mk=W("ZodNullable",(e,t)=>{E9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gh(e){return new mk({type:"nullable",innerType:e})}const gk=W("ZodDefault",(e,t)=>{$9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function yk(e,t){return new gk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const vk=W("ZodPrefault",(e,t)=>{R9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _k(e,t){return new vk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Kh=W("ZodNonOptional",(e,t)=>{P9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wk(e,t){return new Kh({type:"nonoptional",innerType:e,...pe(t)})}const bk=W("ZodCatch",(e,t)=>{M9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function kk(e,t){return new bk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Tk=W("ZodPipe",(e,t)=>{O9.init(e,t),Xe.init(e,t),e.in=t.in,e.out=t.out});function dc(e,t){return new Tk({type:"pipe",in:e,out:t})}const Ck=W("ZodReadonly",(e,t)=>{N9.init(e,t),Xe.init(e,t)});function Sk(e){return new Ck({type:"readonly",innerType:e})}const Ik=W("ZodLazy",(e,t)=>{A9.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function pc(e){return new Ik({type:"lazy",getter:e})}const fc=W("ZodCustom",(e,t)=>{q9.init(e,t),Xe.init(e,t)});function xk(e){const t=new Ht({check:"custom"});return t._zod.check=e,t}function Yh(e,t){return x4(fc,e??(()=>!0),t)}function Ek(e,t={}){return E4(fc,e,t)}function $k(e){const t=xk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(hs(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(hs(o))}},e(r.value,r)));return t}function Ci(e,t={error:`Input not instance of ${e.name}`}){const r=new fc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...pe(t)});return r._zod.bag.Class=e,r}function Qh(e,t){return dc(Jh(e),t)}const Xh={custom:"custom"};function em(e){return c4(lc,e)}const ys="2025-11-25",tm=[ys,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zn="io.modelcontextprotocol/related-task",Si="2.0",Et=Yh(e=>e!==null&&(typeof e=="object"||typeof e=="function")),rm=oe([d(),j().int()]),nm=d();ct({ttl:oe([j(),Ti()]).optional(),pollInterval:j().optional()});const Rk=T({ttl:j().optional()}),Pk=T({taskId:d()}),hc=ct({progressToken:rm.optional(),[Zn]:Pk.optional()}),Xt=T({_meta:hc.optional()}),vs=Xt.extend({task:Rk.optional()}),Mk=e=>vs.safeParse(e).success,$t=T({method:d(),params:Xt.loose().optional()}),ar=T({_meta:hc.optional()}),ir=T({method:d(),params:ar.loose().optional()}),Rt=ct({_meta:hc.optional()}),Ii=oe([d(),j().int()]),om=T({jsonrpc:R(Si),id:Ii,...$t.shape}).strict(),mc=e=>om.safeParse(e).success,sm=T({jsonrpc:R(Si),...ir.shape}).strict(),Ok=e=>sm.safeParse(e).success,gc=T({jsonrpc:R(Si),id:Ii,result:Rt}).strict(),_s=e=>gc.safeParse(e).success;var ue;(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"})(ue||(ue={}));const yc=T({jsonrpc:R(Si),id:Ii.optional(),error:T({code:j().int(),message:d(),data:Me().optional()})}).strict(),Nk=e=>yc.safeParse(e).success,Qr=oe([om,sm,gc,yc]);oe([gc,yc]);const _n=Rt.strict(),Ak=ar.extend({requestId:Ii.optional(),reason:d().optional()}),vc=ir.extend({method:R("notifications/cancelled"),params:Ak}),qk=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:me(["light","dark"]).optional()}),ws=T({icons:q(qk).optional()}),mo=T({name:d(),title:d().optional()}),am=mo.extend({...mo.shape,...ws.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),Lk=cc(T({applyDefaults:he().optional()}),ye(d(),Me())),jk=Qh(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,cc(T({form:Lk.optional(),url:Et.optional()}),ye(d(),Me()).optional())),Dk=ct({list:Et.optional(),cancel:Et.optional(),requests:ct({sampling:ct({createMessage:Et.optional()}).optional(),elicitation:ct({create:Et.optional()}).optional()}).optional()}),Uk=ct({list:Et.optional(),cancel:Et.optional(),requests:ct({tools:ct({call:Et.optional()}).optional()}).optional()}),zk=T({experimental:ye(d(),Et).optional(),sampling:T({context:Et.optional(),tools:Et.optional()}).optional(),elicitation:jk.optional(),roots:T({listChanged:he().optional()}).optional(),tasks:Dk.optional()}),Zk=Xt.extend({protocolVersion:d(),capabilities:zk,clientInfo:am}),im=$t.extend({method:R("initialize"),params:Zk}),Fk=T({experimental:ye(d(),Et).optional(),logging:Et.optional(),completions:Et.optional(),prompts:T({listChanged:he().optional()}).optional(),resources:T({subscribe:he().optional(),listChanged:he().optional()}).optional(),tools:T({listChanged:he().optional()}).optional(),tasks:Uk.optional()}),lm=Rt.extend({protocolVersion:d(),capabilities:Fk,serverInfo:am,instructions:d().optional()}),_c=ir.extend({method:R("notifications/initialized"),params:ar.optional()}),Vk=e=>_c.safeParse(e).success,wc=$t.extend({method:R("ping"),params:Xt.optional()}),Hk=T({progress:j(),total:de(j()),message:de(d())}),Bk=T({...ar.shape,...Hk.shape,progressToken:rm}),bc=ir.extend({method:R("notifications/progress"),params:Bk}),Jk=Xt.extend({cursor:nm.optional()}),bs=$t.extend({params:Jk.optional()}),ks=Rt.extend({nextCursor:nm.optional()}),Wk=me(["working","input_required","completed","failed","cancelled"]),Ts=T({taskId:d(),status:Wk,ttl:oe([j(),Ti()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:de(j()),statusMessage:de(d())}),go=Rt.extend({task:Ts}),Gk=ar.merge(Ts),xi=ir.extend({method:R("notifications/tasks/status"),params:Gk}),kc=$t.extend({method:R("tasks/get"),params:Xt.extend({taskId:d()})}),Tc=Rt.merge(Ts),Cc=$t.extend({method:R("tasks/result"),params:Xt.extend({taskId:d()})});Rt.loose();const Sc=bs.extend({method:R("tasks/list")}),Ic=ks.extend({tasks:q(Ts)}),xc=$t.extend({method:R("tasks/cancel"),params:Xt.extend({taskId:d()})}),Kk=Rt.merge(Ts),cm=T({uri:d(),mimeType:de(d()),_meta:ye(d(),Me()).optional()}),um=cm.extend({text:d()}),Ec=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),dm=cm.extend({blob:Ec}),Cs=me(["user","assistant"]),yo=T({audience:q(Cs).optional(),priority:j().min(0).max(1).optional(),lastModified:Lh({offset:!0}).optional()}),pm=T({...mo.shape,...ws.shape,uri:d(),description:de(d()),mimeType:de(d()),annotations:yo.optional(),_meta:de(ct({}))}),Yk=T({...mo.shape,...ws.shape,uriTemplate:d(),description:de(d()),mimeType:de(d()),annotations:yo.optional(),_meta:de(ct({}))}),Ei=bs.extend({method:R("resources/list")}),fm=ks.extend({resources:q(pm)}),$c=bs.extend({method:R("resources/templates/list")}),hm=ks.extend({resourceTemplates:q(Yk)}),Rc=Xt.extend({uri:d()}),Qk=Rc,Pc=$t.extend({method:R("resources/read"),params:Qk}),mm=Rt.extend({contents:q(oe([um,dm]))}),Mc=ir.extend({method:R("notifications/resources/list_changed"),params:ar.optional()}),Xk=Rc,gm=$t.extend({method:R("resources/subscribe"),params:Xk}),eT=Rc,ym=$t.extend({method:R("resources/unsubscribe"),params:eT}),tT=ar.extend({uri:d()}),vm=ir.extend({method:R("notifications/resources/updated"),params:tT}),rT=T({name:d(),description:de(d()),required:de(he())}),nT=T({...mo.shape,...ws.shape,description:de(d()),arguments:de(q(rT)),_meta:de(ct({}))}),Oc=bs.extend({method:R("prompts/list")}),_m=ks.extend({prompts:q(nT)}),oT=Xt.extend({name:d(),arguments:ye(d(),d()).optional()}),Nc=$t.extend({method:R("prompts/get"),params:oT}),Ac=T({type:R("text"),text:d(),annotations:yo.optional(),_meta:ye(d(),Me()).optional()}),qc=T({type:R("image"),data:Ec,mimeType:d(),annotations:yo.optional(),_meta:ye(d(),Me()).optional()}),Lc=T({type:R("audio"),data:Ec,mimeType:d(),annotations:yo.optional(),_meta:ye(d(),Me()).optional()}),sT=T({type:R("tool_use"),name:d(),id:d(),input:ye(d(),Me()),_meta:ye(d(),Me()).optional()}),aT=T({type:R("resource"),resource:oe([um,dm]),annotations:yo.optional(),_meta:ye(d(),Me()).optional()}),iT=pm.extend({type:R("resource_link")}),jc=oe([Ac,qc,Lc,iT,aT]),lT=T({role:Cs,content:jc}),wm=Rt.extend({description:d().optional(),messages:q(lT)}),Dc=ir.extend({method:R("notifications/prompts/list_changed"),params:ar.optional()}),cT=T({title:d().optional(),readOnlyHint:he().optional(),destructiveHint:he().optional(),idempotentHint:he().optional(),openWorldHint:he().optional()}),uT=T({taskSupport:me(["required","optional","forbidden"]).optional()}),bm=T({...mo.shape,...ws.shape,description:d().optional(),inputSchema:T({type:R("object"),properties:ye(d(),Et).optional(),required:q(d()).optional()}).catchall(Me()),outputSchema:T({type:R("object"),properties:ye(d(),Et).optional(),required:q(d()).optional()}).catchall(Me()).optional(),annotations:cT.optional(),execution:uT.optional(),_meta:ye(d(),Me()).optional()}),Uc=bs.extend({method:R("tools/list")}),km=ks.extend({tools:q(bm)}),vo=Rt.extend({content:q(jc).default([]),structuredContent:ye(d(),Me()).optional(),isError:he().optional()});vo.or(Rt.extend({toolResult:Me()}));const dT=vs.extend({name:d(),arguments:ye(d(),Me()).optional()}),$i=$t.extend({method:R("tools/call"),params:dT}),zc=ir.extend({method:R("notifications/tools/list_changed"),params:ar.optional()}),pT=T({autoRefresh:he().default(!0),debounceMs:j().int().nonnegative().default(300)}),Ri=me(["debug","info","notice","warning","error","critical","alert","emergency"]),fT=Xt.extend({level:Ri}),Pi=$t.extend({method:R("logging/setLevel"),params:fT}),hT=ar.extend({level:Ri,logger:d().optional(),data:Me()}),Tm=ir.extend({method:R("notifications/message"),params:hT}),mT=T({name:d().optional()}),gT=T({hints:q(mT).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),yT=T({mode:me(["auto","required","none"]).optional()}),vT=T({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(jc).default([]),structuredContent:T({}).loose().optional(),isError:he().optional(),_meta:ye(d(),Me()).optional()}),_T=ze("type",[Ac,qc,Lc]),Mi=ze("type",[Ac,qc,Lc,sT,vT]),wT=T({role:Cs,content:oe([Mi,q(Mi)]),_meta:ye(d(),Me()).optional()}),bT=vs.extend({messages:q(wT),modelPreferences:gT.optional(),systemPrompt:d().optional(),includeContext:me(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:Et.optional(),tools:q(bm).optional(),toolChoice:yT.optional()}),Zc=$t.extend({method:R("sampling/createMessage"),params:bT}),Oi=Rt.extend({model:d(),stopReason:de(me(["endTurn","stopSequence","maxTokens"]).or(d())),role:Cs,content:_T}),Fc=Rt.extend({model:d(),stopReason:de(me(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Cs,content:oe([Mi,q(Mi)])}),kT=T({type:R("boolean"),title:d().optional(),description:d().optional(),default:he().optional()}),TT=T({type:R("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:me(["email","uri","date","date-time"]).optional(),default:d().optional()}),CT=T({type:me(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),ST=T({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),IT=T({type:R("string"),title:d().optional(),description:d().optional(),oneOf:q(T({const:d(),title:d()})),default:d().optional()}),xT=T({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),ET=oe([ST,IT]),$T=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({type:R("string"),enum:q(d())}),default:q(d()).optional()}),RT=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),PT=oe([$T,RT]),MT=oe([xT,ET,PT]),OT=oe([MT,kT,TT,CT]),NT=vs.extend({mode:R("form").optional(),message:d(),requestedSchema:T({type:R("object"),properties:ye(d(),OT),required:q(d()).optional()})}),AT=vs.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),qT=oe([NT,AT]),Vc=$t.extend({method:R("elicitation/create"),params:qT}),LT=ar.extend({elicitationId:d()}),jT=ir.extend({method:R("notifications/elicitation/complete"),params:LT}),Ss=Rt.extend({action:me(["accept","decline","cancel"]),content:Qh(e=>e===null?void 0:e,ye(d(),oe([d(),j(),he(),q(d())])).optional())}),DT=T({type:R("ref/resource"),uri:d()}),UT=T({type:R("ref/prompt"),name:d()}),zT=Xt.extend({ref:oe([UT,DT]),argument:T({name:d(),value:d()}),context:T({arguments:ye(d(),d()).optional()}).optional()}),Hc=$t.extend({method:R("completion/complete"),params:zT});function ZT(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function FT(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Cm=Rt.extend({completion:ct({values:q(d()).max(100),total:de(j().int()),hasMore:de(he())})}),VT=T({uri:d().startsWith("file://"),name:d().optional(),_meta:ye(d(),Me()).optional()}),Sm=$t.extend({method:R("roots/list"),params:Xt.optional()}),Bc=Rt.extend({roots:q(VT)}),Im=ir.extend({method:R("notifications/roots/list_changed"),params:ar.optional()});oe([wc,im,Hc,Pi,Nc,Oc,Ei,$c,Pc,gm,ym,$i,Uc,kc,Cc,Sc,xc]),oe([vc,bc,_c,Im,xi]),oe([_n,Oi,Fc,Ss,Bc,Tc,Ic,go]),oe([wc,Zc,Vc,Sm,kc,Cc,Sc,xc]),oe([vc,bc,Tm,vm,Mc,zc,Dc,xi,jT]),oe([_n,lm,Cm,wm,_m,fm,hm,mm,vo,km,Tc,Ic,go]);class ae 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===ue.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new HT(o.elicitations,r)}return new ae(t,r,n)}}class HT extends ae{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ue.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const BT=W("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ge.init(e,t),e.def=t,e.parse=(r,n)=>Xb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>rc(e,r,n),e.parseAsync=async(r,n)=>e3(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>nc(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)=>yn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),JT=W("ZodMiniObject",(e,t)=>{yh.init(e,t),BT.init(e,t),Ve(e,"shape",()=>t.shape)});function xm(e,t){const r={type:"object",get shape(){return us(this,"shape",{...e}),this.shape},...pe(t)};return new JT(r)}function vr(e){return!!e._zod}function _o(e){const t=Object.values(e);if(t.length===0)return xm({});const r=t.every(vr),n=t.every(o=>!vr(o));if(r)return xm(e);if(n)return Vt(e);throw new Error("Mixed Zod versions detected in object shape.")}function _r(e,t){return vr(e)?rc(e,t):e.safeParse(t)}async function Jc(e,t){return vr(e)?await nc(e,t):await e.safeParseAsync(t)}function wo(e){if(!e)return;let t;if(vr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Is(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 _o(e)}}if(vr(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 Wc(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 WT(e){return e.description}function GT(e){if(vr(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(vr(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 Fn(e){return e==="completed"||e==="failed"||e==="cancelled"}const KT=Symbol("Let zodToJsonSchema decide on which parser to use"),$m={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"},YT=e=>typeof e=="string"?{...$m,name:e}:{...$m,...e},QT=e=>{const t=YT(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 Rm(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Je(e,t,r,n,o){e[t]=r,Rm(e,t,n,o)}const Pm=(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 Bt(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Pm(t,e.currentPath):t.join("/")}}function XT(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==J.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 eC(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 tC(){return{type:"boolean"}}function Mm(e,t){return He(e.type._def,t)}const rC=(e,t)=>He(e.innerType._def,t);function Om(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Om(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 nC(e,t)}}const nC=(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 oC(e,t){return{...He(e.innerType._def,t),default:e.defaultValue()}}function sC(e,t){return t.effectStrategy==="input"?He(e.schema._def,t):Bt(t)}function aC(e){return{type:"string",enum:Array.from(e.values)}}const iC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function lC(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(iC(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 cC(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 Gc;const wr={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:()=>(Gc===void 0&&(Gc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Gc),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 Nm(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":br(r,"email",n.message,t);break;case"format:idn-email":br(r,"idn-email",n.message,t);break;case"pattern:zod":Ut(r,wr.email,n.message,t);break}break;case"url":br(r,"uri",n.message,t);break;case"uuid":br(r,"uuid",n.message,t);break;case"regex":Ut(r,n.regex,n.message,t);break;case"cuid":Ut(r,wr.cuid,n.message,t);break;case"cuid2":Ut(r,wr.cuid2,n.message,t);break;case"startsWith":Ut(r,RegExp(`^${Kc(n.value,t)}`),n.message,t);break;case"endsWith":Ut(r,RegExp(`${Kc(n.value,t)}$`),n.message,t);break;case"datetime":br(r,"date-time",n.message,t);break;case"date":br(r,"date",n.message,t);break;case"time":br(r,"time",n.message,t);break;case"duration":br(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":{Ut(r,RegExp(Kc(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&br(r,"ipv4",n.message,t),n.version!=="v4"&&br(r,"ipv6",n.message,t);break}case"base64url":Ut(r,wr.base64url,n.message,t);break;case"jwt":Ut(r,wr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ut(r,wr.ipv4Cidr,n.message,t),n.version!=="v4"&&Ut(r,wr.ipv6Cidr,n.message,t);break}case"emoji":Ut(r,wr.emoji(),n.message,t);break;case"ulid":{Ut(r,wr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{br(r,"binary",n.message,t);break}case"contentEncoding:base64":{Je(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ut(r,wr.base64,n.message,t);break}}break}case"nanoid":Ut(r,wr.nanoid,n.message,t)}return r}function Kc(e,t){return t.patternStrategy==="escape"?dC(e):e}const uC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function dC(e){let t="";for(let r=0;r<e.length;r++)uC.has(e[r])||(t+="\\"),t+=e[r];return t}function br(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 Ut(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:Am(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Je(e,"pattern",Am(t,n),r,n)}function Am(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
36
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
37
37
  ]))`;continue}}if(r.s&&n[l]==="."){o+=a?`${n[l]}\r
38
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 _m(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]:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ut(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Be(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}=ym(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}=mm(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function JT(e,t){if(t.mapStrategy==="record")return _m(e,t);const r=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ut(t),n=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ut(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function WT(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 GT(e){return e.target==="openAi"?void 0:{not:Ut({...e,currentPath:[...e.currentPath,"not"]})}}function KT(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const bi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function YT(e,t){if(t.target==="openApi3")return wm(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in bi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=bi[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 wm(e,t)}const wm=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Be(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 QT(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:bi[e.innerType._def.typeName],nullable:!0}:{type:[bi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function XT(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",fm(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Ge(r,"minimum",n.value,n.message,t):Ge(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ge(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ge(r,"maximum",n.value,n.message,t):Ge(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ge(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ge(r,"multipleOf",n.value,n.message,t);break}return r}function eC(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=rC(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Be(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=tC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function tC(e,t){if(e.catchall._def.typeName!=="ZodNever")return Be(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 rC(e){try{return e.isOptional()}catch{return!0}}const nC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Be(e.innerType._def,t);const r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ut(t)},r]}:Ut(t)},oC=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);if(t.pipeStrategy==="output")return Be(e.out._def,t);const r=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function sC(e,t){return Be(e.type._def,t)}function aC(e,t){const n={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ge(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ge(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function iC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function lC(e){return{not:Ut(e)}}function cC(e){return Ut(e)}const uC=(e,t)=>Be(e.innerType._def,t),dC=(e,t,r)=>{switch(t){case B.ZodString:return ym(e,r);case B.ZodNumber:return XT(e,r);case B.ZodObject:return eC(e,r);case B.ZodBigInt:return NT(e,r);case B.ZodBoolean:return qT();case B.ZodDate:return gm(e,r);case B.ZodUndefined:return lC(r);case B.ZodNull:return KT(r);case B.ZodArray:return AT(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return YT(e,r);case B.ZodIntersection:return FT(e,r);case B.ZodTuple:return iC(e,r);case B.ZodRecord:return _m(e,r);case B.ZodLiteral:return VT(e,r);case B.ZodEnum:return zT(e);case B.ZodNativeEnum:return WT(e);case B.ZodNullable:return QT(e,r);case B.ZodOptional:return nC(e,r);case B.ZodMap:return JT(e,r);case B.ZodSet:return aC(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return sC(e,r);case B.ZodNaN:case B.ZodNever:return GT(r);case B.ZodEffects:return UT(e,r);case B.ZodAny:return Ut(r);case B.ZodUnknown:return cC(r);case B.ZodDefault:return DT(e,r);case B.ZodBranded:return mm(e,r);case B.ZodReadonly:return uC(e,r);case B.ZodCatch:return LT(e,r);case B.ZodPipeline:return oC(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}};function Be(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==PT)return i}if(n&&!r){const i=pC(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=dC(e,e.typeName,t),a=typeof s=="function"?Be(s(),t):s;if(a&&fC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const pC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:hm(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`),Ut(t)):t.$refStrategy==="seen"?Ut(t):void 0}},fC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),hC=(e,t)=>{const r=OT(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:Be(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ut(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Be(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ut(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 bm(e,t){return ur(e)?_h(e,{target:mC(t?.target),io:t?.pipeStrategy??"input"}):hC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function km(e){const r=po(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=dm(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Tm(e,t){const r=dr(e,t);if(!r.success)throw r.error;return r.data}const gC=6e4;class Cm{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(ec,r=>{this._oncancel(r)}),this.setNotificationHandler(nc,r=>{this._onprogress(r)}),this.setRequestHandler(rc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(oc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ae(ce.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ac,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 f=l,p=new ae(f.error.code,f.error.message,f.error.data);u(p)}else{const f=i.type==="response"?"Response":"Error";this._onerror(new Error(`${f} 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 ae(ce.InvalidParams,`Task not found: ${s}`);if(!On(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(On(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[Mn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ic,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 ae(ce.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(cc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ae(ce.InvalidParams,`Task not found: ${r.params.taskId}`);if(On(o.status))throw new ae(ce.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 ae(ce.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ae?o:new ae(ce.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),ae.fromError(ce.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),cs(s)||mk(s)?this._onresponse(s):Yl(s)?this._onrequest(s,a):hk(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=ae.fromError(ce.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?.[Mn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:ce.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(u).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=fk(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 f={relatedRequestId:t.id};s&&(f.relatedTask={taskId:s}),await this.notification(u,f)},sendRequest:async(u,f,p)=>{const h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});const y=h.relatedTask?.taskId??s;return y&&l&&await l.updateTaskStatus(y,"input_required"),await this.request(u,f,h)},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 f={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async u=>{if(a.signal.aborted)return;const f={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:ce.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).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),cs(t))n(t);else{const a=new ae(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(cs(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),cs(t))o(t);else{const a=ae.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 ae?a:new ae(ce.InternalError,String(a))}}return}let s;try{const a=await this.request(t,io,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ae(ce.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},On(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ae(ce.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ae(ce.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 ae?a:new ae(ce.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 f=v=>{u(v)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(v){f(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(h.params={...h.params,task:i}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Mn]:l}});const y=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(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const m=v instanceof ae?v:new ae(ce.RequestTimeout,String(v));u(m)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const m=dr(r,v.result);m.success?c(m.data):u(m.error)}catch(m){u(m)}}}),n?.signal?.addEventListener("abort",()=>{y(n?.signal?.reason)});const w=n?.timeout??gC,g=()=>y(ae.fromError(ce.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(p,w,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);const b=l?.taskId;if(b){const v=m=>{const T=this._responseHandlers.get(p);T?T(m):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(b,{type:"request",message:h,timestamp:Date.now()}).catch(m=>{this._cleanupTimeout(p),u(m)})}else this._transport.send(h,{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},sc,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},lc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Pk,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||{},[Mn]: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||{},[Mn]: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||{},[Mn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=km(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Tm(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=km(t);this._notificationHandlers.set(n,o=>{const s=Tm(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"&&Yl(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ae(ce.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 ae(ce.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ae(ce.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 ae(ce.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=hi.parse({method:"notifications/tasks/status",params:i});await this.notification(l),On(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 ae(ce.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(On(i.status))throw new ae(ce.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=hi.parse({method:"notifications/tasks/status",params:l});await this.notification(c),On(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function Sm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Im(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];Sm(a)&&Sm(s)?r[o]={...a,...s}:r[o]=s}return r}var ki={exports:{}},Oc={},Em;function yC(){return Em||(Em=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,O){return{validate:M,compare:O}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),h),"iso-time":t(l(),u),"iso-date-time":t(p(),y),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:b,"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:U,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:m,int32:{type:"number",validate:_},int64:{type:"number",validate:S},float:{type:"number",validate:$},double:{type:"number",validate:$},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,h),"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,y),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(M){return M%4===0&&(M%100!==0||M%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(M){const O=n.exec(M);if(!O)return!1;const A=+O[1],L=+O[2],Y=+O[3];return L>=1&&L<=12&&Y>=1&&Y<=(L===2&&r(A)?29:o[L])}function a(M,O){if(M&&O)return M>O?1:M<O?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(M){return function(A){const L=i.exec(A);if(!L)return!1;const Y=+L[1],J=+L[2],de=+L[3],K=L[4],$e=L[5]==="-"?-1:1,Z=+(L[6]||0),N=+(L[7]||0);if(Z>23||N>59||M&&!K)return!1;if(Y<=23&&J<=59&&de<60)return!0;const H=J-N*$e,z=Y-Z*$e-(H<0?1:0);return(z===23||z===-1)&&(H===59||H===-1)&&de<61}}function c(M,O){if(!(M&&O))return;const A=new Date("2020-01-01T"+M).valueOf(),L=new Date("2020-01-01T"+O).valueOf();if(A&&L)return A-L}function u(M,O){if(!(M&&O))return;const A=i.exec(M),L=i.exec(O);if(A&&L)return M=A[1]+A[2]+A[3],O=L[1]+L[2]+L[3],M>O?1:M<O?-1:0}const f=/t|\s/i;function p(M){const O=l(M);return function(L){const Y=L.split(f);return Y.length===2&&s(Y[0])&&O(Y[1])}}function h(M,O){if(!(M&&O))return;const A=new Date(M).valueOf(),L=new Date(O).valueOf();if(A&&L)return A-L}function y(M,O){if(!(M&&O))return;const[A,L]=M.split(f),[Y,J]=O.split(f),de=a(A,Y);if(de!==void 0)return de||c(L,J)}const w=/\/|:/,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 b(M){return w.test(M)&&g.test(M)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(M){return v.lastIndex=0,v.test(M)}const T=-2147483648,k=2**31-1;function _(M){return Number.isInteger(M)&&M<=k&&M>=T}function S(M){return Number.isInteger(M)}function $(){return!0}const x=/[^\\]\\Z/;function U(M){if(x.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})(Oc)),Oc}var Ac={},xm;function vC(){return xm||(xm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=_f(),r=Ne(),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:f,it:p}=i,{opts:h,self:y}=p;if(!h.validateFormats)return;const w=new t.KeywordCxt(p,y.RULES.all.format.definition,"format");w.$data?g():b();function g(){const m=l.scopeValue("formats",{ref:y.formats,code:h.code.formats}),T=l.const("fmt",(0,r._)`${m}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${T} != "object"`,(0,r._)`${T} instanceof RegExp`,(0,r._)`typeof ${T}.compare != "function"`,v(T)))}function b(){const m=w.schema,T=y.formats[m];if(!T||T===!0)return;if(typeof T!="object"||T instanceof RegExp||typeof T.compare!="function")throw new Error(`"${f}": format "${m}" does not define "compare" function`);const k=l.scopeValue("formats",{key:m,ref:T,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(m)}`:void 0});i.fail$data(v(k))}function v(m){return(0,r._)`${m}.compare(${c}, ${u}) ${o[f].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(Ac)),Ac}var $m;function _C(){return $m||($m=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=yC(),n=vC(),o=Ne(),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[f,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],h=u.formats||r.formatNames;return l(c,h,f,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,f,p){var h,y;(h=(y=c.opts.code).formats)!==null&&h!==void 0||(y.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const w of u)c.addFormat(w,f[w])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(ki,ki.exports)),ki.exports}var wC=_C();const bC=kn(wC);function kC(){const e=new wf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return bC(e),e}class Rm{constructor(t){this._ajv=t??kC()}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 TC{constructor(t){this._client=t}async*callToolStream(t,r=co,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 ae(ce.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 ae(ce.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ae){yield{type:"error",error:u};return}yield{type:"error",error:new ae(ce.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 Pm(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 Mm(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 Ti(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&&Ti(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Ti(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Ti(r,t)}}function CC(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 ys extends Cm{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 Rm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Tc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",bc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",hc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new TC(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Im(this._capabilities,t)}setRequestHandler(t,r){const o=po(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(ur(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=dr(Ic,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ce.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:f}=u.data;f.mode=f.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=CC(this._capabilities.elicitation);if(f.mode==="form"&&!p)throw new ae(ce.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!h)throw new ae(ce.InvalidParams,"Client does not support URL-mode elicitation requests");const y=await Promise.resolve(r(l,c));if(f.task){const v=dr(io,y);if(!v.success){const m=v.error instanceof Error?v.error.message:String(v.error);throw new ae(ce.InvalidParams,`Invalid task creation result: ${m}`)}return v.data}const w=dr(ms,y);if(!w.success){const v=w.error instanceof Error?w.error.message:String(w.error);throw new ae(ce.InvalidParams,`Invalid elicitation result: ${v}`)}const g=w.data,b=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&g.action==="accept"&&g.content&&b&&this._capabilities.elicitation?.form?.applyDefaults)try{Ti(b,g.content)}catch{}return g};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=dr(Cc,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ce.InvalidParams,`Invalid sampling request: ${g}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const g=dr(io,p);if(!g.success){const b=g.error instanceof Error?g.error.message:String(g.error);throw new ae(ce.InvalidParams,`Invalid task creation result: ${b}`)}return g.data}const y=f.tools||f.toolChoice?Sc:wi,w=dr(y,p);if(!w.success){const g=w.error instanceof Error?w.error.message:String(w.error);throw new ae(ce.InvalidParams,`Invalid sampling result: ${g}`)}return w.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:is,capabilities:this._capabilities,clientInfo:this._clientInfo}},Hh,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!jh.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){Pm(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Mm(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},ln,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},im,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},ln,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},nm,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},rm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Kh,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Yh,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Qh,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},ln,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},ln,r)}async callTool(t,r=co,n){if(this.isToolTaskRequired(t.name))throw new ae(ce.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 ae(ce.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 ae(ce.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ae?a:new ae(ce.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},sm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=Jk.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 f=await o();l(null,f)}catch(f){const p=f instanceof Error?f:new Error(String(f));l(p,null)}},u=()=>{if(i){const f=this._listChangedDebounceTimers.get(t);f&&clearTimeout(f);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 Om 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 Nc(e){}function Am(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=Nc,onError:r=Nc,onRetry:n=Nc,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(w){const g=a?w.replace(/^\xEF\xBB\xBF/,""):w,[b,v]=SC(`${s}${g}`);for(const m of b)f(m);s=v,a=!1}function f(w){if(w===""){h();return}if(w.startsWith(":")){o&&o(w.slice(w.startsWith(": ")?2:1));return}const g=w.indexOf(":");if(g!==-1){const b=w.slice(0,g),v=w[g+1]===" "?2:1,m=w.slice(g+v);p(b,m,w);return}p(w,"",w)}function p(w,g,b){switch(w){case"event":c=g;break;case"data":l=`${l}${g}
40
- `;break;case"id":i=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new Om(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:b}));break;default:r(new Om(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:g,line:b}));break}}function h(){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 y(w={}){s&&w.consume&&f(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:y}}function SC(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
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 qm(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===J.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]})??Bt(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===J.ZodString&&e.keyType._def.checks?.length){const{type:n,...o}=Nm(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===J.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===J.ZodBranded&&e.keyType._def.type._def.typeName===J.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...o}=Mm(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function pC(e,t){if(t.mapStrategy==="record")return qm(e,t);const r=He(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Bt(t),n=He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Bt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function fC(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 hC(e){return e.target==="openAi"?void 0:{not:Bt({...e,currentPath:[...e.currentPath,"not"]})}}function mC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gC(e,t){if(t.target==="openApi3")return Lm(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ni&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Ni[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 Lm(e,t)}const Lm=(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 yC(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:Ni[e.innerType._def.typeName],nullable:!0}:{type:[Ni[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 vC(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",Rm(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 _C(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=bC(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=wC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function wC(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 bC(e){try{return e.isOptional()}catch{return!0}}const kC=(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:Bt(t)},r]}:Bt(t)},TC=(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 CC(e,t){return He(e.type._def,t)}function SC(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 IC(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 xC(e){return{not:Bt(e)}}function EC(e){return Bt(e)}const $C=(e,t)=>He(e.innerType._def,t),RC=(e,t,r)=>{switch(t){case J.ZodString:return Nm(e,r);case J.ZodNumber:return vC(e,r);case J.ZodObject:return _C(e,r);case J.ZodBigInt:return eC(e,r);case J.ZodBoolean:return tC();case J.ZodDate:return Om(e,r);case J.ZodUndefined:return xC(r);case J.ZodNull:return mC(r);case J.ZodArray:return XT(e,r);case J.ZodUnion:case J.ZodDiscriminatedUnion:return gC(e,r);case J.ZodIntersection:return lC(e,r);case J.ZodTuple:return IC(e,r);case J.ZodRecord:return qm(e,r);case J.ZodLiteral:return cC(e,r);case J.ZodEnum:return aC(e);case J.ZodNativeEnum:return fC(e);case J.ZodNullable:return yC(e,r);case J.ZodOptional:return kC(e,r);case J.ZodMap:return pC(e,r);case J.ZodSet:return SC(e,r);case J.ZodLazy:return()=>e.getter()._def;case J.ZodPromise:return CC(e,r);case J.ZodNaN:case J.ZodNever:return hC(r);case J.ZodEffects:return sC(e,r);case J.ZodAny:return Bt(r);case J.ZodUnknown:return EC(r);case J.ZodDefault:return oC(e,r);case J.ZodBranded:return Mm(e,r);case J.ZodReadonly:return $C(e,r);case J.ZodCatch:return rC(e,r);case J.ZodPipeline:return TC(e,r);case J.ZodFunction:case J.ZodVoid:case J.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!==KT)return i}if(n&&!r){const i=PC(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=RC(e,e.typeName,t),a=typeof s=="function"?He(s(),t):s;if(a&&MC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const PC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pm(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`),Bt(t)):t.$refStrategy==="seen"?Bt(t):void 0}},MC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),OC=(e,t)=>{const r=QT(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)??Bt(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)??Bt(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 NC(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function jm(e,t){return vr(e)?qh(e,{target:NC(t?.target),io:t?.pipeStrategy??"input"}):OC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Dm(e){const r=wo(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 Um(e,t){const r=_r(e,t);if(!r.success)throw r.error;return r.data}const AC=6e4;class zm{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(vc,r=>{this._oncancel(r)}),this.setNotificationHandler(bc,r=>{this._onprogress(r)}),this.setRequestHandler(wc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(kc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ae(ue.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Cc,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 ae(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 ae(ue.InvalidParams,`Task not found: ${s}`);if(!Fn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Fn(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(Sc,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 ae(ue.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ae(ue.InvalidParams,`Task not found: ${r.params.taskId}`);if(Fn(o.status))throw new ae(ue.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 ae(ue.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ae?o:new ae(ue.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),ae.fromError(ue.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),_s(s)||Nk(s)?this._onresponse(s):mc(s)?this._onrequest(s,a):Ok(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=ae.fromError(ue.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:ue.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=Mk(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:ue.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),_s(t))n(t);else{const a=new ae(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(_s(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),_s(t))o(t);else{const a=ae.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 ae?a:new ae(ue.InternalError,String(a))}}return}let s;try{const a=await this.request(t,go,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ae(ue.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Fn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ae(ue.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ae(ue.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 ae?a:new ae(ue.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(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));const m=v instanceof ae?v:new ae(ue.RequestTimeout,String(v));u(m)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const m=_r(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??AC,y=()=>g(ae.fromError(ue.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const v=m=>{const C=this._responseHandlers.get(p);C?C(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},Tc,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},Ic,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Kk,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=Dm(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Um(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=Dm(t);this._notificationHandlers.set(n,o=>{const s=Um(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"&&mc(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ae(ue.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 ae(ue.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ae(ue.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 ae(ue.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=xi.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Fn(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 ae(ue.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Fn(i.status))throw new ae(ue.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=xi.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Fn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function Zm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fm(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 Ai={exports:{}},Yc={},Vm;function qC(){return Vm||(Vm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t($,N){return{validate:$,compare:N}}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:b},int64:{type:"number",validate:S},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($){return $%4===0&&($%100!==0||$%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($){const N=n.exec($);if(!N)return!1;const A=+N[1],U=+N[2],V=+N[3];return U>=1&&U<=12&&V>=1&&V<=(U===2&&r(A)?29:o[U])}function a($,N){if($&&N)return $>N?1:$<N?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l($){return function(A){const U=i.exec(A);if(!U)return!1;const V=+U[1],Q=+U[2],_e=+U[3],te=U[4],ge=U[5]==="-"?-1:1,H=+(U[6]||0),M=+(U[7]||0);if(H>23||M>59||$&&!te)return!1;if(V<=23&&Q<=59&&_e<60)return!0;const B=Q-M*ge,Z=V-H*ge-(B<0?1:0);return(Z===23||Z===-1)&&(B===59||B===-1)&&_e<61}}function c($,N){if(!($&&N))return;const A=new Date("2020-01-01T"+$).valueOf(),U=new Date("2020-01-01T"+N).valueOf();if(A&&U)return A-U}function u($,N){if(!($&&N))return;const A=i.exec($),U=i.exec(N);if(A&&U)return $=A[1]+A[2]+A[3],N=U[1]+U[2]+U[3],$>N?1:$<N?-1:0}const h=/t|\s/i;function p($){const N=l($);return function(U){const V=U.split(h);return V.length===2&&s(V[0])&&N(V[1])}}function f($,N){if(!($&&N))return;const A=new Date($).valueOf(),U=new Date(N).valueOf();if(A&&U)return A-U}function g($,N){if(!($&&N))return;const[A,U]=$.split(h),[V,Q]=N.split(h),_e=a(A,V);if(_e!==void 0)return _e||c(U,Q)}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($){return _.test($)&&y.test($)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m($){return v.lastIndex=0,v.test($)}const C=-2147483648,k=2**31-1;function b($){return Number.isInteger($)&&$<=k&&$>=C}function S($){return Number.isInteger($)}function x(){return!0}const I=/[^\\]\\Z/;function L($){if(I.test($))return!1;try{return new RegExp($),!0}catch{return!1}}})(Yc)),Yc}var Qc={},Hm;function LC(){return Hm||(Hm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=qf(),r=Ne(),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}),C=l.const("fmt",(0,r._)`${m}[${_.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${C} != "object"`,(0,r._)`${C} instanceof RegExp`,(0,r._)`typeof ${C}.compare != "function"`,v(C)))}function w(){const m=_.schema,C=g.formats[m];if(!C||C===!0)return;if(typeof C!="object"||C instanceof RegExp||typeof C.compare!="function")throw new Error(`"${h}": format "${m}" does not define "compare" function`);const k=l.scopeValue("formats",{key:m,ref:C,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})(Qc)),Qc}var Bm;function jC(){return Bm||(Bm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=qC(),n=LC(),o=Ne(),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})(Ai,Ai.exports)),Ai.exports}var DC=jC();const UC=Mn(DC);function zC(){const e=new Lf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return UC(e),e}class Jm{constructor(t){this._ajv=t??zC()}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 ZC{constructor(t){this._client=t}async*callToolStream(t,r=vo,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 ae(ue.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 ae(ue.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ae){yield{type:"error",error:u};return}yield{type:"error",error:new ae(ue.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 Wm(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 Gm(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 qi(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&&qi(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&qi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&qi(r,t)}}function FC(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 xs extends zm{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 Jm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",zc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Dc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Mc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ZC(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fm(this._capabilities,t)}setRequestHandler(t,r){const o=wo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(vr(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=_r(Vc,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ue.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=FC(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new ae(ue.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!f)throw new ae(ue.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(h.task){const v=_r(go,g);if(!v.success){const m=v.error instanceof Error?v.error.message:String(v.error);throw new ae(ue.InvalidParams,`Invalid task creation result: ${m}`)}return v.data}const _=_r(Ss,g);if(!_.success){const v=_.error instanceof Error?_.error.message:String(_.error);throw new ae(ue.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{qi(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=_r(Zc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ue.InvalidParams,`Invalid sampling request: ${y}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const y=_r(go,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ae(ue.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=h.tools||h.toolChoice?Fc:Oi,_=_r(g,p);if(!_.success){const y=_.error instanceof Error?_.error.message:String(_.error);throw new ae(ue.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:ys,capabilities:this._capabilities,clientInfo:this._clientInfo}},lm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!tm.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){Wm(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Gm(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},_n,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Cm,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},_n,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},wm,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},_m,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},fm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},hm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},mm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},_n,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},_n,r)}async callTool(t,r=vo,n){if(this.isToolTaskRequired(t.name))throw new ae(ue.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 ae(ue.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 ae(ue.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ae?a:new ae(ue.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},km,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=pT.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 Km 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 Xc(e){}function Ym(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=Xc,onError:r=Xc,onRetry:n=Xc,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(_){const y=a?_.replace(/^\xEF\xBB\xBF/,""):_,[w,v]=VC(`${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 Km(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new Km(`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 VC(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
42
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 Nm 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 IC(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function qc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(qc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${qc(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 Lm=e=>{throw TypeError(e)},Lc=(e,t,r)=>t.has(e)||Lm("Cannot "+r),je=(e,t,r)=>(Lc(e,t,"read from private field"),r?r.call(e):t.get(e)),ft=(e,t,r)=>t.has(e)?Lm("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ot=(e,t,r,n)=>(Lc(e,t,"write to private field"),t.set(e,r),r),Fr=(e,t,r)=>(Lc(e,t,"access private method"),r),zt,An,fo,Ci,Si,vs,ho,_s,cn,mo,go,yo,ws,hr,jc,Dc,Uc,jm,zc,Zc,bs,Fc,Vc;class Ii extends EventTarget{constructor(t,r){var n,o;super(),ft(this,hr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ft(this,zt),ft(this,An),ft(this,fo),ft(this,Ci),ft(this,Si),ft(this,vs),ft(this,ho),ft(this,_s,null),ft(this,cn),ft(this,mo),ft(this,go,null),ft(this,yo,null),ft(this,ws,null),ft(this,Dc,async s=>{var a;je(this,mo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){Fr(this,hr,bs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?ot(this,fo,new URL(s.url)):ot(this,fo,void 0),c!==200){Fr(this,hr,bs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Fr(this,hr,bs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(je(this,zt)===this.CLOSED)return;ot(this,zt,this.OPEN);const f=new Event("open");if((a=je(this,ws))==null||a.call(this,f),this.dispatchEvent(f),typeof i!="object"||!i||!("getReader"in i)){Fr(this,hr,bs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,h=i.getReader();let y=!0;do{const{done:w,value:g}=await h.read();g&&je(this,mo).feed(p.decode(g,{stream:!w})),w&&(y=!1,je(this,mo).reset(),Fr(this,hr,Fc).call(this))}while(y)}),ft(this,Uc,s=>{ot(this,cn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Fr(this,hr,Fc).call(this,qc(s))}),ft(this,zc,s=>{typeof s.id=="string"&&ot(this,_s,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:je(this,fo)?je(this,fo).origin:je(this,An).origin,lastEventId:s.id||""});je(this,yo)&&(!s.event||s.event==="message")&&je(this,yo).call(this,a),this.dispatchEvent(a)}),ft(this,Zc,s=>{ot(this,vs,s)}),ft(this,Vc,()=>{ot(this,ho,void 0),je(this,zt)===this.CONNECTING&&Fr(this,hr,jc).call(this)});try{if(t instanceof URL)ot(this,An,t);else if(typeof t=="string")ot(this,An,new URL(t,EC()));else throw new Error("Invalid URL")}catch{throw IC("An invalid or illegal string was specified")}ot(this,mo,Am({onEvent:je(this,zc),onRetry:je(this,Zc)})),ot(this,zt,this.CONNECTING),ot(this,vs,3e3),ot(this,Si,(n=r?.fetch)!=null?n:globalThis.fetch),ot(this,Ci,(o=r?.withCredentials)!=null?o:!1),Fr(this,hr,jc).call(this)}get readyState(){return je(this,zt)}get url(){return je(this,An).href}get withCredentials(){return je(this,Ci)}get onerror(){return je(this,go)}set onerror(t){ot(this,go,t)}get onmessage(){return je(this,yo)}set onmessage(t){ot(this,yo,t)}get onopen(){return je(this,ws)}set onopen(t){ot(this,ws,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(){je(this,ho)&&clearTimeout(je(this,ho)),je(this,zt)!==this.CLOSED&&(je(this,cn)&&je(this,cn).abort(),ot(this,zt,this.CLOSED),ot(this,cn,void 0))}}zt=new WeakMap,An=new WeakMap,fo=new WeakMap,Ci=new WeakMap,Si=new WeakMap,vs=new WeakMap,ho=new WeakMap,_s=new WeakMap,cn=new WeakMap,mo=new WeakMap,go=new WeakMap,yo=new WeakMap,ws=new WeakMap,hr=new WeakSet,jc=function(){ot(this,zt,this.CONNECTING),ot(this,cn,new AbortController),je(this,Si)(je(this,An),Fr(this,hr,jm).call(this)).then(je(this,Dc)).catch(je(this,Uc))},Dc=new WeakMap,Uc=new WeakMap,jm=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...je(this,_s)?{"Last-Event-ID":je(this,_s)}:void 0},cache:"no-store",signal:(e=je(this,cn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},zc=new WeakMap,Zc=new WeakMap,bs=function(e,t){var r;je(this,zt)!==this.CLOSED&&ot(this,zt,this.CLOSED);const n=new Nm("error",{code:t,message:e});(r=je(this,go))==null||r.call(this,n),this.dispatchEvent(n)},Fc=function(e,t){var r;if(je(this,zt)===this.CLOSED)return;ot(this,zt,this.CONNECTING);const n=new Nm("error",{code:t,message:e});(r=je(this,go))==null||r.call(this,n),this.dispatchEvent(n),ot(this,ho,setTimeout(je(this,Vc),je(this,vs)))},Vc=new WeakMap,Ii.CONNECTING=0,Ii.OPEN=1,Ii.CLOSED=2;function EC(){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 Ei(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Dm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ei(t.headers),...Ei(n.headers)}:t.headers};return e(r,o)}:e}let Hc;Hc=globalThis.crypto;async function xC(e){return(await Hc).getRandomValues(new Uint8Array(e))}async function $C(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await xC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function RC(e){return await $C(e)}async function PC(e){const t=await(await Hc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Um(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await RC(e),r=await PC(t);return{code_verifier:t,code_challenge:r}}const Tt=k4().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:qh.custom,message:"URL must be parseable",fatal:!0}),Of}).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"}),MC=at({resource:d().url(),authorization_servers:q(Tt).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()}),zm=at({issuer:d(),authorization_endpoint:Tt,token_endpoint:Tt,registration_endpoint:Tt.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:Tt.optional(),revocation_endpoint:Tt.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()}),OC=at({issuer:d(),authorization_endpoint:Tt,token_endpoint:Tt,userinfo_endpoint:Tt.optional(),jwks_uri:Tt,registration_endpoint:Tt.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:Tt.optional(),op_tos_uri:Tt.optional(),client_id_metadata_document_supported:me().optional()}),AC=C({...OC.shape,...zm.pick({code_challenge_methods_supported:!0}).shape}),NC=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Lh().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),qC=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),Zm=Tt.optional().or(P("").transform(()=>{})),LC=C({redirect_uris:q(Tt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Tt.optional(),logo_uri:Zm,scope:d().optional(),contacts:q(d()).optional(),tos_uri:Zm,policy_uri:d().optional(),jwks_uri:Tt.optional(),jwks:mt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),jC=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),DC=LC.merge(jC);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function UC(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function zC({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 gt 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 Bc extends gt{}Bc.errorCode="invalid_request";let xi=class extends gt{};xi.errorCode="invalid_client";let $i=class extends gt{};$i.errorCode="invalid_grant";let Ri=class extends gt{};Ri.errorCode="unauthorized_client";class Jc extends gt{}Jc.errorCode="unsupported_grant_type";class Wc extends gt{}Wc.errorCode="invalid_scope";class Gc extends gt{}Gc.errorCode="access_denied";let vo=class extends gt{};vo.errorCode="server_error";class Kc extends gt{}Kc.errorCode="temporarily_unavailable";class Yc extends gt{}Yc.errorCode="unsupported_response_type";class Qc extends gt{}Qc.errorCode="unsupported_token_type";class Xc extends gt{}Xc.errorCode="invalid_token";class eu extends gt{}eu.errorCode="method_not_allowed";class tu extends gt{}tu.errorCode="too_many_requests";class Pi extends gt{}Pi.errorCode="invalid_client_metadata";class ru extends gt{}ru.errorCode="insufficient_scope";class nu extends gt{}nu.errorCode="invalid_target";const ZC={[Bc.errorCode]:Bc,[xi.errorCode]:xi,[$i.errorCode]:$i,[Ri.errorCode]:Ri,[Jc.errorCode]:Jc,[Wc.errorCode]:Wc,[Gc.errorCode]:Gc,[vo.errorCode]:vo,[Kc.errorCode]:Kc,[Yc.errorCode]:Yc,[Qc.errorCode]:Qc,[Xc.errorCode]:Xc,[eu.errorCode]:eu,[tu.errorCode]:tu,[Pi.errorCode]:Pi,[ru.errorCode]:ru,[nu.errorCode]:nu};let rr=class extends Error{constructor(t){super(t??"Unauthorized")}};function FC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ou="code",su="S256";function VC(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&&FC(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 HC(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":BC(o,s,r);return;case"client_secret_post":JC(o,s,n);return;case"none":WC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function BC(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 JC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function WC(e,t){t.set("client_id",e)}async function Fm(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=qC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=ZC[o]||vo;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new vo(o)}}async function Nn(e,t){try{return await au(e,t)}catch(r){if(r instanceof xi||r instanceof Ri)return await e.invalidateCredentials?.("all"),await au(e,t);if(r instanceof $i)return await e.invalidateCredentials?.("tokens"),await au(e,t);throw r}}async function au(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await YC(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 KC(t,e,a),c=await rS(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 g=c?.client_id_metadata_document_supported===!0,b=e.clientMetadataUrl;if(b&&!GC(b))throw new Pi(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(g&&b)u={client_id:b},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const m=await iS(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(m),u=m}}const f=!e.redirectUrl;if(r!==void 0||f){const g=await aS(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const g=await sS(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof gt)||g instanceof vo))throw g}const h=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:w}=await nS(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(y),"REDIRECT"}function GC(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function KC(e,t,r){const n=UC(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!zC({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 Mi(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=iu(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=iu(e,"scope")||void 0,i=iu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function iu(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 YC(e,t,r=fetch){const n=await eS(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 MC.parse(await n.json())}async function lu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?lu(e,void 0,r):void 0;throw n}}function QC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Vm(e,t,r=fetch){return await lu(e,{"MCP-Protocol-Version":t},r)}function XC(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function eS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??is;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=QC(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await Vm(a,s,r);if(!n?.metadataUrl&&XC(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await Vm(l,s,r)}return i}function tS(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 rS(e,{fetchFn:t=fetch,protocolVersion:r=is}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=tS(e);for(const{url:s,type:a}of o){const i=await lu(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"?zm.parse(await i.json()):AC.parse(await i.json())}}}async function nS(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(ou))throw new Error(`Incompatible auth server: does not support response type ${ou}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(su))throw new Error(`Incompatible auth server: does not support code challenge method ${su}`)}else i=new URL("/authorize",e);const l=await Um(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",ou),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",su),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 oS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Hm(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??[],f=VC(n,u);HC(f,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await Fm(c);return NC.parse(await c.json())}async function sS(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 Hm(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function aS(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=oS(o,c,e.redirectUrl)}const l=await e.clientInformation();return Hm(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function iS(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 Fm(s);return DC.parse(await s.json())}class lS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class ks{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=Dm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Nn(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 rr;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=Ei(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 Ii(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}=Mi(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 lS(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=Zr.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 rr("No auth provider");if(await Nn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("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}=Mi(o);if(this._resourceMetadataUrl=a,this._scope=i,await Nn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;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 _o extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Am({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 cS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class wo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Ts{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=Dm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??cS}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Nn(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 rr;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=Ei(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 wo(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 _o({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){const{value:h,done:y}=await u.read();if(y)break;if(h.id&&(a=h.id,i=!0,o?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{const w=Zr.parse(JSON.parse(h.data));cs(w)&&(l=!0,s!==void 0&&(w.id=s)),this.onmessage?.(w)}catch(w){this.onerror?.(w)}}(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(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 rr("No auth provider");if(await Nn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("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:Yl(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 wo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:h,scope:y}=Mi(i);if(this._resourceMetadataUrl=h,this._scope=y,await Nn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:h,scope:y,error:w}=Mi(i);if(w==="insufficient_scope"){const g=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new wo(403,"Server returned 403 after trying upscoping");if(y&&(this._scope=y),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=g??void 0,await Nn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new rr;return this.send(t)}}throw new wo(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),Sk(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,f=i.headers.get("content-type");if(u)if(f?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(f?.includes("application/json")){const p=await i.json(),h=Array.isArray(p)?p.map(y=>Zr.parse(y)):[Zr.parse(p)];for(const y of h)this.onmessage?.(y)}else throw await i.body?.cancel(),new wo(-1,`Unexpected content type: ${f}`);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 wo(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 uS="mcp";class Bm{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,uS),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=Zr.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 un=Wt;(function(e,t){const r=Wt,n=Wt,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())}})(Oi,-118057+3521*-35+-2099*-233);const Jm=()=>{const e=Wt,t=Wt,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}},dS=(e,t,r)=>{const n=Wt,o=Wt,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)},pS=(e,t)=>{const r=Wt,n=Wt,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 Cs{constructor(t){this._port=t}async[un(401)](){const t=un,r=un;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=Zr.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=Wt,l=Wt;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=un,o=un;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class cu extends Cs{constructor(t,r=Jm()){const n=un,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)](dS,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class uu extends Cs{constructor(t,r=Jm()){const n=un,o=un,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)](pS,this._globalObject,c=>{const u=i,f=i;c[u(412)]&&l.XlglK(c.data[f(396)],this._endpoint)&&(this[u(422)]=c[f(430)][-3036+-1518*-2],l.pXlad(a))})})}async listen(){return this._listen}}function Oi(){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 Oi=function(){return e},Oi()}function Wt(e,t){const r=Oi();return Wt=function(n,o){return n=n-(17227+1*-16844),r[n]},Wt(e,t)}const fS=()=>{const e=new MessageChannel;return[new Cs(e.port1),new Cs(e.port2)]};(function(e,t){const r=Qe,n=Qe,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())}})(Ai,-411935*1+228107+208149*2);const hS=async(e,t,r)=>{var n;const o=Qe,s=Qe,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 f={};switch(c){case i.VRyiJ:f=await t.listTools(u);break;case i.VkPYu:f=await t.callTool(u);break;case i.fgMSD:f=await t.listResources(u);break;case i[s(466)]:f=await t.listResourceTemplates(u);break;case i.sthgI:f=await t[o(455)](u);break;case s(486):f=await t.subscribeResource(u);break;case o(410):f=await t.unsubscribeResource(u);break;case i[s(461)]:f=await t[s(414)](u);break;case i[o(412)]:f=await t[o(491)](u);break;case i[o(436)]:f=await t[o(478)]();break;case i.kkNqg:f=await t.complete(u);break;case o(464):f=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=f,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=Qe,s=Qe,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let f={};switch(c){case"roots/list":const h={};h.method=c,h[s(446)]=u,f=await t[o(469)](h,xc);break;case"sampling/createMessage":const y={};y[o(481)]=c,y[o(446)]=u,f=await t.request(y,wi);break;case i[o(487)]:const w={};w.method=c,w[s(446)]=u,f=await t.request(w,ms);break;case i.ypHTC:const g={};g.method=c,f=await t.request(g,ln);break}const p={};return p.result=f,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),f};function Qe(e,t){const r=Ai();return Qe=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Qe(e,t)}const gS=(e,t)=>{const r=Qe,n=Qe,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,f,p;const h=n,y=r,{id:w,method:g}=a;try{o[h(451)](g,o.DhPFX)?await s.call(e,a,i):await o[y(474)](hS,e,t,a)}catch(b){const{code:v,message:m,data:T}=b;try{if(v){const k={};k[y(485)]=v,k[h(422)]=m,k.data=T;const _={};_[y(448)]=k,_.jsonrpc=o[h(417)],_.id=w,await((l=e?.transport)==null?void 0:l[y(460)](_))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,b)}catch(k){(p=(f=e?.transport)==null?void 0:f.onerror)==null||p.call(f,k)}}}},yS=(e,t)=>{const r=Qe,n=Qe,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:f,params:p}=a;if(f!==s[c(476)]&&(s.QWYMz(f,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(h){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,h)}}},vS=(e,t)=>async r=>{var n,o,s,a,i;const l=Qe,c=Qe,u={TJhyV:function(f,p,h,y){return f(p,h,y)},MMNTY:l(465)};try{return await u.TJhyV(mS,e,t,r)}catch(f){const{code:p,message:h,data:y}=f;try{if(p){const w={};w.code=p,w[l(422)]=h,w[c(419)]=y;const g={};g[l(448)]=w,g[l(424)]=u.MMNTY,g.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](g))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,f)}catch(w){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,w)}}},_S=(e,t)=>async r=>{var n,o,s;const a=Qe,i=Qe,l={};l.xmcLM=function(p,h){return p!==h},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:f}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||f?.[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 Ai(){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 Ai=function(){return e},Ai()}const wS=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Qe,u=Qe,f={};f.kSvAZ=c(465);const p=f;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(h){const{code:y,message:w,data:g}=h;try{if(y){const b={};b.code=y,b.message=w,b.data=g;const v={};v.error=b,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,h)}catch(b){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,b)}}},du=()=>{const e=Qe,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Qe;if(c){const f=[];for(const p of r)try{f.push(p(l,c))}catch{}for(const p of f)if(t.rgPZO(p,null))return p}else for(const f of r)try{t[u(427)](f,l)}catch{}},o=l=>{const c=Qe,u=Qe;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Qe,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Qe;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},bS=e=>{const t=Qe,r=Qe,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](du);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)](du);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(du);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},kS=(e,{beforeInit:t,afterInit:r}={})=>{const n=Qe,o=Qe,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(bS,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)})},TS=Vr;(function(e,t){const r=Vr,n=Vr,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())}})(Ni,995159+-6*-266138+-1619768);const CS=()=>{const e=Vr,t=Vr,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)})},SS=e=>{const t=Vr,r=Vr,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)]("")},dn={};dn[TS(211)]=CS,dn.randomBytes=SS;function Vr(e,t){const r=Ni();return Vr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Vr(e,t)}function Ni(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Ni=function(){return e},Ni()}function Hr(e,t){const r=qi();return Hr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Hr(e,t)}const mr=Hr,Ss=Hr;(function(e,t){const r=Hr,n=Hr,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())}})(qi,-4*308317+753182*2+658196);const IS=(e,t)=>{const r=Hr,n=Hr,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)](gS,e,t),yS(e,t);const s=o[n(283)](vS,t,e),a=o[n(294)](wS,t,e),i=o[r(277)](_S,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)}},pu=(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,ks)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Hr(295)])==null||i.close()})),n.Qalmc(IS,e,t)},s={};s.afterInit=o,n.Qalmc(kS,t,s)},Wm=(e,t=dn[mr(299)]())=>{const r=mr,n=mr,o={RVabx:function(u,f,p){return u(f,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,f){const p=r,h=r,y=new Headers(f?.[p(268)]||{});Object.entries(a).forEach(([g,b])=>{y.set(g,b)});const w={...f};return w.headers=y,o[h(279)](fetch,u,w)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},Gm=(e,t=dn[mr(299)]())=>{const r=Ss,n=mr,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},fu=async(e,t,r)=>{const n=mr,o=mr,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,rr)){const l=await t();return await a[n(257)](l),await fu(e,t,r)}else throw i}},Km=(e,t)=>{const r=Ss,n=Ss,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 qi(){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 qi=function(){return e},qi()}const ES=async e=>{const t=Ss,r=mr,n={GKDjq:function(x,U,M){return x(U,M)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(x){return x()},kdowC:function(x,U,M,O){return x(U,M,O)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const h=p,y=i||dn[r(299)](),w=n[t(289)](Wm,a,y);if(c){const x={...w.requestInit,...c};x[r(268)]={...w[r(280)][t(268)],...c.headers},h.requestInit=x}else h.requestInit=w[t(280)];if(u){const x={...w[t(270)],...u};h.eventSourceInit=x}else h.eventSourceInit=w[t(270)];const g={};g[t(254)]=!0;const b={};b.roots=g,b[t(298)]={},b[r(303)]={};const v=b,m={};m.name=n[r(261)],m[t(288)]=n.mcbiU;const T={};T[t(251)]=v;const k=new ys(m,T),_=()=>new ks(new URL(s),h);let S=n[t(282)](_);if(l){const x=Km(l,f);S=await n[t(263)](fu,k,x,_)}else await k.connect(S);pu(k,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const $={};return $.transport=S,$.sessionId=S[r(286)],$},xS=async e=>{const t=Ss,r=mr,n={wfHUn:function(x,U,M){return x(U,M)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(x){return x()},PdsSn:function(x,U,M,O){return x(U,M,O)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const h=p,y=i||dn.randomUUID(),w=n[r(272)](Gm,a,y);if(c){const x={...w[t(280)],...c};x.headers={...w.requestInit[t(268)],...c.headers},h.requestInit=x}else h[r(280)]=w[r(280)];const g={};g[r(254)]=!0;const b={};b.roots=g,b[t(298)]={},b[t(303)]={};const v=b,m={};m.name=n[t(262)],m.version=n.omKPe;const T={};T.capabilities=v;const k=new ys(m,T),_=()=>new Ts(new URL(s),h);let S=n.rSiEq(_);if(l){const x=n[t(272)](Km,l,f);S=await n[t(296)](fu,k,x,_)}else await k[t(260)](S);n.PdsSn(pu,k,o,S);const $={};return $.transport=S,$[r(286)]=S[r(286)],$},$S=async e=>{const t=mr,r=mr,n={eZwNI:function(b,v,m,T){return b(v,m,T)}},{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,f={};f.name="mcp-socket-proxy-client",f.version=r(248);const p={};p[r(251)]=u;const h=new ys(f,p),y=i||dn[r(299)](),w=new Bm(new URL(s+"?sessionId="+y+r(265)+a));await h.connect(w),n[t(259)](pu,h,o,w);const g={};return g.transport=w,g[r(286)]=y,g},pn=gr,Is=gr;(function(e,t){const r=gr,n=gr,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())}})(Li,1297719+-42747*-22+-1289197);function gr(e,t){const r=Li();return gr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},gr(e,t)}const RS=()=>dn.randomBytes(-8746+-382*-23);class PS{constructor(t){const r=gr,n=gr,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(RS),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=gr,c=gr,u={};u[l(198)]="GET";const f=await fetch(t,u);!f.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+f[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 h=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,h.code)}async[pn(191)](t,r){const n=pn,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=gr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[pn(206)]}get[Is(190)](){return this._clientMetadata}[pn(213)](){return this[pn(197)]}[Is(218)](){return this[Is(200)]}[pn(194)](t){this._clientInformation=t}tokens(){return this[Is(210)]}saveTokens(t){const r=Is;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[pn(212)](){const t=pn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Li(){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 Li=function(){return e},Li()}(function(e,t){for(var r=Di,n=Di,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())}})(ji,262*-2438+1346066*-1+2*1373311);function ji(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return ji=function(){return e},ji()}function Di(e,t){var r=ji();return Di=function(n,o){n=n-287;var s=r[n];return s},Di(e,t)}class MS{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 OS extends Cm{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(yi.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 Rm,this.setRequestHandler(Vh,n=>this._oninitialize(n)),this.setNotificationHandler(tc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(vi,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=yi.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new MS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Im(this._capabilities,t)}setRequestHandler(t,r){const o=po(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(ur(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=dr(gi,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ce.InvalidParams,`Invalid tools/call request: ${y}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const y=dr(io,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ae(ce.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const h=dr(co,p);if(!h.success){const y=h.error instanceof Error?h.error.message:String(h.error);throw new ae(ce.InvalidParams,`Invalid tools/call result: ${y}`)}return h.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){Mm(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Pm(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:jh.includes(r)?r:is,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"},ln)}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(f=>f.type==="tool_use").map(f=>f.id)),u=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(c.size!==u.size||![...c].every(f=>u.has(f)))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},Sc,r):this.request({method:"sampling/createMessage",params:t},wi,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},ms,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},ms,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new ae(ce.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof ae?a:new ae(ce.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},xc,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 hu=Symbol.for("mcp.completable");function AS(e,t){return Object.defineProperty(e,hu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function Ym(e){return!!e&&typeof e=="object"&&hu in e}function NS(e){return e[hu]?.complete}var Qm;(function(e){e.Completable="McpCompletable"})(Qm||(Qm={}));const Xm=1e6,mu=1e6,e0=1e4,qS=1e6;class Br{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){Br.validateLength(t,Xm,"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>e0)throw new Error(`Template contains too many expressions (max ${e0})`);const i=t.slice(o+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),f=u[0];for(const p of u)Br.validateLength(p,mu,"Variable name");r.push({name:f,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 Br.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(f=>this.encodeValue(f,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)Br.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){Br.validateLength(t,Xm,"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+="$",Br.validateLength(r,qS,"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],f=l.replace("*","");c&&u.includes(",")?a[f]=u.split(","):a[f]=u}return a}}const LS=/^[A-Za-z0-9._-]{1,128}$/;function jS(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"),!LS.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 DS(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 t0(e){const t=jS(e);return DS(e,t.warnings),t.isValid}class US{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 r0{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 OS(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new US(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(fn(kc)),this.server.assertCanSetRequestHandler(fn(gi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(kc,()=>({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=gs(r.inputSchema);return o?bm(o,{strictUnions:!0,pipeStrategy:"input"}):ZS})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=gs(r.outputSchema);o&&(n.outputSchema=bm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(gi,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new ae(ce.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ae(ce.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 ae(ce.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new ae(ce.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 ae&&n.code===ce.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=gs(t.inputSchema)??t.inputSchema,a=await $c(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Rc(i);throw new ae(ce.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 ae(ce.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=gs(t.outputSchema),s=await $c(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Rc(a);throw new ae(ce.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 f=await n.taskStore.getTask(l);if(!f)throw new ae(ce.InternalError,`Task ${l} not found during polling`);c=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(fn(Ec)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ec,async t=>{switch(t.params.ref.type){case"ref/prompt":return TT(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return CT(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ae(ce.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new ae(ce.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ae(ce.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Es;const s=po(n.argsSchema)?.[t.params.argument.name];if(!Ym(s))return Es;const a=NS(s);if(!a)return Es;const i=await a(t.params.argument.value,t.params.context);return s0(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 Es;throw new ae(ce.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Es;const s=await o(t.params.argument.value,t.params.context);return s0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(fn(mi)),this.server.assertCanSetRequestHandler(fn(dc)),this.server.assertCanSetRequestHandler(fn(fc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(mi,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(dc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(fc,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ae(ce.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 ae(ce.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(fn(mc)),this.server.assertCanSetRequestHandler(fn(gc)),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?VS(r.argsSchema):void 0}))})),this.server.setRequestHandler(gc,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new ae(ce.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ae(ce.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=gs(n.argsSchema),s=await $c(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Rc(l);throw new ae(ce.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:uo(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=uo(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 cr?l._def?.innerType:l;return Ym(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){t0(t);const u={title:r,description:n,inputSchema:o0(o),outputSchema:o0(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:f=>{typeof f.name<"u"&&f.name!==t&&(typeof f.name=="string"&&t0(f.name),delete this._registeredTools[t],f.name&&(this._registeredTools[f.name]=u)),typeof f.title<"u"&&(u.title=f.title),typeof f.description<"u"&&(u.description=f.description),typeof f.paramsSchema<"u"&&(u.inputSchema=uo(f.paramsSchema)),typeof f.outputSchema<"u"&&(u.outputSchema=uo(f.outputSchema)),typeof f.callback<"u"&&(u.handler=f.callback),typeof f.annotations<"u"&&(u.annotations=f.annotations),typeof f._meta<"u"&&(u._meta=f._meta),typeof f.enabled<"u"&&(u.enabled=f.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];gu(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!gu(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 zS{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new Br(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const ZS={type:"object",properties:{}};function n0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function FS(e){return"_def"in e||"_zod"in e||n0(e)}function gu(e){return typeof e!="object"||e===null||FS(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(n0)}function o0(e){if(e)return gu(e)?uo(e):e}function VS(e){const t=po(e);return t?Object.entries(t).map(([r,n])=>{const o=$T(n),s=RT(n);return{name:r,description:o,required:!s}}):[]}function fn(e){const r=po(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=dm(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function s0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Es={completion:{values:[],hasMore:!1}};function HS(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class xs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new xs,r=new xs;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 BS{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 r0(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(vi,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 uu(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(Xh,t)}onUnsubscribe(t){this.server.server.setRequestHandler(em,t)}onSetLogLevel(t){this.server.server.setRequestHandler(vi,t)}onListResources(t){this.server.server.setRequestHandler(mi,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(cm,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const JS=(e,t)=>new uu(e,t),WS=()=>fS(),GS=e=>e instanceof uu,KS=e=>e instanceof r0;class a0{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new ys(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 f;return await(async()=>{const{transport:h,sessionId:y}=s==="sse"?await ES(u):s==="socket"?await $S(u):await xS(u);h.onerror=async w=>{i?.(w)},f={transport:h,sessionId:y}})(),f}const l=new URL(r);let c;if(s==="channel"&&(c=new cu(r),await this.client.connect(c)),s==="sse"){const u=Wm(n,o);c=new ks(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Bm(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=Gm(n,o);c=new Ts(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,co,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(Ic,t)}onCreateMessage(t){this.client.setRequestHandler(Cc,t)}onListRoots(t){this.client.setRequestHandler(lm,t)}onToolListChanged(t){this.client.setNotificationHandler(Tc,t)}onPromptListChanged(t){this.client.setNotificationHandler(bc,t)}onResourceListChanged(t){this.client.setNotificationHandler(hc,t)}onResourceUpdated(t){this.client.setNotificationHandler(tm,t)}onLoggingMessage(t){this.client.setNotificationHandler(am,t)}async onPagehide(t){t.persisted||(i0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const YS=(e,t)=>new ks(e,t),QS=(e,t)=>new Ts(e,t),XS=(e,t)=>new cu(e,t),e6=e=>e instanceof ks,i0=e=>e instanceof Ts,t6=e=>e instanceof cu,r6=e=>e instanceof ys,bo=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},l0=(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)},yu=(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})},vu=(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 c0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=vu("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Zr.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];yu("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 u0=()=>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 n6{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||u0(),this._messageListener1=l0("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=l0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=Zr.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&bo("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】 已关闭,无法发送消息"),bo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&bo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{bo("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 o6{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||u0(),this.tabId=r,vu("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】 已关闭,无法重新启动");vu("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=Zr.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&bo("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),yu("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&t.result?.content&&bo("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,yu("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 ko={},_u,d0;function s6(){return d0||(d0=1,_u=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),_u}var wu={},hn={},p0;function qn(){if(p0)return hn;p0=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 hn.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},hn.getSymbolTotalCodewords=function(n){return t[n]},hn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},hn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},hn.isKanjiModeEnabled=function(){return typeof e<"u"},hn.toSJIS=function(n){return e(n)},hn}var bu={},f0;function ku(){return f0||(f0=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}}})(bu)),bu}var Tu,h0;function a6(){if(h0)return Tu;h0=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++}},Tu=e,Tu}var Cu,m0;function i6(){if(m0)return Cu;m0=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]},Cu=e,Cu}var Su={},g0;function l6(){return g0||(g0=1,(function(e){const t=qn().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}})(Su)),Su}var Iu={},y0;function c6(){if(y0)return Iu;y0=1;const e=qn().getSymbolSize,t=7;return Iu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Iu}var Eu={},v0;function u6(){return v0||(v0=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 f=0;f<s;f++){i=l=0,c=u=null;for(let p=0;p<s;p++){let h=o.get(f,p);h===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=h,i=1),h=o.get(p,f),h===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=h,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}})(Eu)),Eu}var Ui={},_0;function w0(){if(_0)return Ui;_0=1;const e=ku(),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 Ui.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}},Ui.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}},Ui}var xu={},$s={},b0;function d6(){if(b0)return $s;b0=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]})(),$s.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},$s.exp=function(n){return e[n]},$s.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},$s}var k0;function p6(){return k0||(k0=1,(function(e){const t=d6();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}})(xu)),xu}var $u,T0;function f6(){if(T0)return $u;T0=1;const e=p6();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},$u=t,$u}var Ru={},Pu={},Mu={},C0;function S0(){return C0||(C0=1,Mu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Mu}var Er={},I0;function E0(){if(I0)return Er;I0=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
- ]))+`;Er.KANJI=new RegExp(r,"g"),Er.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Er.BYTE=new RegExp(n,"g"),Er.NUMERIC=new RegExp(e,"g"),Er.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Er.testKanji=function(l){return o.test(l)},Er.testNumeric=function(l){return s.test(l)},Er.testAlphanumeric=function(l){return a.test(l)},Er}var x0;function Ln(){return x0||(x0=1,(function(e){const t=S0(),r=E0();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}}})(Pu)),Pu}var $0;function h6(){return $0||($0=1,(function(e){const t=qn(),r=w0(),n=ku(),o=Ln(),s=S0(),a=7973,i=t.getBCHDigit(a);function l(p,h,y){for(let w=1;w<=40;w++)if(h<=e.getCapacity(w,y,p))return w}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let y=0;return p.forEach(function(w){const g=c(w.mode,h);y+=g+w.getBitsLength()}),y}function f(p,h){for(let y=1;y<=40;y++)if(u(p,y)<=e.getCapacity(y,h,o.MIXED))return y}e.from=function(h,y){return s.isValid(h)?parseInt(h,10):y},e.getCapacity=function(h,y,w){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=o.BYTE);const g=t.getSymbolTotalCodewords(h),b=r.getTotalCodewordsCount(h,y),v=(g-b)*8;if(w===o.MIXED)return v;const m=v-c(w,h);switch(w){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(h,y){let w;const g=n.from(y,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,g);if(h.length===0)return 1;w=h[0]}else w=h;return l(w.mode,w.getLength(),g)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let y=h<<12;for(;t.getBCHDigit(y)-i>=0;)y^=a<<t.getBCHDigit(y)-i;return h<<12|y}})(Ru)),Ru}var Ou={},R0;function m6(){if(R0)return Ou;R0=1;const e=qn(),t=1335,r=21522,n=e.getBCHDigit(t);return Ou.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},Ou}var Au={},Nu,P0;function g6(){if(P0)return Nu;P0=1;const e=Ln();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))},Nu=t,Nu}var qu,M0;function y6(){if(M0)return qu;M0=1;const e=Ln(),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)},qu=r,qu}var Lu,O0;function v6(){if(O0)return Lu;O0=1;const e=Ln();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)},Lu=t,Lu}var ju,A0;function _6(){if(A0)return ju;A0=1;const e=Ln(),t=qn();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)}},ju=r,ju}var Du={exports:{}},N0;function w6(){return N0||(N0=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,f,p,h,y,w,g;!i.empty();){l=i.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],y=f+h,w=a[u],g=typeof a[u]>"u",(g||w>y)&&(a[u]=y,i.push(u,y),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var b=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(b)}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})(Du)),Du.exports}var q0;function b6(){return q0||(q0=1,(function(e){const t=Ln(),r=g6(),n=y6(),o=v6(),s=_6(),a=E0(),i=qn(),l=w6();function c(b){return unescape(encodeURIComponent(b)).length}function u(b,v,m){const T=[];let k;for(;(k=b.exec(m))!==null;)T.push({data:k[0],index:k.index,mode:v,length:k[0].length});return T}function f(b){const v=u(a.NUMERIC,t.NUMERIC,b),m=u(a.ALPHANUMERIC,t.ALPHANUMERIC,b);let T,k;return i.isKanjiModeEnabled()?(T=u(a.BYTE,t.BYTE,b),k=u(a.KANJI,t.KANJI,b)):(T=u(a.BYTE_KANJI,t.BYTE,b),k=[]),v.concat(m,T,k).sort(function(S,$){return S.index-$.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function p(b,v){switch(v){case t.NUMERIC:return r.getBitsLength(b);case t.ALPHANUMERIC:return n.getBitsLength(b);case t.KANJI:return s.getBitsLength(b);case t.BYTE:return o.getBitsLength(b)}}function h(b){return b.reduce(function(v,m){const T=v.length-1>=0?v[v.length-1]:null;return T&&T.mode===m.mode?(v[v.length-1].data+=m.data,v):(v.push(m),v)},[])}function y(b){const v=[];for(let m=0;m<b.length;m++){const T=b[m];switch(T.mode){case t.NUMERIC:v.push([T,{data:T.data,mode:t.ALPHANUMERIC,length:T.length},{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.ALPHANUMERIC:v.push([T,{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.KANJI:v.push([T,{data:T.data,mode:t.BYTE,length:c(T.data)}]);break;case t.BYTE:v.push([{data:T.data,mode:t.BYTE,length:c(T.data)}])}}return v}function w(b,v){const m={},T={start:{}};let k=["start"];for(let _=0;_<b.length;_++){const S=b[_],$=[];for(let x=0;x<S.length;x++){const U=S[x],M=""+_+x;$.push(M),m[M]={node:U,lastCount:0},T[M]={};for(let O=0;O<k.length;O++){const A=k[O];m[A]&&m[A].node.mode===U.mode?(T[A][M]=p(m[A].lastCount+U.length,U.mode)-p(m[A].lastCount,U.mode),m[A].lastCount+=U.length):(m[A]&&(m[A].lastCount=U.length),T[A][M]=p(U.length,U.mode)+4+t.getCharCountIndicator(U.mode,v))}}k=$}for(let _=0;_<k.length;_++)T[k[_]].end=0;return{map:T,table:m}}function g(b,v){let m;const T=t.getBestModeForData(b);if(m=t.from(v,T),m!==t.BYTE&&m.bit<T.bit)throw new Error('"'+b+'" cannot be encoded with mode '+t.toString(m)+`.
46
- Suggested mode is: `+t.toString(T));switch(m===t.KANJI&&!i.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(b);case t.ALPHANUMERIC:return new n(b);case t.KANJI:return new s(b);case t.BYTE:return new o(b)}}e.fromArray=function(v){return v.reduce(function(m,T){return typeof T=="string"?m.push(g(T,null)):T.data&&m.push(g(T.data,T.mode)),m},[])},e.fromString=function(v,m){const T=f(v,i.isKanjiModeEnabled()),k=y(T),_=w(k,m),S=l.find_path(_.map,"start","end"),$=[];for(let x=1;x<S.length-1;x++)$.push(_.table[S[x]].node);return e.fromArray(h($))},e.rawSplit=function(v){return e.fromArray(f(v,i.isKanjiModeEnabled()))}})(Au)),Au}var L0;function k6(){if(L0)return wu;L0=1;const e=qn(),t=ku(),r=a6(),n=i6(),o=l6(),s=c6(),a=u6(),i=w0(),l=f6(),c=h6(),u=m6(),f=Ln(),p=b6();function h(_,S){const $=_.size,x=s.getPositions(S);for(let U=0;U<x.length;U++){const M=x[U][0],O=x[U][1];for(let A=-1;A<=7;A++)if(!(M+A<=-1||$<=M+A))for(let L=-1;L<=7;L++)O+L<=-1||$<=O+L||(A>=0&&A<=6&&(L===0||L===6)||L>=0&&L<=6&&(A===0||A===6)||A>=2&&A<=4&&L>=2&&L<=4?_.set(M+A,O+L,!0,!0):_.set(M+A,O+L,!1,!0))}}function y(_){const S=_.size;for(let $=8;$<S-8;$++){const x=$%2===0;_.set($,6,x,!0),_.set(6,$,x,!0)}}function w(_,S){const $=o.getPositions(S);for(let x=0;x<$.length;x++){const U=$[x][0],M=$[x][1];for(let O=-2;O<=2;O++)for(let A=-2;A<=2;A++)O===-2||O===2||A===-2||A===2||O===0&&A===0?_.set(U+O,M+A,!0,!0):_.set(U+O,M+A,!1,!0)}}function g(_,S){const $=_.size,x=c.getEncodedBits(S);let U,M,O;for(let A=0;A<18;A++)U=Math.floor(A/3),M=A%3+$-8-3,O=(x>>A&1)===1,_.set(U,M,O,!0),_.set(M,U,O,!0)}function b(_,S,$){const x=_.size,U=u.getEncodedBits(S,$);let M,O;for(M=0;M<15;M++)O=(U>>M&1)===1,M<6?_.set(M,8,O,!0):M<8?_.set(M+1,8,O,!0):_.set(x-15+M,8,O,!0),M<8?_.set(8,x-M-1,O,!0):M<9?_.set(8,15-M-1+1,O,!0):_.set(8,15-M-1,O,!0);_.set(x-8,8,1,!0)}function v(_,S){const $=_.size;let x=-1,U=$-1,M=7,O=0;for(let A=$-1;A>0;A-=2)for(A===6&&A--;;){for(let L=0;L<2;L++)if(!_.isReserved(U,A-L)){let Y=!1;O<S.length&&(Y=(S[O]>>>M&1)===1),_.set(U,A-L,Y),M--,M===-1&&(O++,M=7)}if(U+=x,U<0||$<=U){U-=x,x=-x;break}}}function m(_,S,$){const x=new r;$.forEach(function(L){x.put(L.mode.bit,4),x.put(L.getLength(),f.getCharCountIndicator(L.mode,_)),L.write(x)});const U=e.getSymbolTotalCodewords(_),M=i.getTotalCodewordsCount(_,S),O=(U-M)*8;for(x.getLengthInBits()+4<=O&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const A=(O-x.getLengthInBits())/8;for(let L=0;L<A;L++)x.put(L%2?17:236,8);return T(x,_,S)}function T(_,S,$){const x=e.getSymbolTotalCodewords(S),U=i.getTotalCodewordsCount(S,$),M=x-U,O=i.getBlocksCount(S,$),A=x%O,L=O-A,Y=Math.floor(x/O),J=Math.floor(M/O),de=J+1,K=Y-J,$e=new l(K);let Z=0;const N=new Array(O),H=new Array(O);let z=0;const I=new Uint8Array(_.buffer);for(let _e=0;_e<O;_e++){const xe=_e<L?J:de;N[_e]=I.slice(Z,Z+xe),H[_e]=$e.encode(N[_e]),Z+=xe,z=Math.max(z,xe)}const E=new Uint8Array(x);let V=0,te,Q;for(te=0;te<z;te++)for(Q=0;Q<O;Q++)te<N[Q].length&&(E[V++]=N[Q][te]);for(te=0;te<K;te++)for(Q=0;Q<O;Q++)E[V++]=H[Q][te];return E}function k(_,S,$,x){let U;if(Array.isArray(_))U=p.fromArray(_);else if(typeof _=="string"){let Y=S;if(!Y){const J=p.rawSplit(_);Y=c.getBestVersionForData(J,$)}U=p.fromString(_,Y||40)}else throw new Error("Invalid data");const M=c.getBestVersionForData(U,$);if(!M)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=M;else if(S<M)throw new Error(`
43
+ `&&n++}}return[t,r]}class Qm 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(Xm(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Xm(this),r)}}function HC(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function eu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(eu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${eu(e.cause)}`:e.message:`${e}`}function Xm(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var e0=e=>{throw TypeError(e)},tu=(e,t,r)=>t.has(e)||e0("Cannot "+r),je=(e,t,r)=>(tu(e,t,"read from private field"),r?r.call(e):t.get(e)),bt=(e,t,r)=>t.has(e)?e0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ot=(e,t,r,n)=>(tu(e,t,"write to private field"),t.set(e,r),r),Xr=(e,t,r)=>(tu(e,t,"access private method"),r),Jt,Vn,bo,Li,ji,Es,ko,$s,wn,To,Co,So,Rs,kr,ru,nu,ou,t0,su,au,Ps,iu,lu;class Di extends EventTarget{constructor(t,r){var n,o;super(),bt(this,kr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,bt(this,Jt),bt(this,Vn),bt(this,bo),bt(this,Li),bt(this,ji),bt(this,Es),bt(this,ko),bt(this,$s,null),bt(this,wn),bt(this,To),bt(this,Co,null),bt(this,So,null),bt(this,Rs,null),bt(this,nu,async s=>{var a;je(this,To).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){Xr(this,kr,Ps).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?ot(this,bo,new URL(s.url)):ot(this,bo,void 0),c!==200){Xr(this,kr,Ps).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Xr(this,kr,Ps).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(je(this,Jt)===this.CLOSED)return;ot(this,Jt,this.OPEN);const h=new Event("open");if((a=je(this,Rs))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){Xr(this,kr,Ps).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&&je(this,To).feed(p.decode(y,{stream:!_})),_&&(g=!1,je(this,To).reset(),Xr(this,kr,iu).call(this))}while(g)}),bt(this,ou,s=>{ot(this,wn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Xr(this,kr,iu).call(this,eu(s))}),bt(this,su,s=>{typeof s.id=="string"&&ot(this,$s,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:je(this,bo)?je(this,bo).origin:je(this,Vn).origin,lastEventId:s.id||""});je(this,So)&&(!s.event||s.event==="message")&&je(this,So).call(this,a),this.dispatchEvent(a)}),bt(this,au,s=>{ot(this,Es,s)}),bt(this,lu,()=>{ot(this,ko,void 0),je(this,Jt)===this.CONNECTING&&Xr(this,kr,ru).call(this)});try{if(t instanceof URL)ot(this,Vn,t);else if(typeof t=="string")ot(this,Vn,new URL(t,BC()));else throw new Error("Invalid URL")}catch{throw HC("An invalid or illegal string was specified")}ot(this,To,Ym({onEvent:je(this,su),onRetry:je(this,au)})),ot(this,Jt,this.CONNECTING),ot(this,Es,3e3),ot(this,ji,(n=r?.fetch)!=null?n:globalThis.fetch),ot(this,Li,(o=r?.withCredentials)!=null?o:!1),Xr(this,kr,ru).call(this)}get readyState(){return je(this,Jt)}get url(){return je(this,Vn).href}get withCredentials(){return je(this,Li)}get onerror(){return je(this,Co)}set onerror(t){ot(this,Co,t)}get onmessage(){return je(this,So)}set onmessage(t){ot(this,So,t)}get onopen(){return je(this,Rs)}set onopen(t){ot(this,Rs,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(){je(this,ko)&&clearTimeout(je(this,ko)),je(this,Jt)!==this.CLOSED&&(je(this,wn)&&je(this,wn).abort(),ot(this,Jt,this.CLOSED),ot(this,wn,void 0))}}Jt=new WeakMap,Vn=new WeakMap,bo=new WeakMap,Li=new WeakMap,ji=new WeakMap,Es=new WeakMap,ko=new WeakMap,$s=new WeakMap,wn=new WeakMap,To=new WeakMap,Co=new WeakMap,So=new WeakMap,Rs=new WeakMap,kr=new WeakSet,ru=function(){ot(this,Jt,this.CONNECTING),ot(this,wn,new AbortController),je(this,ji)(je(this,Vn),Xr(this,kr,t0).call(this)).then(je(this,nu)).catch(je(this,ou))},nu=new WeakMap,ou=new WeakMap,t0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...je(this,$s)?{"Last-Event-ID":je(this,$s)}:void 0},cache:"no-store",signal:(e=je(this,wn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},su=new WeakMap,au=new WeakMap,Ps=function(e,t){var r;je(this,Jt)!==this.CLOSED&&ot(this,Jt,this.CLOSED);const n=new Qm("error",{code:t,message:e});(r=je(this,Co))==null||r.call(this,n),this.dispatchEvent(n)},iu=function(e,t){var r;if(je(this,Jt)===this.CLOSED)return;ot(this,Jt,this.CONNECTING);const n=new Qm("error",{code:t,message:e});(r=je(this,Co))==null||r.call(this,n),this.dispatchEvent(n),ot(this,ko,setTimeout(je(this,lu),je(this,Es)))},lu=new WeakMap,Di.CONNECTING=0,Di.OPEN=1,Di.CLOSED=2;function BC(){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 Ui(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function r0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ui(t.headers),...Ui(n.headers)}:t.headers};return e(r,o)}:e}let cu;cu=globalThis.crypto;async function JC(e){return(await cu).getRandomValues(new Uint8Array(e))}async function WC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await JC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function GC(e){return await WC(e)}async function KC(e){const t=await(await cu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function n0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await GC(e),r=await KC(t);return{code_verifier:t,code_challenge:r}}const Pt=z4().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xh.custom,message:"URL must be parseable",fatal:!0}),Kf}).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"}),YC=ct({resource:d().url(),authorization_servers:q(Pt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}),o0=ct({issuer:d(),authorization_endpoint:Pt,token_endpoint:Pt,registration_endpoint:Pt.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:Pt.optional(),revocation_endpoint:Pt.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:he().optional()}),QC=ct({issuer:d(),authorization_endpoint:Pt,token_endpoint:Pt,userinfo_endpoint:Pt.optional(),jwks_uri:Pt,registration_endpoint:Pt.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:he().optional(),request_parameter_supported:he().optional(),request_uri_parameter_supported:he().optional(),require_request_uri_registration:he().optional(),op_policy_uri:Pt.optional(),op_tos_uri:Pt.optional(),client_id_metadata_document_supported:he().optional()}),XC=T({...QC.shape,...o0.pick({code_challenge_methods_supported:!0}).shape}),eS=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:em().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),tS=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),s0=Pt.optional().or(R("").transform(()=>{})),rS=T({redirect_uris:q(Pt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Pt.optional(),logo_uri:s0,scope:d().optional(),contacts:q(d()).optional(),tos_uri:s0,policy_uri:d().optional(),jwks_uri:Pt.optional(),jwks:kt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),nS=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),oS=rS.merge(nS);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function sS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function aS({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 Tt 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 uu extends Tt{}uu.errorCode="invalid_request";let zi=class extends Tt{};zi.errorCode="invalid_client";let Zi=class extends Tt{};Zi.errorCode="invalid_grant";let Fi=class extends Tt{};Fi.errorCode="unauthorized_client";class du extends Tt{}du.errorCode="unsupported_grant_type";class pu extends Tt{}pu.errorCode="invalid_scope";class fu extends Tt{}fu.errorCode="access_denied";let Io=class extends Tt{};Io.errorCode="server_error";class hu extends Tt{}hu.errorCode="temporarily_unavailable";class mu extends Tt{}mu.errorCode="unsupported_response_type";class gu extends Tt{}gu.errorCode="unsupported_token_type";class yu extends Tt{}yu.errorCode="invalid_token";class vu extends Tt{}vu.errorCode="method_not_allowed";class _u extends Tt{}_u.errorCode="too_many_requests";class Vi extends Tt{}Vi.errorCode="invalid_client_metadata";class wu extends Tt{}wu.errorCode="insufficient_scope";class bu extends Tt{}bu.errorCode="invalid_target";const iS={[uu.errorCode]:uu,[zi.errorCode]:zi,[Zi.errorCode]:Zi,[Fi.errorCode]:Fi,[du.errorCode]:du,[pu.errorCode]:pu,[fu.errorCode]:fu,[Io.errorCode]:Io,[hu.errorCode]:hu,[mu.errorCode]:mu,[gu.errorCode]:gu,[yu.errorCode]:yu,[vu.errorCode]:vu,[_u.errorCode]:_u,[Vi.errorCode]:Vi,[wu.errorCode]:wu,[bu.errorCode]:bu};let lr=class extends Error{constructor(t){super(t??"Unauthorized")}};function lS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ku="code",Tu="S256";function cS(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&&lS(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 uS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":dS(o,s,r);return;case"client_secret_post":pS(o,s,n);return;case"none":fS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function dS(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 pS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function fS(e,t){t.set("client_id",e)}async function a0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=tS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=iS[o]||Io;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Io(o)}}async function Hn(e,t){try{return await Cu(e,t)}catch(r){if(r instanceof zi||r instanceof Fi)return await e.invalidateCredentials?.("all"),await Cu(e,t);if(r instanceof Zi)return await e.invalidateCredentials?.("tokens"),await Cu(e,t);throw r}}async function Cu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await gS(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 mS(t,e,a),c=await bS(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&&!hS(w))throw new Vi(`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 IS(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 SS(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 CS(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 Tt)||y instanceof Io))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:_}=await kS(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 hS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function mS(e,t,r){const n=sS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!aS({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 Hi(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Su(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=Su(e,"scope")||void 0,i=Su(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Su(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 gS(e,t,r=fetch){const n=await _S(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 YC.parse(await n.json())}async function Iu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Iu(e,void 0,r):void 0;throw n}}function yS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function i0(e,t,r=fetch){return await Iu(e,{"MCP-Protocol-Version":t},r)}function vS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function _S(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ys;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=yS(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await i0(a,s,r);if(!n?.metadataUrl&&vS(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await i0(l,s,r)}return i}function wS(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 bS(e,{fetchFn:t=fetch,protocolVersion:r=ys}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=wS(e);for(const{url:s,type:a}of o){const i=await Iu(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"?o0.parse(await i.json()):XC.parse(await i.json())}}}async function kS(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(ku))throw new Error(`Incompatible auth server: does not support response type ${ku}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Tu))throw new Error(`Incompatible auth server: does not support code challenge method ${Tu}`)}else i=new URL("/authorize",e);const l=await n0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",ku),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Tu),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 TS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function l0(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=cS(n,u);uS(h,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await a0(c);return eS.parse(await c.json())}async function CS(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 l0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function SS(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=TS(o,c,e.redirectUrl)}const l=await e.clientInformation();return l0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function IS(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 a0(s);return oS.parse(await s.json())}class xS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ms{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=r0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new lr("No auth provider");let t;try{t=await Hn(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=Ui(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 Di(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}=Hi(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 xS(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=Qr.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 Hn(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}=Hi(o);if(this._resourceMetadataUrl=a,this._scope=i,await Hn(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 xo extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Ym({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 ES={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 Os{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=r0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??ES}async _authThenStart(){if(!this._authProvider)throw new lr("No auth provider");let t;try{t=await Hn(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=Ui(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 xo({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 _=Qr.parse(JSON.parse(f.data));_s(_)&&(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 Hn(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:mc(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}=Hi(i);if(this._resourceMetadataUrl=f,this._scope=g,await Hn(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:_}=Hi(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 Hn(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(),Vk(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=>Qr.parse(g)):[Qr.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 $S="mcp";class c0{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,$S),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=Qr.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 bn=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())}})(Bi,-118057+3521*-35+-2099*-233);const u0=()=>{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}},RS=(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)},PS=(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 Ns{constructor(t){this._port=t}async[bn(401)](){const t=bn,r=bn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=Qr.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=bn,o=bn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class xu extends Ns{constructor(t,r=u0()){const n=bn,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)](RS,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class Eu extends Ns{constructor(t,r=u0()){const n=bn,o=bn,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)](PS,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 Bi(){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 Bi=function(){return e},Bi()}function er(e,t){const r=Bi();return er=function(n,o){return n=n-(17227+1*-16844),r[n]},er(e,t)}const MS=()=>{const e=new MessageChannel;return[new Ns(e.port1),new Ns(e.port2)]};(function(e,t){const r=Ke,n=Ke,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())}})(Ji,-411935*1+228107+208149*2);const OS=async(e,t,r)=>{var n;const o=Ke,s=Ke,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))},NS=async(e,t,r)=>{var n;const o=Ke,s=Ke,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,Bc);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,h=await t.request(g,Oi);break;case i[o(487)]:const _={};_.method=c,_[s(446)]=u,h=await t.request(_,Ss);break;case i.ypHTC:const y={};y.method=c,h=await t.request(y,_n);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 Ke(e,t){const r=Ji();return Ke=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ke(e,t)}const AS=(e,t)=>{const r=Ke,n=Ke,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)](OS,e,t,a)}catch(w){const{code:v,message:m,data:C}=w;try{if(v){const k={};k[g(485)]=v,k[f(422)]=m,k.data=C;const b={};b[g(448)]=k,b.jsonrpc=o[f(417)],b.id=_,await((l=e?.transport)==null?void 0:l[g(460)](b))}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)}}}},qS=(e,t)=>{const r=Ke,n=Ke,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)}}},LS=(e,t)=>async r=>{var n,o,s,a,i;const l=Ke,c=Ke,u={TJhyV:function(h,p,f,g){return h(p,f,g)},MMNTY:l(465)};try{return await u.TJhyV(NS,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,_)}}},jS=(e,t)=>async r=>{var n,o,s;const a=Ke,i=Ke,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 Ji(){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 Ji=function(){return e},Ji()}const DS=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Ke,u=Ke,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)}}},$u=()=>{const e=Ke,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ke;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=Ke,u=Ke;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ke,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Ke;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},US=e=>{const t=Ke,r=Ke,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)]($u);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)]($u);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($u);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},zS=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ke,o=Ke,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(US,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)})},ZS=en;(function(e,t){const r=en,n=en,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())}})(Wi,995159+-6*-266138+-1619768);const FS=()=>{const e=en,t=en,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)})},VS=e=>{const t=en,r=en,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)]("")},kn={};kn[ZS(211)]=FS,kn.randomBytes=VS;function en(e,t){const r=Wi();return en=function(n,o){return n=n-(-7373+7187*1+395),r[n]},en(e,t)}function Wi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Wi=function(){return e},Wi()}function tn(e,t){const r=Gi();return tn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},tn(e,t)}const Tr=tn,As=tn;(function(e,t){const r=tn,n=tn,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())}})(Gi,-4*308317+753182*2+658196);const HS=(e,t)=>{const r=tn,n=tn,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)](AS,e,t),qS(e,t);const s=o[n(283)](LS,t,e),a=o[n(294)](DS,t,e),i=o[r(277)](jS,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)}},Ru=(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,Ms)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[tn(295)])==null||i.close()})),n.Qalmc(HS,e,t)},s={};s.afterInit=o,n.Qalmc(zS,t,s)},d0=(e,t=kn[Tr(299)]())=>{const r=Tr,n=Tr,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},p0=(e,t=kn[Tr(299)]())=>{const r=As,n=Tr,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},Pu=async(e,t,r)=>{const n=Tr,o=Tr,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 Pu(e,t,r)}else throw i}},f0=(e,t)=>{const r=As,n=As,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 Gi(){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 Gi=function(){return e},Gi()}const BS=async e=>{const t=As,r=Tr,n={GKDjq:function(I,L,$){return I(L,$)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(I){return I()},kdowC:function(I,L,$,N){return I(L,$,N)},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||kn[r(299)](),_=n[t(289)](d0,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 C={};C[t(251)]=v;const k=new xs(m,C),b=()=>new Ms(new URL(s),f);let S=n[t(282)](b);if(l){const I=f0(l,h);S=await n[t(263)](Pu,k,I,b)}else await k.connect(S);Ru(k,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const x={};return x.transport=S,x.sessionId=S[r(286)],x},JS=async e=>{const t=As,r=Tr,n={wfHUn:function(I,L,$){return I(L,$)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(I){return I()},PdsSn:function(I,L,$,N){return I(L,$,N)}},{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||kn.randomUUID(),_=n[r(272)](p0,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 C={};C.capabilities=v;const k=new xs(m,C),b=()=>new Os(new URL(s),f);let S=n.rSiEq(b);if(l){const I=n[t(272)](f0,l,h);S=await n[t(296)](Pu,k,I,b)}else await k[t(260)](S);n.PdsSn(Ru,k,o,S);const x={};return x.transport=S,x[r(286)]=S[r(286)],x},WS=async e=>{const t=Tr,r=Tr,n={eZwNI:function(w,v,m,C){return w(v,m,C)}},{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 xs(h,p),g=i||kn[r(299)](),_=new c0(new URL(s+"?sessionId="+g+r(265)+a));await f.connect(_),n[t(259)](Ru,f,o,_);const y={};return y.transport=_,y[r(286)]=g,y},Tn=Cr,qs=Cr;(function(e,t){const r=Cr,n=Cr,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())}})(Ki,1297719+-42747*-22+-1289197);function Cr(e,t){const r=Ki();return Cr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Cr(e,t)}const GS=()=>kn.randomBytes(-8746+-382*-23);class KS{constructor(t){const r=Cr,n=Cr,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(GS),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=Cr,c=Cr,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[Tn(191)](t,r){const n=Tn,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=Cr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Tn(206)]}get[qs(190)](){return this._clientMetadata}[Tn(213)](){return this[Tn(197)]}[qs(218)](){return this[qs(200)]}[Tn(194)](t){this._clientInformation=t}tokens(){return this[qs(210)]}saveTokens(t){const r=qs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Tn(212)](){const t=Tn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Ki(){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 Ki=function(){return e},Ki()}(function(e,t){for(var r=Qi,n=Qi,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())}})(Yi,262*-2438+1346066*-1+2*1373311);function Yi(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Yi=function(){return e},Yi()}function Qi(e,t){var r=Yi();return Qi=function(n,o){n=n-287;var s=r[n];return s},Qi(e,t)}class YS{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 QS extends zm{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ri.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 Jm,this.setRequestHandler(im,n=>this._oninitialize(n)),this.setNotificationHandler(_c,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Pi,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=Ri.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new YS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fm(this._capabilities,t)}setRequestHandler(t,r){const o=wo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(vr(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=_r($i,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new ae(ue.InvalidParams,`Invalid tools/call request: ${g}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const g=_r(go,p);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new ae(ue.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}const f=_r(vo,p);if(!f.success){const g=f.error instanceof Error?f.error.message:String(f.error);throw new ae(ue.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){Gm(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Wm(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:tm.includes(r)?r:ys,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"},_n)}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},Fc,r):this.request({method:"sampling/createMessage",params:t},Oi,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},Ss,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},Ss,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new ae(ue.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof ae?a:new ae(ue.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},Bc,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 Mu=Symbol.for("mcp.completable");function XS(e,t){return Object.defineProperty(e,Mu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function h0(e){return!!e&&typeof e=="object"&&Mu in e}function e6(e){return e[Mu]?.complete}var m0;(function(e){e.Completable="McpCompletable"})(m0||(m0={}));const g0=1e6,Ou=1e6,y0=1e4,t6=1e6;class rn{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){rn.validateLength(t,g0,"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>y0)throw new Error(`Template contains too many expressions (max ${y0})`);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)rn.validateLength(p,Ou,"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 rn.validateLength(t,Ou,"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)rn.validateLength(s,Ou,"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){rn.validateLength(t,g0,"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+="$",rn.validateLength(r,t6,"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 r6=/^[A-Za-z0-9._-]{1,128}$/;function n6(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"),!r6.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 o6(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 v0(e){const t=n6(e);return o6(e,t.warnings),t.isValid}class s6{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 _0{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 QS(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new s6(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Cn(Uc)),this.server.assertCanSetRequestHandler(Cn($i)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Uc,()=>({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=Is(r.inputSchema);return o?jm(o,{strictUnions:!0,pipeStrategy:"input"}):i6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=Is(r.outputSchema);o&&(n.outputSchema=jm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler($i,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new ae(ue.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ae(ue.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 ae(ue.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new ae(ue.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 ae&&n.code===ue.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=Is(t.inputSchema)??t.inputSchema,a=await Jc(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Wc(i);throw new ae(ue.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 ae(ue.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=Is(t.outputSchema),s=await Jc(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Wc(a);throw new ae(ue.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 ae(ue.InternalError,`Task ${l} not found during polling`);c=h}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Cn(Hc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Hc,async t=>{switch(t.params.ref.type){case"ref/prompt":return ZT(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return FT(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ae(ue.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new ae(ue.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ae(ue.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ls;const s=wo(n.argsSchema)?.[t.params.argument.name];if(!h0(s))return Ls;const a=e6(s);if(!a)return Ls;const i=await a(t.params.argument.value,t.params.context);return k0(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 Ls;throw new ae(ue.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Ls;const s=await o(t.params.argument.value,t.params.context);return k0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Cn(Ei)),this.server.assertCanSetRequestHandler(Cn($c)),this.server.assertCanSetRequestHandler(Cn(Pc)),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($c,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Pc,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ae(ue.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 ae(ue.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Cn(Oc)),this.server.assertCanSetRequestHandler(Cn(Nc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?c6(r.argsSchema):void 0}))})),this.server.setRequestHandler(Nc,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new ae(ue.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ae(ue.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=Is(n.argsSchema),s=await Jc(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Wc(l);throw new ae(ue.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:_o(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=_o(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 yr?l._def?.innerType:l;return h0(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){v0(t);const u={title:r,description:n,inputSchema:b0(o),outputSchema:b0(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"&&v0(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=_o(h.paramsSchema)),typeof h.outputSchema<"u"&&(u.outputSchema=_o(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];Nu(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Nu(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 a6{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new rn(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const i6={type:"object",properties:{}};function w0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function l6(e){return"_def"in e||"_zod"in e||w0(e)}function Nu(e){return typeof e!="object"||e===null||l6(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(w0)}function b0(e){if(e)return Nu(e)?_o(e):e}function c6(e){const t=wo(e);return t?Object.entries(t).map(([r,n])=>{const o=WT(n),s=GT(n);return{name:r,description:o,required:!s}}):[]}function Cn(e){const r=wo(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 k0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Ls={completion:{values:[],hasMore:!1}};function u6(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class js{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new js,r=new js;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 d6{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 _0(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(Pi,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(gm,t)}onUnsubscribe(t){this.server.server.setRequestHandler(ym,t)}onSetLogLevel(t){this.server.server.setRequestHandler(Pi,t)}onListResources(t){this.server.server.setRequestHandler(Ei,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(Im,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const p6=(e,t)=>new Eu(e,t),f6=()=>MS(),h6=e=>e instanceof Eu,m6=e=>e instanceof _0;class T0{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new xs(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 BS(u):s==="socket"?await WS(u):await JS(u);f.onerror=async _=>{i?.(_)},h={transport:f,sessionId:g}})(),h}const l=new URL(r);let c;if(s==="channel"&&(c=new xu(r),await this.client.connect(c)),s==="sse"){const u=d0(n,o);c=new Ms(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new c0(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=p0(n,o);c=new Os(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,vo,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(Vc,t)}onCreateMessage(t){this.client.setRequestHandler(Zc,t)}onListRoots(t){this.client.setRequestHandler(Sm,t)}onToolListChanged(t){this.client.setNotificationHandler(zc,t)}onPromptListChanged(t){this.client.setNotificationHandler(Dc,t)}onResourceListChanged(t){this.client.setNotificationHandler(Mc,t)}onResourceUpdated(t){this.client.setNotificationHandler(vm,t)}onLoggingMessage(t){this.client.setNotificationHandler(Tm,t)}async onPagehide(t){t.persisted||(C0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const g6=(e,t)=>new Ms(e,t),y6=(e,t)=>new Os(e,t),v6=(e,t)=>new xu(e,t),_6=e=>e instanceof Ms,C0=e=>e instanceof Os,w6=e=>e instanceof xu,b6=e=>e instanceof xs,$o=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},S0=(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)},Au=(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})},qu=(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 I0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=qu("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Qr.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];Au("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 x0=()=>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 k6{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||x0(),this._messageListener1=S0("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=S0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=Qr.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&$o("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】 已关闭,无法发送消息"),$o("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&$o("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{$o("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 T6{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||x0(),this.tabId=r,qu("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】 已关闭,无法重新启动");qu("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=Qr.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&$o("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),Au("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&t.result?.content&&$o("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,Au("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 Ro={},Lu,E0;function C6(){return E0||(E0=1,Lu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Lu}var ju={},Sn={},$0;function Bn(){if($0)return Sn;$0=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 Sn.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},Sn.getSymbolTotalCodewords=function(n){return t[n]},Sn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Sn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Sn.isKanjiModeEnabled=function(){return typeof e<"u"},Sn.toSJIS=function(n){return e(n)},Sn}var Du={},R0;function Uu(){return R0||(R0=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}}})(Du)),Du}var zu,P0;function S6(){if(P0)return zu;P0=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++}},zu=e,zu}var Zu,M0;function I6(){if(M0)return Zu;M0=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 Fu={},O0;function x6(){return O0||(O0=1,(function(e){const t=Bn().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}})(Fu)),Fu}var Vu={},N0;function E6(){if(N0)return Vu;N0=1;const e=Bn().getSymbolSize,t=7;return Vu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Vu}var Hu={},A0;function $6(){return A0||(A0=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}})(Hu)),Hu}var Xi={},q0;function L0(){if(q0)return Xi;q0=1;const e=Uu(),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 Xi.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}},Xi.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}},Xi}var Bu={},Ds={},j0;function R6(){if(j0)return Ds;j0=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]})(),Ds.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Ds.exp=function(n){return e[n]},Ds.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Ds}var D0;function P6(){return D0||(D0=1,(function(e){const t=R6();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}})(Bu)),Bu}var Ju,U0;function M6(){if(U0)return Ju;U0=1;const e=P6();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},Ju=t,Ju}var Wu={},Gu={},Ku={},z0;function Z0(){return z0||(z0=1,Ku.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ku}var Lr={},F0;function V0(){if(F0)return Lr;F0=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
+ ]))+`;Lr.KANJI=new RegExp(r,"g"),Lr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Lr.BYTE=new RegExp(n,"g"),Lr.NUMERIC=new RegExp(e,"g"),Lr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Lr.testKanji=function(l){return o.test(l)},Lr.testNumeric=function(l){return s.test(l)},Lr.testAlphanumeric=function(l){return a.test(l)},Lr}var H0;function Jn(){return H0||(H0=1,(function(e){const t=Z0(),r=V0();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}}})(Gu)),Gu}var B0;function O6(){return B0||(B0=1,(function(e){const t=Bn(),r=L0(),n=Uu(),o=Jn(),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}})(Wu)),Wu}var Yu={},J0;function N6(){if(J0)return Yu;J0=1;const e=Bn(),t=1335,r=21522,n=e.getBCHDigit(t);return Yu.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},Yu}var Qu={},Xu,W0;function A6(){if(W0)return Xu;W0=1;const e=Jn();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))},Xu=t,Xu}var ed,G0;function q6(){if(G0)return ed;G0=1;const e=Jn(),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)},ed=r,ed}var td,K0;function L6(){if(K0)return td;K0=1;const e=Jn();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)},td=t,td}var rd,Y0;function j6(){if(Y0)return rd;Y0=1;const e=Jn(),t=Bn();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)}},rd=r,rd}var nd={exports:{}},Q0;function D6(){return Q0||(Q0=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})(nd)),nd.exports}var X0;function U6(){return X0||(X0=1,(function(e){const t=Jn(),r=A6(),n=q6(),o=L6(),s=j6(),a=V0(),i=Bn(),l=D6();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,v,m){const C=[];let k;for(;(k=w.exec(m))!==null;)C.push({data:k[0],index:k.index,mode:v,length:k[0].length});return C}function h(w){const v=u(a.NUMERIC,t.NUMERIC,w),m=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let C,k;return i.isKanjiModeEnabled()?(C=u(a.BYTE,t.BYTE,w),k=u(a.KANJI,t.KANJI,w)):(C=u(a.BYTE_KANJI,t.BYTE,w),k=[]),v.concat(m,C,k).sort(function(S,x){return S.index-x.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.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 C=v.length-1>=0?v[v.length-1]:null;return C&&C.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 C=w[m];switch(C.mode){case t.NUMERIC:v.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:v.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:v.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:v.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return v}function _(w,v){const m={},C={start:{}};let k=["start"];for(let b=0;b<w.length;b++){const S=w[b],x=[];for(let I=0;I<S.length;I++){const L=S[I],$=""+b+I;x.push($),m[$]={node:L,lastCount:0},C[$]={};for(let N=0;N<k.length;N++){const A=k[N];m[A]&&m[A].node.mode===L.mode?(C[A][$]=p(m[A].lastCount+L.length,L.mode)-p(m[A].lastCount,L.mode),m[A].lastCount+=L.length):(m[A]&&(m[A].lastCount=L.length),C[A][$]=p(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,v))}}k=x}for(let b=0;b<k.length;b++)C[k[b]].end=0;return{map:C,table:m}}function y(w,v){let m;const C=t.getBestModeForData(w);if(m=t.from(v,C),m!==t.BYTE&&m.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
46
+ Suggested mode is: `+t.toString(C));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,C){return typeof C=="string"?m.push(y(C,null)):C.data&&m.push(y(C.data,C.mode)),m},[])},e.fromString=function(v,m){const C=h(v,i.isKanjiModeEnabled()),k=g(C),b=_(k,m),S=l.find_path(b.map,"start","end"),x=[];for(let I=1;I<S.length-1;I++)x.push(b.table[S[I]].node);return e.fromArray(f(x))},e.rawSplit=function(v){return e.fromArray(h(v,i.isKanjiModeEnabled()))}})(Qu)),Qu}var e2;function z6(){if(e2)return ju;e2=1;const e=Bn(),t=Uu(),r=S6(),n=I6(),o=x6(),s=E6(),a=$6(),i=L0(),l=M6(),c=O6(),u=N6(),h=Jn(),p=U6();function f(b,S){const x=b.size,I=s.getPositions(S);for(let L=0;L<I.length;L++){const $=I[L][0],N=I[L][1];for(let A=-1;A<=7;A++)if(!($+A<=-1||x<=$+A))for(let U=-1;U<=7;U++)N+U<=-1||x<=N+U||(A>=0&&A<=6&&(U===0||U===6)||U>=0&&U<=6&&(A===0||A===6)||A>=2&&A<=4&&U>=2&&U<=4?b.set($+A,N+U,!0,!0):b.set($+A,N+U,!1,!0))}}function g(b){const S=b.size;for(let x=8;x<S-8;x++){const I=x%2===0;b.set(x,6,I,!0),b.set(6,x,I,!0)}}function _(b,S){const x=o.getPositions(S);for(let I=0;I<x.length;I++){const L=x[I][0],$=x[I][1];for(let N=-2;N<=2;N++)for(let A=-2;A<=2;A++)N===-2||N===2||A===-2||A===2||N===0&&A===0?b.set(L+N,$+A,!0,!0):b.set(L+N,$+A,!1,!0)}}function y(b,S){const x=b.size,I=c.getEncodedBits(S);let L,$,N;for(let A=0;A<18;A++)L=Math.floor(A/3),$=A%3+x-8-3,N=(I>>A&1)===1,b.set(L,$,N,!0),b.set($,L,N,!0)}function w(b,S,x){const I=b.size,L=u.getEncodedBits(S,x);let $,N;for($=0;$<15;$++)N=(L>>$&1)===1,$<6?b.set($,8,N,!0):$<8?b.set($+1,8,N,!0):b.set(I-15+$,8,N,!0),$<8?b.set(8,I-$-1,N,!0):$<9?b.set(8,15-$-1+1,N,!0):b.set(8,15-$-1,N,!0);b.set(I-8,8,1,!0)}function v(b,S){const x=b.size;let I=-1,L=x-1,$=7,N=0;for(let A=x-1;A>0;A-=2)for(A===6&&A--;;){for(let U=0;U<2;U++)if(!b.isReserved(L,A-U)){let V=!1;N<S.length&&(V=(S[N]>>>$&1)===1),b.set(L,A-U,V),$--,$===-1&&(N++,$=7)}if(L+=I,L<0||x<=L){L-=I,I=-I;break}}}function m(b,S,x){const I=new r;x.forEach(function(U){I.put(U.mode.bit,4),I.put(U.getLength(),h.getCharCountIndicator(U.mode,b)),U.write(I)});const L=e.getSymbolTotalCodewords(b),$=i.getTotalCodewordsCount(b,S),N=(L-$)*8;for(I.getLengthInBits()+4<=N&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const A=(N-I.getLengthInBits())/8;for(let U=0;U<A;U++)I.put(U%2?17:236,8);return C(I,b,S)}function C(b,S,x){const I=e.getSymbolTotalCodewords(S),L=i.getTotalCodewordsCount(S,x),$=I-L,N=i.getBlocksCount(S,x),A=I%N,U=N-A,V=Math.floor(I/N),Q=Math.floor($/N),_e=Q+1,te=V-Q,ge=new l(te);let H=0;const M=new Array(N),B=new Array(N);let Z=0;const E=new Uint8Array(b.buffer);for(let ie=0;ie<N;ie++){const Ie=ie<U?Q:_e;M[ie]=E.slice(H,H+Ie),B[ie]=ge.encode(M[ie]),H+=Ie,Z=Math.max(Z,Ie)}const O=new Uint8Array(I);let D=0,G,re;for(G=0;G<Z;G++)for(re=0;re<N;re++)G<M[re].length&&(O[D++]=M[re][G]);for(G=0;G<te;G++)for(re=0;re<N;re++)O[D++]=B[re][G];return O}function k(b,S,x,I){let L;if(Array.isArray(b))L=p.fromArray(b);else if(typeof b=="string"){let V=S;if(!V){const Q=p.rawSplit(b);V=c.getBestVersionForData(Q,x)}L=p.fromString(b,V||40)}else throw new Error("Invalid data");const $=c.getBestVersionForData(L,x);if(!$)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=$;else if(S<$)throw new Error(`
47
47
  The chosen QR Code version cannot contain this amount of data.
48
- Minimum version required to store current data is: `+M+`.
49
- `);const O=m(S,$,U),A=e.getSymbolSize(S),L=new n(A);return h(L,S),y(L),w(L,S),b(L,$,0),S>=7&&g(L,S),v(L,O),isNaN(x)&&(x=a.getBestMask(L,b.bind(null,L,$))),a.applyMask(x,L),b(L,$,x),{modules:L,version:S,errorCorrectionLevel:$,maskPattern:x,segments:U}}return wu.create=function(S,$){if(typeof S>"u"||S==="")throw new Error("No input text");let x=t.M,U,M;return typeof $<"u"&&(x=t.from($.errorCorrectionLevel,t.M),U=c.from($.version),M=a.from($.maskPattern),$.toSJISFunc&&e.setToSJISFunction($.toSJISFunc)),k(S,U,x,M)},wu}var Uu={},zu={},j0;function D0(){return j0||(j0=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,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let y=(p*c+h)*4,w=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const g=Math.floor((p-u)/l),b=Math.floor((h-u)/l);w=f[i[g*a+b]?1:0]}n[y++]=w.r,n[y++]=w.g,n[y++]=w.b,n[y]=w.a}}})(zu)),zu}var U0;function T6(){return U0||(U0=1,(function(e){const t=D0();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),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.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",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(Uu)),Uu}var Zu={},z0;function C6(){if(z0)return Zu;z0=1;const e=D0();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 f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(i+=c?r("M",p+a,.5+h+a):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(i+=r("h",u),u=0)):l++}return i}return Zu.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',y='viewBox="0 0 '+f+" "+f+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+y+' shape-rendering="crispEdges">'+p+h+`</svg>
50
- `;return typeof i=="function"&&i(null,g),g},Zu}var Z0;function S6(){if(Z0)return ko;Z0=1;const e=s6(),t=k6(),r=T6(),n=C6();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=i,i=a,a=l=void 0):f===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(i=a,a=l=void 0):f===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(h,y){try{const w=t.create(i,l);h(s(w,a,l))}catch(w){y(w)}})}try{const h=t.create(i,l);c(null,s(h,a,l))}catch(h){c(h)}}return ko.create=t.create,ko.toCanvas=o.bind(null,r.render),ko.toDataURL=o.bind(null,r.renderToDataURL),ko.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),ko}var I6=S6();const F0=kn(I6);class V0{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 F0.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return F0.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const E6={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class x6{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={...E6,...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=`
48
+ Minimum version required to store current data is: `+$+`.
49
+ `);const N=m(S,x,L),A=e.getSymbolSize(S),U=new n(A);return f(U,S),g(U),_(U,S),w(U,x,0),S>=7&&y(U,S),v(U,N),isNaN(I)&&(I=a.getBestMask(U,w.bind(null,U,x))),a.applyMask(I,U),w(U,x,I),{modules:U,version:S,errorCorrectionLevel:x,maskPattern:I,segments:L}}return ju.create=function(S,x){if(typeof S>"u"||S==="")throw new Error("No input text");let I=t.M,L,$;return typeof x<"u"&&(I=t.from(x.errorCorrectionLevel,t.M),L=c.from(x.version),$=a.from(x.maskPattern),x.toSJISFunc&&e.setToSJISFunction(x.toSJISFunc)),k(S,L,I,$)},ju}var od={},sd={},t2;function r2(){return t2||(t2=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}}})(sd)),sd}var n2;function Z6(){return n2||(n2=1,(function(e){const t=r2();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)}})(od)),od}var ad={},o2;function F6(){if(o2)return ad;o2=1;const e=r2();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 ad.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},ad}var s2;function V6(){if(s2)return Ro;s2=1;const e=C6(),t=z6(),r=Z6(),n=F6();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 Ro.create=t.create,Ro.toCanvas=o.bind(null,r.render),Ro.toDataURL=o.bind(null,r.renderToDataURL),Ro.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),Ro}var H6=V6();const a2=Mn(H6);class i2{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 a2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return a2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const B6={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class J6{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={...B6,...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
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 H0="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(H0))return;const e=document.createElement("style");e.id=H0,e.textContent=`
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 l2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(l2))return;const e=document.createElement("style");e.id=l2,e.textContent=`
54
54
  .tiny-remoter-native-tooltip {
55
55
  position: absolute;
56
56
  z-index: 9999;
@@ -97,7 +97,7 @@ Minimum version required to store current data is: `+M+`.
97
97
  transform: translateY(-50%);
98
98
  border-right-color: rgba(0,0,0,.75);
99
99
  }
100
- `,document.head.appendChild(e)})();const $6="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",R6="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",P6="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",M6="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",O6="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",A6="https://chat.opentiny.design",N6="https://ai.opentiny.design/next-remoter",q6="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",B0=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:M6},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:$6},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:P6},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:R6}];class L6{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 x6(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||N6,remoteUrl:t.remoteUrl||A6,logoUrl:t.logoUrl||q6},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?B0(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}):B0(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 W6="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",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_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",K6="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",Y6="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",Q6="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",X6="https://chat.opentiny.design",e5="https://ai.opentiny.design/next-remoter",t5="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",c2=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:Y6},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:W6},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:K6},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:G6}];class r5{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 J6(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||e5,remoteUrl:t.remoteUrl||X6,logoUrl:t.logoUrl||t5},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?c2(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}):c2(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>
@@ -112,14 +112,14 @@ Minimum version required to store current data is: `+M+`.
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="${O6}"/>
115
+ <img src="${Q6}"/>
116
116
  </div>
117
117
  `:""}
118
118
  </div>
119
119
  </div>
120
120
  </div>
121
121
  </div>
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 V0((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 i2((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="
@@ -545,13 +545,13 @@ Minimum version required to store current data is: `+M+`.
545
545
  color: white;
546
546
  }
547
547
  }
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 j6=(e={})=>new L6(e);var J0="vercel.ai.error",D6=Symbol.for(J0),W0,G0,ye=class k1 extends(G0=Error,W0=D6,G0){constructor({name:t,message:r,cause:n}){super(r),this[W0]=!0,this.name=t,this.cause=n}static isInstance(t){return k1.hasMarker(t,J0)}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}},K0="AI_APICallError",Y0=`vercel.ai.error.${K0}`,U6=Symbol.for(Y0),Q0,X0,ht=class extends(X0=ye,Q0=U6,X0){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:K0,message:t,cause:i}),this[Q0]=!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 ye.hasMarker(t,Y0)}},e2="AI_EmptyResponseBodyError",t2=`vercel.ai.error.${e2}`,z6=Symbol.for(t2),r2,n2,Z6=class extends(n2=ye,r2=z6,n2){constructor({message:t="Empty response body"}={}){super({name:e2,message:t}),this[r2]=!0}static isInstance(t){return ye.hasMarker(t,t2)}};function jn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var o2="AI_InvalidArgumentError",s2=`vercel.ai.error.${o2}`,F6=Symbol.for(s2),a2,i2,l2=class extends(i2=ye,a2=F6,i2){constructor({message:t,cause:r,argument:n}){super({name:o2,message:t,cause:r}),this[a2]=!0,this.argument=n}static isInstance(t){return ye.hasMarker(t,s2)}},c2="AI_InvalidPromptError",u2=`vercel.ai.error.${c2}`,V6=Symbol.for(u2),d2,p2,Dn=class extends(p2=ye,d2=V6,p2){constructor({prompt:e,message:t,cause:r}){super({name:c2,message:`Invalid prompt: ${t}`,cause:r}),this[d2]=!0,this.prompt=e}static isInstance(e){return ye.hasMarker(e,u2)}},f2="AI_InvalidResponseDataError",h2=`vercel.ai.error.${f2}`,H6=Symbol.for(h2),m2,g2,Fu=class extends(g2=ye,m2=H6,g2){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:f2,message:r}),this[m2]=!0,this.data=t}static isInstance(t){return ye.hasMarker(t,h2)}},y2="AI_JSONParseError",v2=`vercel.ai.error.${y2}`,B6=Symbol.for(v2),_2,w2,zi=class extends(w2=ye,_2=B6,w2){constructor({text:t,cause:r}){super({name:y2,message:`JSON parsing failed: Text: ${t}.
549
- Error message: ${jn(r)}`,cause:r}),this[_2]=!0,this.text=t}static isInstance(t){return ye.hasMarker(t,v2)}},b2="AI_LoadAPIKeyError",k2=`vercel.ai.error.${b2}`,J6=Symbol.for(k2),T2,C2,Zi=class extends(C2=ye,T2=J6,C2){constructor({message:t}){super({name:b2,message:t}),this[T2]=!0}static isInstance(t){return ye.hasMarker(t,k2)}},S2="AI_TooManyEmbeddingValuesForCallError",I2=`vercel.ai.error.${S2}`,W6=Symbol.for(I2),E2,x2,G6=class extends(x2=ye,E2=W6,x2){constructor(e){super({name:S2,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[E2]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ye.hasMarker(e,I2)}},$2="AI_TypeValidationError",R2=`vercel.ai.error.${$2}`,K6=Symbol.for(R2),P2,M2,Un=class Kd extends(M2=ye,P2=K6,M2){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:$2,message:`${o}: Value: ${JSON.stringify(t)}.
550
- Error message: ${jn(r)}`,cause:r}),this[P2]=!0,this.value=t,this.context=n}static isInstance(t){return ye.hasMarker(t,R2)}static wrap({value:t,cause:r,context:n}){var o,s,a;return Kd.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 Kd({value:t,cause:r,context:n})}},O2="AI_UnsupportedFunctionalityError",A2=`vercel.ai.error.${O2}`,Y6=Symbol.for(A2),N2,q2,xr=class extends(q2=ye,N2=Y6,q2){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:O2,message:r}),this[N2]=!0,this.functionality=t}static isInstance(t){return ye.hasMarker(t,A2)}};function $t(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Q6({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 X6(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(L2());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(L2())};r?.addEventListener("abort",i)})}function L2(){return new DOMException("Delay was aborted","AbortError")}var Rs=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 To(e){return Object.fromEntries([...e.headers])}var{btoa:e5,atob:t5}=globalThis;function Co(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t5(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function So(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return e5(t)}function Io(e){return e instanceof Uint8Array?So(e):e}function r5(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 j2="AI_DownloadError",D2=`vercel.ai.error.${j2}`,n5=Symbol.for(D2),U2,z2,mn=class extends(z2=ye,U2=n5,z2){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:j2,message:o,cause:n}),this[U2]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ye.hasMarker(e,D2)}},Vu=2*1024*1024*1024;async function Z2({response:e,url:t,maxBytes:r=Vu}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new mn({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:f}=await s.read();if(u)break;if(i+=f.length,i>r)throw new mn({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(f)}}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 F2(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new mn({url:e,statusCode:o.status,statusText:o.statusText});const s=await Z2({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Vu}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw mn.isInstance(o)?o:new mn({url:e,cause:o})}}var Ps=({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 l2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},At=Ps();function Hu(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function zn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var o5=["fetch failed","failed to fetch"],s5=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function a5(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&s5.includes(t))}function V2({error:e,url:t,requestBodyValues:r}){if(zn(e))return e;if(e instanceof TypeError&&o5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ht({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return a5(e)?new ht({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Ms(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 i5(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 gn(e,...t){const r=new Headers(i5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var H2="4.0.15",l5=()=>globalThis.fetch,B2=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=l5()})=>{try{const a=await s(e,{method:"GET",headers:gn(t,`ai-sdk/provider-utils/${H2}`,Ms()),signal:o}),i=To(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw zn(c)||ht.isInstance(c)?c:new ht({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&&(zn(l)||ht.isInstance(l))?l:new ht({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw V2({error:a,url:e,requestBodyValues:{}})}};function c5(e){return e!=null}function u5({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 d5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Zi({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Zi({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 Zi({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Zi({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Os({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 p5(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 f5=/"__proto__"\s*:/,h5=/"constructor"\s*:/;function J2(e){const t=JSON.parse(e);return t===null||typeof t!="object"||f5.test(e)===!1&&h5.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 Bu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return J2(e)}try{return J2(e)}finally{Error.stackTraceLimit=t}}function Ju(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]=Zn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Zn):Zn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Zn)),e.allOf!=null&&(e.allOf=e.allOf.map(Zn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Zn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Zn(t[r]);return e}function Zn(e){return typeof e=="boolean"?e:Ju(e)}var g5=Symbol("Let zodToJsonSchema decide on which parser to use"),W2={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"},y5=e=>typeof e=="string"?{...W2,name:e}:{...W2,...e};function Gt(){return{}}function v5(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=Ke(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 _5(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 w5(){return{type:"boolean"}}function G2(e,t){return Ke(e.type._def,t)}var b5=(e,t)=>Ke(e.innerType._def,t);function K2(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>K2(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 k5(e)}}var k5=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 T5(e,t){return{...Ke(e.innerType._def,t),default:e.defaultValue()}}function C5(e,t){return t.effectStrategy==="input"?Ke(e.schema._def,t):Gt()}function S5(e){return{type:"string",enum:Array.from(e.values)}}var I5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function E5(e,t){const r=[Ke(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ke(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(I5(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 x5(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 Wu=void 0,yr={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:()=>(Wu===void 0&&(Wu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wu),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 Y2(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":vr(r,"email",n.message,t);break;case"format:idn-email":vr(r,"idn-email",n.message,t);break;case"pattern:zod":Nt(r,yr.email,n.message,t);break}break;case"url":vr(r,"uri",n.message,t);break;case"uuid":vr(r,"uuid",n.message,t);break;case"regex":Nt(r,n.regex,n.message,t);break;case"cuid":Nt(r,yr.cuid,n.message,t);break;case"cuid2":Nt(r,yr.cuid2,n.message,t);break;case"startsWith":Nt(r,RegExp(`^${Gu(n.value,t)}`),n.message,t);break;case"endsWith":Nt(r,RegExp(`${Gu(n.value,t)}$`),n.message,t);break;case"datetime":vr(r,"date-time",n.message,t);break;case"date":vr(r,"date",n.message,t);break;case"time":vr(r,"time",n.message,t);break;case"duration":vr(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":{Nt(r,RegExp(Gu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&vr(r,"ipv4",n.message,t),n.version!=="v4"&&vr(r,"ipv6",n.message,t);break}case"base64url":Nt(r,yr.base64url,n.message,t);break;case"jwt":Nt(r,yr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Nt(r,yr.ipv4Cidr,n.message,t),n.version!=="v4"&&Nt(r,yr.ipv6Cidr,n.message,t);break}case"emoji":Nt(r,yr.emoji(),n.message,t);break;case"ulid":{Nt(r,yr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{vr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Nt(r,yr.base64,n.message,t);break}}break}case"nanoid":Nt(r,yr.nanoid,n.message,t)}return r}function Gu(e,t){return t.patternStrategy==="escape"?R5(e):e}var $5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function R5(e){let t="";for(let r=0;r<e.length;r++)$5.has(e[r])||(t+="\\"),t+=e[r];return t}function vr(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 Nt(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:Q2(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Q2(t,n)}function Q2(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
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 n5=(e={})=>new r5(e);var u2="vercel.ai.error",o5=Symbol.for(u2),d2,p2,ve=class z1 extends(p2=Error,d2=o5,p2){constructor({name:t,message:r,cause:n}){super(r),this[d2]=!0,this.name=t,this.cause=n}static isInstance(t){return z1.hasMarker(t,u2)}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}},f2="AI_APICallError",h2=`vercel.ai.error.${f2}`,s5=Symbol.for(h2),m2,g2,ut=class extends(g2=ve,m2=s5,g2){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:f2,message:t,cause:i}),this[m2]=!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,h2)}},y2="AI_EmptyResponseBodyError",v2=`vercel.ai.error.${y2}`,a5=Symbol.for(v2),_2,w2,i5=class extends(w2=ve,_2=a5,w2){constructor({message:t="Empty response body"}={}){super({name:y2,message:t}),this[_2]=!0}static isInstance(t){return ve.hasMarker(t,v2)}};function Wn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var b2="AI_InvalidArgumentError",k2=`vercel.ai.error.${b2}`,l5=Symbol.for(k2),T2,C2,S2=class extends(C2=ve,T2=l5,C2){constructor({message:t,cause:r,argument:n}){super({name:b2,message:t,cause:r}),this[T2]=!0,this.argument=n}static isInstance(t){return ve.hasMarker(t,k2)}},I2="AI_InvalidPromptError",x2=`vercel.ai.error.${I2}`,c5=Symbol.for(x2),E2,$2,Gn=class extends($2=ve,E2=c5,$2){constructor({prompt:e,message:t,cause:r}){super({name:I2,message:`Invalid prompt: ${t}`,cause:r}),this[E2]=!0,this.prompt=e}static isInstance(e){return ve.hasMarker(e,x2)}},R2="AI_InvalidResponseDataError",P2=`vercel.ai.error.${R2}`,u5=Symbol.for(P2),M2,O2,id=class extends(O2=ve,M2=u5,O2){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:R2,message:r}),this[M2]=!0,this.data=t}static isInstance(t){return ve.hasMarker(t,P2)}},N2="AI_JSONParseError",A2=`vercel.ai.error.${N2}`,d5=Symbol.for(A2),q2,L2,el=class extends(L2=ve,q2=d5,L2){constructor({text:t,cause:r}){super({name:N2,message:`JSON parsing failed: Text: ${t}.
549
+ Error message: ${Wn(r)}`,cause:r}),this[q2]=!0,this.text=t}static isInstance(t){return ve.hasMarker(t,A2)}},j2="AI_LoadAPIKeyError",D2=`vercel.ai.error.${j2}`,p5=Symbol.for(D2),U2,z2,tl=class extends(z2=ve,U2=p5,z2){constructor({message:t}){super({name:j2,message:t}),this[U2]=!0}static isInstance(t){return ve.hasMarker(t,D2)}},Z2="AI_TooManyEmbeddingValuesForCallError",F2=`vercel.ai.error.${Z2}`,f5=Symbol.for(F2),V2,H2,h5=class extends(H2=ve,V2=f5,H2){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[V2]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ve.hasMarker(e,F2)}},B2="AI_TypeValidationError",J2=`vercel.ai.error.${B2}`,m5=Symbol.for(J2),W2,G2,Kn=class fp extends(G2=ve,W2=m5,G2){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:B2,message:`${o}: Value: ${JSON.stringify(t)}.
550
+ Error message: ${Wn(r)}`,cause:r}),this[W2]=!0,this.value=t,this.context=n}static isInstance(t){return ve.hasMarker(t,J2)}static wrap({value:t,cause:r,context:n}){var o,s,a;return fp.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 fp({value:t,cause:r,context:n})}},K2="AI_UnsupportedFunctionalityError",Y2=`vercel.ai.error.${K2}`,g5=Symbol.for(Y2),Q2,X2,jr=class extends(X2=ve,Q2=g5,X2){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:K2,message:r}),this[Q2]=!0,this.functionality=t}static isInstance(t){return ve.hasMarker(t,Y2)}};function At(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function y5({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 v5(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(eg());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(eg())};r?.addEventListener("abort",i)})}function eg(){return new DOMException("Delay was aborted","AbortError")}var Us=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 Po(e){return Object.fromEntries([...e.headers])}var{btoa:_5,atob:w5}=globalThis;function Mo(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=w5(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Oo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return _5(t)}function No(e){return e instanceof Uint8Array?Oo(e):e}function b5(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 tg="AI_DownloadError",rg=`vercel.ai.error.${tg}`,k5=Symbol.for(rg),ng,og,In=class extends(og=ve,ng=k5,og){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:tg,message:o,cause:n}),this[ng]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ve.hasMarker(e,rg)}},ld=2*1024*1024*1024;async function sg({response:e,url:t,maxBytes:r=ld}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new In({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 In({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 ag(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new In({url:e,statusCode:o.status,statusText:o.statusText});const s=await sg({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:ld}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw In.isInstance(o)?o:new In({url:e,cause:o})}}var zs=({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 S2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},zt=zs();function cd(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Yn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var T5=["fetch failed","failed to fetch"],C5=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function S5(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&C5.includes(t))}function ig({error:e,url:t,requestBodyValues:r}){if(Yn(e))return e;if(e instanceof TypeError&&T5.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 S5(e)?new ut({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Zs(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 I5(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 xn(e,...t){const r=new Headers(I5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var lg="4.0.15",x5=()=>globalThis.fetch,cg=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=x5()})=>{try{const a=await s(e,{method:"GET",headers:xn(t,`ai-sdk/provider-utils/${lg}`,Zs()),signal:o}),i=Po(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw Yn(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&&(Yn(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 ig({error:a,url:e,requestBodyValues:{}})}};function E5(e){return e!=null}function $5({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 R5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new tl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new tl({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 tl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new tl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Ao({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 P5(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 M5=/"__proto__"\s*:/,O5=/"constructor"\s*:/;function ug(e){const t=JSON.parse(e);return t===null||typeof t!="object"||M5.test(e)===!1&&O5.test(e)===!1?t:N5(t)}function N5(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 ud(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ug(e)}try{return ug(e)}finally{Error.stackTraceLimit=t}}function dd(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]=Qn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Qn):Qn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Qn)),e.allOf!=null&&(e.allOf=e.allOf.map(Qn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Qn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Qn(t[r]);return e}function Qn(e){return typeof e=="boolean"?e:dd(e)}var A5=Symbol("Let zodToJsonSchema decide on which parser to use"),dg={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"},q5=e=>typeof e=="string"?{...dg,name:e}:{...dg,...e};function tr(){return{}}function L5(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)!==J.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 j5(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 D5(){return{type:"boolean"}}function pg(e,t){return We(e.type._def,t)}var U5=(e,t)=>We(e.innerType._def,t);function fg(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>fg(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 z5(e)}}var z5=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 Z5(e,t){return{...We(e.innerType._def,t),default:e.defaultValue()}}function F5(e,t){return t.effectStrategy==="input"?We(e.schema._def,t):tr()}function V5(e){return{type:"string",enum:Array.from(e.values)}}var H5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function B5(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(H5(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 J5(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 pd=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:()=>(pd===void 0&&(pd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pd),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 hg(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":Ir(r,"email",n.message,t);break;case"format:idn-email":Ir(r,"idn-email",n.message,t);break;case"pattern:zod":Zt(r,Sr.email,n.message,t);break}break;case"url":Ir(r,"uri",n.message,t);break;case"uuid":Ir(r,"uuid",n.message,t);break;case"regex":Zt(r,n.regex,n.message,t);break;case"cuid":Zt(r,Sr.cuid,n.message,t);break;case"cuid2":Zt(r,Sr.cuid2,n.message,t);break;case"startsWith":Zt(r,RegExp(`^${fd(n.value,t)}`),n.message,t);break;case"endsWith":Zt(r,RegExp(`${fd(n.value,t)}$`),n.message,t);break;case"datetime":Ir(r,"date-time",n.message,t);break;case"date":Ir(r,"date",n.message,t);break;case"time":Ir(r,"time",n.message,t);break;case"duration":Ir(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(fd(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Ir(r,"ipv4",n.message,t),n.version!=="v4"&&Ir(r,"ipv6",n.message,t);break}case"base64url":Zt(r,Sr.base64url,n.message,t);break;case"jwt":Zt(r,Sr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Zt(r,Sr.ipv4Cidr,n.message,t),n.version!=="v4"&&Zt(r,Sr.ipv6Cidr,n.message,t);break}case"emoji":Zt(r,Sr.emoji(),n.message,t);break;case"ulid":{Zt(r,Sr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Ir(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Zt(r,Sr.base64,n.message,t);break}}break}case"nanoid":Zt(r,Sr.nanoid,n.message,t)}return r}function fd(e,t){return t.patternStrategy==="escape"?G5(e):e}var W5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function G5(e){let t="";for(let r=0;r<e.length;r++)W5.has(e[r])||(t+="\\"),t+=e[r];return t}function Ir(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:mg(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=mg(t,n)}function mg(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
551
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
552
552
  ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
553
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 X2(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ke(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}=Y2(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}=G2(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function P5(e,t){if(t.mapStrategy==="record")return X2(e,t);const r=Ke(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(),n=Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function M5(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 O5(){return{not:Gt()}}function A5(){return{type:"null"}}var Ku={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function N5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ku&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Ku[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 q5(e,t)}var q5=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ke(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 L5(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ku[e.innerType._def.typeName],"null"]};const r=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function j5(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 D5(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=z5(i),c=Ke(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=U5(e,t);return s!==void 0&&(r.additionalProperties=s),r}function U5(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ke(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 z5(e){try{return e.isOptional()}catch{return!0}}var Z5=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ke(e.innerType._def,t);const n=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Gt()},n]}:Gt()},F5=(e,t)=>{if(t.pipeStrategy==="input")return Ke(e.in._def,t);if(t.pipeStrategy==="output")return Ke(e.out._def,t);const r=Ke(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ke(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function V5(e,t){return Ke(e.type._def,t)}function H5(e,t){const n={type:"array",uniqueItems:!0,items:Ke(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 B5(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ke(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function J5(){return{not:Gt()}}function W5(){return Gt()}var G5=(e,t)=>Ke(e.innerType._def,t),K5=(e,t,r)=>{switch(t){case B.ZodString:return Y2(e,r);case B.ZodNumber:return j5(e);case B.ZodObject:return D5(e,r);case B.ZodBigInt:return _5(e);case B.ZodBoolean:return w5();case B.ZodDate:return K2(e,r);case B.ZodUndefined:return J5();case B.ZodNull:return A5();case B.ZodArray:return v5(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return N5(e,r);case B.ZodIntersection:return E5(e,r);case B.ZodTuple:return B5(e,r);case B.ZodRecord:return X2(e,r);case B.ZodLiteral:return x5(e);case B.ZodEnum:return S5(e);case B.ZodNativeEnum:return M5(e);case B.ZodNullable:return L5(e,r);case B.ZodOptional:return Z5(e,r);case B.ZodMap:return P5(e,r);case B.ZodSet:return H5(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return V5(e,r);case B.ZodNaN:case B.ZodNever:return O5();case B.ZodEffects:return C5(e,r);case B.ZodAny:return Gt();case B.ZodUnknown:return W5();case B.ZodDefault:return T5(e,r);case B.ZodBranded:return G2(e,r);case B.ZodReadonly:return G5(e,r);case B.ZodCatch:return b5(e,r);case B.ZodPipeline:return F5(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}},Y5=(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 Ke(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!==g5)return l}if(o&&!r){const l=Q5(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=K5(e,e.typeName,t),i=typeof a=="function"?Ke(a(),t):a;if(i&&X5(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Q5=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Y5(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`),Gt()):t.$refStrategy==="seen"?Gt():void 0}},X5=(e,t,r)=>(e.description&&(r.description=e.description),r),eI=e=>{const t=y5(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}]))}},tI=(e,t)=>{var r;const n=eI(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,f])=>{var p;return{...c,[u]:(p=Ke(f._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:Gt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ke(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Gt(),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},Yu=Symbol.for("vercel.ai.schema");function Ie(e){let t;return()=>(t==null&&(t=e()),t)}function Eo(e,{validate:t}={}){return{[Yu]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function rI(e){return typeof e=="object"&&e!==null&&Yu in e&&e[Yu]===!0&&"jsonSchema"in e&&"validate"in e}function Fn(e){return e==null?Eo({properties:{},additionalProperties:!1}):rI(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Ce(e):nI(e):e()}function nI(e){return Eo(()=>Ju(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 Un({value:t,cause:r.issues})}}})}function oI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Eo(()=>tI(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 sI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Eo(()=>Ju(_h(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await bh(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function aI(e){return"_zod"in e}function Ce(e,t){return aI(e)?sI(e):oI(e)}async function qt({value:e,schema:t,context:r}){const n=await nr({value:e,schema:t,context:r});if(!n.success)throw Un.wrap({value:e,cause:n.error,context:r});return n.value}async function nr({value:e,schema:t,context:r}){const n=Fn(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:Un.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Un.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function iI({text:e,schema:t}){try{const r=Bu(e);return t==null?r:qt({value:r,schema:t})}catch(r){throw zi.isInstance(r)||Un.isInstance(r)?r:new zi({text:e,cause:r})}}async function or({text:e,schema:t}){try{const r=Bu(e);return t==null?{success:!0,value:r,rawValue:r}:await nr({value:r,schema:t})}catch(r){return{success:!1,error:zi.isInstance(r)?r:new zi({text:e,cause:r}),rawValue:void 0}}}function eg(e){try{return Bu(e),!0}catch{return!1}}function lI({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await or({text:r,schema:t}))}}))}async function Jr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await nr({value:t[e],schema:r});if(!n.success)throw new l2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var cI=()=>globalThis.fetch,Zt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>rg({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),tg=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>rg({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),rg=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=cI()})=>{try{const i=await a(e,{method:"POST",headers:gn(t,`ai-sdk/provider-utils/${H2}`,Ms()),body:r.content,signal:s}),l=To(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw zn(u)||ht.isInstance(u)?u:new ht({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&&(zn(c)||ht.isInstance(c))?c:new ht({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw V2({error:i,url:e,requestBodyValues:r.values})}};function zP(e){return e}function ng(e){return{...e,type:"dynamic"}}function _r({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 Ft(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var yn=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=To(n);if(a.trim()==="")return{responseHeaders:i,value:new ht({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await iI({text:a,schema:e});return{responseHeaders:i,value:new ht({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 ht({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Fi=e=>async({response:t})=>{const r=To(t);if(t.body==null)throw new Z6({});return{responseHeaders:r,value:lI({stream:t.body,schema:e})}},Kt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await or({text:o,schema:e}),a=To(t);if(!s.success)throw new ht({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}},uI=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=To(e);if(!e.body)throw new ht({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 ht({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function og(e){return e?.replace(/\/$/,"")}function dI(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*pI({execute:e,input:t,options:r}){const n=e(t,r);if(dI(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 Qu,sg;function fI(){if(sg)return Qu;sg=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,f)=>{for(var p in f)e(u,p,{get:f[p],enumerable:!0})},s=(u,f,p,h)=>{if(f&&typeof f=="object"||typeof f=="function")for(let y of r(f))!n.call(u,y)&&y!==p&&e(u,y,{get:()=>f[y],enumerable:!(h=t(f,y))||h.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Qu=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Qu}var Xu,ag;function hI(){if(ag)return Xu;ag=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(f,p)=>{for(var h in p)e(f,h,{get:p[h],enumerable:!0})},s=(f,p,h,y)=>{if(p&&typeof p=="object"||typeof p=="function")for(let w of r(p))!n.call(f,w)&&w!==h&&e(f,w,{get:()=>p[w],enumerable:!(y=t(p,w))||y.enumerable});return f},a=f=>s(e({},"__esModule",{value:!0}),f),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Xu=a(i);var l=fI();async function c(){return""}function u(){return""}return Xu}var ig=hI(),mI="vercel.ai.gateway.error",ed=Symbol.for(mI),lg,cg,Lt=class T1 extends(cg=Error,lg=ed,cg){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[lg]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return T1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ed in t&&t[ed]===!0}},ug="GatewayAuthenticationError",gI=`vercel.ai.gateway.error.${ug}`,dg=Symbol.for(gI),pg,fg,td=class C1 extends(fg=Lt,pg=dg,fg){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[pg]=!0,this.name=ug,this.type="authentication_error"}static isInstance(t){return Lt.hasMarker(t)&&dg 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.
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 gg(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)===J.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=hg(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===J.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===J.ZodBranded&&e.keyType._def.type._def.typeName===J.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=pg(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function K5(e,t){if(t.mapStrategy==="record")return gg(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 Y5(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 Q5(){return{not:tr()}}function X5(){return{type:"null"}}var hd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function eI(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in hd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=hd[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 tI(e,t)}var tI=(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 rI(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[hd[e.innerType._def.typeName],"null"]};const r=We(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function nI(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 oI(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=aI(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=sI(e,t);return s!==void 0&&(r.additionalProperties=s),r}function sI(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 aI(e){try{return e.isOptional()}catch{return!0}}var iI=(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()},lI=(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 cI(e,t){return We(e.type._def,t)}function uI(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 dI(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 pI(){return{not:tr()}}function fI(){return tr()}var hI=(e,t)=>We(e.innerType._def,t),mI=(e,t,r)=>{switch(t){case J.ZodString:return hg(e,r);case J.ZodNumber:return nI(e);case J.ZodObject:return oI(e,r);case J.ZodBigInt:return j5(e);case J.ZodBoolean:return D5();case J.ZodDate:return fg(e,r);case J.ZodUndefined:return pI();case J.ZodNull:return X5();case J.ZodArray:return L5(e,r);case J.ZodUnion:case J.ZodDiscriminatedUnion:return eI(e,r);case J.ZodIntersection:return B5(e,r);case J.ZodTuple:return dI(e,r);case J.ZodRecord:return gg(e,r);case J.ZodLiteral:return J5(e);case J.ZodEnum:return V5(e);case J.ZodNativeEnum:return Y5(e);case J.ZodNullable:return rI(e,r);case J.ZodOptional:return iI(e,r);case J.ZodMap:return K5(e,r);case J.ZodSet:return uI(e,r);case J.ZodLazy:return()=>e.getter()._def;case J.ZodPromise:return cI(e,r);case J.ZodNaN:case J.ZodNever:return Q5();case J.ZodEffects:return F5(e,r);case J.ZodAny:return tr();case J.ZodUnknown:return fI();case J.ZodDefault:return Z5(e,r);case J.ZodBranded:return pg(e,r);case J.ZodReadonly:return hI(e,r);case J.ZodCatch:return U5(e,r);case J.ZodPipeline:return lI(e,r);case J.ZodFunction:case J.ZodVoid:case J.ZodSymbol:return;default:return(n=>{})()}},gI=(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!==A5)return l}if(o&&!r){const l=yI(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=mI(e,e.typeName,t),i=typeof a=="function"?We(a(),t):a;if(i&&vI(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var yI=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:gI(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}},vI=(e,t,r)=>(e.description&&(r.description=e.description),r),_I=e=>{const t=q5(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}]))}},wI=(e,t)=>{var r;const n=_I(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},md=Symbol.for("vercel.ai.schema");function Ce(e){let t;return()=>(t==null&&(t=e()),t)}function qo(e,{validate:t}={}){return{[md]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function bI(e){return typeof e=="object"&&e!==null&&md in e&&e[md]===!0&&"jsonSchema"in e&&"validate"in e}function Xn(e){return e==null?qo({properties:{},additionalProperties:!1}):bI(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Te(e):kI(e):e()}function kI(e){return qo(()=>dd(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 Kn({value:t,cause:r.issues})}}})}function TI(e,t){var r;const n=(r=void 0)!=null?r:!1;return qo(()=>wI(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 CI(e,t){var r;const n=(r=void 0)!=null?r:!1;return qo(()=>dd(qh(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await jh(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function SI(e){return"_zod"in e}function Te(e,t){return SI(e)?CI(e):TI(e)}async function Mt({value:e,schema:t,context:r}){const n=await cr({value:e,schema:t,context:r});if(!n.success)throw Kn.wrap({value:e,cause:n.error,context:r});return n.value}async function cr({value:e,schema:t,context:r}){const n=Xn(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:Kn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Kn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function II({text:e,schema:t}){try{const r=ud(e);return t==null?r:Mt({value:r,schema:t})}catch(r){throw el.isInstance(r)||Kn.isInstance(r)?r:new el({text:e,cause:r})}}async function ur({text:e,schema:t}){try{const r=ud(e);return t==null?{success:!0,value:r,rawValue:r}:await cr({value:r,schema:t})}catch(r){return{success:!1,error:el.isInstance(r)?r:new el({text:e,cause:r}),rawValue:void 0}}}function yg(e){try{return ud(e),!0}catch{return!1}}function vg({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new xo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await ur({text:r,schema:t}))}}))}async function nn({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 S2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var xI=()=>globalThis.fetch,Wt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>wg({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),_g=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>wg({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),wg=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=xI()})=>{try{const i=await a(e,{method:"POST",headers:xn(t,`ai-sdk/provider-utils/${lg}`,Zs()),body:r.content,signal:s}),l=Po(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Yn(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&&(Yn(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 ig({error:i,url:e,requestBodyValues:r.values})}};function lM(e){return e}function bg(e){return{...e,type:"dynamic"}}function xr({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 Gt(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=Po(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 II({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)})}}},rl=e=>async({response:t})=>{const r=Po(t);if(t.body==null)throw new i5({});return{responseHeaders:r,value:vg({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=Po(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}},EI=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Po(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 kg(e){return e?.replace(/\/$/,"")}function $I(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*RI({execute:e,input:t,options:r}){const n=e(t,r);if($I(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 gd,Tg;function PI(){if(Tg)return gd;Tg=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}),gd=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return gd}var yd,Cg;function MI(){if(Cg)return yd;Cg=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}),yd=a(i);var l=PI();async function c(){return""}function u(){return""}return yd}var Sg=MI(),OI="vercel.ai.gateway.error",vd=Symbol.for(OI),Ig,xg,Ft=class Z1 extends(xg=Error,Ig=vd,xg){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Ig]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return Z1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&vd in t&&t[vd]===!0}},Eg="GatewayAuthenticationError",NI=`vercel.ai.gateway.error.${Eg}`,$g=Symbol.for(NI),Rg,Pg,_d=class F1 extends(Pg=Ft,Rg=$g,Pg){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Rg]=!0,this.name=Eg,this.type="authentication_error"}static isInstance(t){return Ft.hasMarker(t)&&$g 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
 
@@ -566,9 +566,9 @@ 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 C1({message:i,statusCode:o,cause:s,generationId:a})}},hg="GatewayInvalidRequestError",yI=`vercel.ai.gateway.error.${hg}`,mg=Symbol.for(yI),gg,yg,vI=class extends(yg=Lt,gg=mg,yg){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[gg]=!0,this.name=hg,this.type="invalid_request_error"}static isInstance(e){return Lt.hasMarker(e)&&mg in e}},vg="GatewayRateLimitError",_I=`vercel.ai.gateway.error.${vg}`,_g=Symbol.for(_I),wg,bg,wI=class extends(bg=Lt,wg=_g,bg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[wg]=!0,this.name=vg,this.type="rate_limit_exceeded"}static isInstance(e){return Lt.hasMarker(e)&&_g in e}},kg="GatewayModelNotFoundError",bI=`vercel.ai.gateway.error.${kg}`,Tg=Symbol.for(bI),kI=Ie(()=>Ce(C({modelId:d()}))),Cg,Sg,TI=class extends(Sg=Lt,Cg=Tg,Sg){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[Cg]=!0,this.name=kg,this.type="model_not_found",this.modelId=r}static isInstance(e){return Lt.hasMarker(e)&&Tg in e}},Ig="GatewayInternalServerError",CI=`vercel.ai.gateway.error.${Ig}`,Eg=Symbol.for(CI),xg,$g,Rg=class extends($g=Lt,xg=Eg,$g){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[xg]=!0,this.name=Ig,this.type="internal_server_error"}static isInstance(e){return Lt.hasMarker(e)&&Eg in e}},Pg="GatewayResponseError",SI=`vercel.ai.gateway.error.${Pg}`,Mg=Symbol.for(SI),Og,Ag,II=class extends(Ag=Lt,Og=Mg,Ag){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[Og]=!0,this.name=Pg,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Lt.hasMarker(e)&&Mg in e}};async function Ng({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await nr({value:e,schema:EI});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new II({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:f})}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 td.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new vI({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new wI({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await nr({value:i.error.param,schema:kI});return new TI({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Rg({message:c,statusCode:t,cause:n,generationId:u});default:return new Rg({message:c,statusCode:t,cause:n,generationId:u})}}var EI=Ie(()=>Ce(C({error:C({message:d(),type:d().nullish(),param:Le().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),qg="GatewayTimeoutError",xI=`vercel.ai.gateway.error.${qg}`,Lg=Symbol.for(xI),jg,Dg,Ug=class S1 extends(Dg=Lt,jg=Lg,Dg){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[jg]=!0,this.name=qg,this.type="timeout_error"}static isInstance(t){return Lt.hasMarker(t)&&Lg in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
569
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new F1({message:i,statusCode:o,cause:s,generationId:a})}},Mg="GatewayInvalidRequestError",AI=`vercel.ai.gateway.error.${Mg}`,Og=Symbol.for(AI),Ng,Ag,qI=class extends(Ag=Ft,Ng=Og,Ag){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Ng]=!0,this.name=Mg,this.type="invalid_request_error"}static isInstance(e){return Ft.hasMarker(e)&&Og in e}},qg="GatewayRateLimitError",LI=`vercel.ai.gateway.error.${qg}`,Lg=Symbol.for(LI),jg,Dg,jI=class extends(Dg=Ft,jg=Lg,Dg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[jg]=!0,this.name=qg,this.type="rate_limit_exceeded"}static isInstance(e){return Ft.hasMarker(e)&&Lg in e}},Ug="GatewayModelNotFoundError",DI=`vercel.ai.gateway.error.${Ug}`,zg=Symbol.for(DI),UI=Ce(()=>Te(T({modelId:d()}))),Zg,Fg,zI=class extends(Fg=Ft,Zg=zg,Fg){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=Ug,this.type="model_not_found",this.modelId=r}static isInstance(e){return Ft.hasMarker(e)&&zg in e}},Vg="GatewayInternalServerError",ZI=`vercel.ai.gateway.error.${Vg}`,Hg=Symbol.for(ZI),Bg,Jg,Wg=class extends(Jg=Ft,Bg=Hg,Jg){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Bg]=!0,this.name=Vg,this.type="internal_server_error"}static isInstance(e){return Ft.hasMarker(e)&&Hg in e}},Gg="GatewayResponseError",FI=`vercel.ai.gateway.error.${Gg}`,Kg=Symbol.for(FI),Yg,Qg,VI=class extends(Qg=Ft,Yg=Kg,Qg){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[Yg]=!0,this.name=Gg,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Ft.hasMarker(e)&&Kg in e}};async function Xg({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await cr({value:e,schema:HI});if(!a.success){const h=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new VI({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 _d.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new qI({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new jI({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const h=await cr({value:i.error.param,schema:UI});return new zI({message:c,statusCode:t,modelId:h.success?h.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Wg({message:c,statusCode:t,cause:n,generationId:u});default:return new Wg({message:c,statusCode:t,cause:n,generationId:u})}}var HI=Ce(()=>Te(T({error:T({message:d(),type:d().nullish(),param:Me().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),ey="GatewayTimeoutError",BI=`vercel.ai.gateway.error.${ey}`,ty=Symbol.for(BI),ry,ny,oy=class V1 extends(ny=Ft,ry=ty,ny){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[ry]=!0,this.name=ey,this.type="timeout_error"}static isInstance(t){return Ft.hasMarker(t)&&ty in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
570
570
 
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 S1({message:s,statusCode:r,cause:n,generationId:o})}};function zg(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 Wr(e,t){var r;return Lt.isInstance(e)?e:zg(e)?Ug.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ht.isInstance(e)?e.cause&&zg(e.cause)?Ug.createTimeoutError({originalMessage:e.message,cause:e}):await Ng({response:$I(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Ng({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function $I(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 Zg="ai-gateway-auth-method";async function Vn(e){const t=await nr({value:e[Zg],schema:RI});return t.success?t.value:void 0}var RI=Ie(()=>Ce(oe([P("api-key"),P("oidc")]))),Fg=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await B2({url:`${this.config.baseURL}/config`,headers:await Ft(this.config.headers()),successfulResponseHandler:Kt(PI),failedResponseHandler:yn({errorSchema:mt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Wr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await B2({url:`${e.origin}/v1/credits`,headers:await Ft(this.config.headers()),successfulResponseHandler:Kt(MI),failedResponseHandler:yn({errorSchema:mt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Wr(e)}}},PI=Ie(()=>Ce(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:P("v3"),provider:d(),modelId:d()}),modelType:Ee(["embedding","image","language","video"]).nullish()}))}))),MI=Ie(()=>Ce(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),OI=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 Ft(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Zt({url:this.getUrl(),headers:$t(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ft(this.config.o11yHeaders)),body:t,successfulResponseHandler:Kt(mt()),failedResponseHandler:yn({errorSchema:mt(),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 Wr(s,await Vn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ft(this.config.headers());try{const{value:s,responseHeaders:a}=await Zt({url:this.getUrl(),headers:$t(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ft(this.config.o11yHeaders)),body:t,successfulResponseHandler:Fi(mt()),failedResponseHandler:yn({errorSchema:mt(),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 Wr(s,await Vn(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)}}},AI=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 Ft(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Zt({url:this.getUrl(),headers:$t(s,t??{},this.getModelConfigHeaders(),await Ft(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Kt(NI),failedResponseHandler:yn({errorSchema:mt(),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 Wr(a,await Vn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},NI=Ie(()=>Ce(C({embeddings:q(q(j())),usage:C({tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),Le())).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,f,p,h;const y=await Ft(this.config.headers());try{const{responseHeaders:w,value:g,rawValue:b}=await Zt({url:this.getUrl(),headers:$t(y,l??{},this.getModelConfigHeaders(),await Ft(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=>Vg(v))},...a&&{mask:Vg(a)}},successfulResponseHandler:Kt(UI),failedResponseHandler:yn({errorSchema:mt(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:g.images,warnings:(u=g.warnings)!=null?u:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:w},...g.usage!=null&&{usage:{inputTokens:(f=g.usage.inputTokens)!=null?f:void 0,outputTokens:(p=g.usage.outputTokens)!=null?p:void 0,totalTokens:(h=g.usage.totalTokens)!=null?h:void 0}}}}catch(w){throw await Wr(w,await Vn(y))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function Vg(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:So(e.data)}:e}var LI=C({images:q(Le()).optional()}).catchall(Le()),jI=tt("type",[C({type:P("unsupported"),feature:d(),details:d().optional()}),C({type:P("compatibility"),feature:d(),details:d().optional()}),C({type:P("other"),message:d()})]),DI=C({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),UI=C({images:q(d()),warnings:q(jI).optional(),providerMetadata:ge(d(),LI).optional(),usage:DI.optional()}),zI=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 f;const p=await Ft(this.config.headers());try{const{responseHeaders:h,value:y,rawValue:w}=await Zt({url:this.getUrl(),headers:$t(p,c??{},this.getModelConfigHeaders(),await Ft(this.config.o11yHeaders)),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:ZI(i)}},successfulResponseHandler:Kt(BI),failedResponseHandler:yn({errorSchema:mt(),errorToMessage:g=>g}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:y.videos,warnings:(f=y.warnings)!=null?f:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await Wr(h,await Vn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function ZI(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:So(e.data)}:e}var FI=C({videos:q(Le()).optional()}).catchall(Le()),VI=oe([C({type:P("url"),url:d(),mediaType:d()}),C({type:P("base64"),data:d(),mediaType:d()})]),HI=tt("type",[C({type:P("unsupported"),feature:d(),details:d().optional()}),C({type:P("compatibility"),feature:d(),details:d().optional()}),C({type:P("other"),message:d()})]),BI=C({videos:q(VI),warnings:q(HI).optional(),providerMetadata:ge(d(),FI).optional()}),JI=Ie(()=>Ce(jt({objective:Ve().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:zr(Ve()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Qo(["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:Xt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:jt({include_domains:zr(Ve()).optional().describe("List of domains to include in search results."),exclude_domains:zr(Ve()).optional().describe("List of domains to exclude from search results."),after_date:Ve().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:jt({max_chars_per_result:Xt().optional().describe("Maximum characters per result."),max_chars_total:Xt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:jt({max_age_seconds:Xt().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.")}))),WI=Ie(()=>Ce(ei([jt({searchId:Ve(),results:zr(jt({url:Ve(),title:Ve(),excerpt:Ve(),publishDate:Ve().nullable().optional(),relevanceScore:Xt().optional()}))}),jt({error:Qo(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Xt().optional(),message:Ve()})]))),GI=_r({id:"gateway.parallel_search",inputSchema:JI,outputSchema:WI}),KI=(e={})=>GI(e),YI=Ie(()=>Ce(jt({query:ei([Ve(),zr(Ve())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Xt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Xt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Xt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ve().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:zr(Ve()).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:zr(Ve()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ve().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:Ve().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:Ve().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:Ve().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:Qo(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),QI=Ie(()=>Ce(ei([jt({results:zr(jt({title:Ve(),url:Ve(),snippet:Ve(),date:Ve().optional(),lastUpdated:Ve().optional()})),id:Ve()}),jt({error:Qo(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Xt().optional(),message:Ve()})]))),XI=_r({id:"gateway.perplexity_search",inputSchema:YI,outputSchema:QI}),e8=(e={})=>XI(e),t8={parallelSearch:KI,perplexitySearch:e8};async function r8(){var e;return(e=ig.getContext().headers)==null?void 0:e["x-vercel-id"]}var n8="3.0.45",o8="0.0.1";function s8(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=og(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const w=await i8(e);return gn({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":o8,[Zg]:w.authMethod,...e.headers},`ai-sdk/gateway/${n8}`)}catch(w){throw td.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=Os({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),g=Os({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=Os({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await r8();return{...w&&{"ai-o11y-deployment-id":w},...g&&{"ai-o11y-environment":g},...b&&{"ai-o11y-region":b},...v&&{"ai-o11y-request-id":v}}}},u=w=>new OI(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f=async()=>{var w,g,b;const v=(b=(g=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:g.call(w).getTime())!=null?b:Date.now();return(!n||v-a>s)&&(a=v,n=new Fg({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(m=>(o=m,m)).catch(async m=>{throw await Wr(m,await Vn(await l()))})),o?Promise.resolve(o):n},p=async()=>new Fg({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await Wr(w,await Vn(await l()))}),h=function(w){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(w)};h.specificationVersion="v3",h.getAvailableModels=f,h.getCredits=p,h.imageModel=w=>new qI(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h.languageModel=u;const y=w=>new AI(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return h.embeddingModel=y,h.textEmbeddingModel=y,h.videoModel=w=>new zI(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h.chat=h.languageModel,h.embedding=h.embeddingModel,h.image=h.imageModel,h.video=h.videoModel,h.tools=t8,h}var a8=s8();async function i8(e){const t=Os({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await ig.getVercelOidcToken(),authMethod:"oidc"}}var l8=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Hn="1.9.0",Hg=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function c8(e){var t=new Set([e]),r=new Set,n=e.match(Hg);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(Hg);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 u8=c8(Hn),d8=Hn.split(".")[0],As=Symbol.for("opentelemetry.js.api."+d8),Ns=l8;function qs(e,t,r,n){var o;n===void 0&&(n=!1);var s=Ns[As]=(o=Ns[As])!==null&&o!==void 0?o:{version:Hn};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!==Hn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Hn);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Hn+"."),!0}function Bn(e){var t,r,n=(t=Ns[As])===null||t===void 0?void 0:t.version;if(!(!n||!u8(n)))return(r=Ns[As])===null||r===void 0?void 0:r[e]}function Ls(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Hn+".");var r=Ns[As];r&&delete r[e]}var p8=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},f8=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))},h8=(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 js("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return js("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return js("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return js("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return js("verbose",this._namespace,t)},e})();function js(e,t,r){var n=Bn("diag");if(n)return r.unshift(t),n[e].apply(n,f8([],p8(r),!1))}var Yt;(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"})(Yt||(Yt={}));function m8(e,t){e<Yt.NONE?e=Yt.NONE:e>Yt.ALL&&(e=Yt.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",Yt.ERROR),warn:r("warn",Yt.WARN),info:r("info",Yt.INFO),debug:r("debug",Yt.DEBUG),verbose:r("verbose",Yt.VERBOSE)}}var g8=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},y8=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))},v8="diag",$r=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=Bn("diag");if(i)return i[o].apply(i,y8([],g8(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:Yt.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=Bn("diag"),f=m8((i=s.logLevel)!==null&&i!==void 0?i:Yt.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),f.warn("Current logger will overwrite one already registered from "+p)}return qs("diag",f,r,!0)};r.setLogger=n,r.disable=function(){Ls(v8,r)},r.createComponentLogger=function(o){return new h8(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})(),_8=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},w8=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.")},b8=(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=_8(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=w8(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})();$r.instance();function k8(e){return e===void 0&&(e={}),new b8(new Map(Object.entries(e)))}function Bg(e){return Symbol.for(e)}var T8=(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})(),C8=new T8,Jn=(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)}})(),S8=(function(){function e(){}return e.prototype.createGauge=function(t,r){return N8},e.prototype.createHistogram=function(t,r){return q8},e.prototype.createCounter=function(t,r){return A8},e.prototype.createUpDownCounter=function(t,r){return L8},e.prototype.createObservableGauge=function(t,r){return D8},e.prototype.createObservableCounter=function(t,r){return j8},e.prototype.createObservableUpDownCounter=function(t,r){return U8},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Vi=(function(){function e(){}return e})(),I8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Vi),E8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Vi),x8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Vi),$8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Vi),rd=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),R8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(rd),P8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(rd),M8=(function(e){Jn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(rd),O8=new S8,A8=new I8,N8=new x8,q8=new $8,L8=new E8,j8=new R8,D8=new P8,U8=new M8,z8={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},Z8={set:function(e,t,r){e!=null&&(e[t]=r)}},F8=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},V8=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))},H8=(function(){function e(){}return e.prototype.active=function(){return C8},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,V8([n],F8(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),B8=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},J8=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))},nd="context",W8=new H8,Hi=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return qs(nd,t,$r.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,J8([t,r,n],B8(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Bn(nd)||W8},e.prototype.disable=function(){this._getContextManager().disable(),Ls(nd,$r.instance())},e})(),od;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(od||(od={}));var Jg="0000000000000000",Wg="00000000000000000000000000000000",G8={traceId:Wg,spanId:Jg,traceFlags:od.NONE},Ds=(function(){function e(t){t===void 0&&(t=G8),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})(),sd=Bg("OpenTelemetry Context Key SPAN");function ad(e){return e.getValue(sd)||void 0}function K8(){return ad(Hi.getInstance().active())}function id(e,t){return e.setValue(sd,t)}function Y8(e){return e.deleteValue(sd)}function Q8(e,t){return id(e,new Ds(t))}function Gg(e){var t;return(t=ad(e))===null||t===void 0?void 0:t.spanContext()}var X8=/^([0-9a-f]{32})$/i,eE=/^[0-9a-f]{16}$/i;function tE(e){return X8.test(e)&&e!==Wg}function rE(e){return eE.test(e)&&e!==Jg}function Kg(e){return tE(e.traceId)&&rE(e.spanId)}function nE(e){return new Ds(e)}var ld=Hi.getInstance(),Yg=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=ld.active());var o=!!r?.root;if(o)return new Ds;var s=n&&Gg(n);return oE(s)&&Kg(s)?new Ds(s):new Ds},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??ld.active(),c=this.startSpan(t,s,l),u=id(l,c);return ld.with(u,i,void 0,c)}},e})();function oE(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var sE=new Yg,aE=(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):sE},e})(),iE=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Yg},e})(),lE=new iE,Qg=(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 aE(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:lE},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})(),Bi;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Bi||(Bi={}));var Xg=Hi.getInstance();$r.instance();var cE=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return O8},e})(),uE=new cE,cd="metrics",dE=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return qs(cd,t,$r.instance())},e.prototype.getMeterProvider=function(){return Bn(cd)||uE},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Ls(cd,$r.instance())},e})();dE.getInstance();var pE=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),ud=Bg("OpenTelemetry Baggage Key");function ey(e){return e.getValue(ud)||void 0}function fE(){return ey(Hi.getInstance().active())}function hE(e,t){return e.setValue(ud,t)}function mE(e){return e.deleteValue(ud)}var dd="propagation",gE=new pE,yE=(function(){function e(){this.createBaggage=k8,this.getBaggage=ey,this.getActiveBaggage=fE,this.setBaggage=hE,this.deleteBaggage=mE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return qs(dd,t,$r.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=Z8),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=z8),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Ls(dd,$r.instance())},e.prototype._getGlobalPropagator=function(){return Bn(dd)||gE},e})();yE.getInstance();var pd="trace",vE=(function(){function e(){this._proxyTracerProvider=new Qg,this.wrapSpanContext=nE,this.isSpanContextValid=Kg,this.deleteSpan=Y8,this.getSpan=ad,this.getActiveSpan=K8,this.getSpanContext=Gg,this.setSpan=id,this.setSpanContext=Q8}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=qs(pd,this._proxyTracerProvider,$r.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Bn(pd)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ls(pd,$r.instance()),this._proxyTracerProvider=new Qg},e})(),_E=vE.getInstance(),wE=Object.defineProperty,bE=(e,t)=>{for(var r in t)wE(e,r,{get:t[r],enumerable:!0})},ty="AI_InvalidArgumentError",ry=`vercel.ai.error.${ty}`,kE=Symbol.for(ry),ny,Rr=class extends ye{constructor({parameter:t,value:r,message:n}){super({name:ty,message:`Invalid argument for parameter ${t}: ${n}`}),this[ny]=!0,this.parameter=t,this.value=r}static isInstance(t){return ye.hasMarker(t,ry)}};ny=kE;var oy="AI_InvalidToolApprovalError",sy=`vercel.ai.error.${oy}`,TE=Symbol.for(sy),ay,CE=class extends ye{constructor({approvalId:e}){super({name:oy,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[ay]=!0,this.approvalId=e}static isInstance(e){return ye.hasMarker(e,sy)}};ay=TE;var iy="AI_InvalidToolInputError",ly=`vercel.ai.error.${iy}`,SE=Symbol.for(ly),cy,fd=class extends ye{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${jn(r)}`}){super({name:iy,message:n,cause:r}),this[cy]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ye.hasMarker(e,ly)}};cy=SE;var uy="AI_ToolCallNotFoundForApprovalError",dy=`vercel.ai.error.${uy}`,IE=Symbol.for(dy),py,hd=class extends ye{constructor({toolCallId:e,approvalId:t}){super({name:uy,message:`Tool call "${e}" not found for approval request "${t}".`}),this[py]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ye.hasMarker(e,dy)}};py=IE;var fy="AI_MissingToolResultsError",hy=`vercel.ai.error.${fy}`,EE=Symbol.for(hy),my,gy=class extends ye{constructor({toolCallIds:e}){super({name:fy,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 ye.hasMarker(e,hy)}};my=EE;var yy="AI_NoObjectGeneratedError",vy=`vercel.ai.error.${yy}`,xE=Symbol.for(vy),_y,vn=class extends ye{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:yy,message:e,cause:t}),this[_y]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ye.hasMarker(e,vy)}};_y=xE;var wy="AI_NoOutputGeneratedError",by=`vercel.ai.error.${wy}`,$E=Symbol.for(by),ky,Ty=class extends ye{constructor({message:e="No output generated.",cause:t}={}){super({name:wy,message:e,cause:t}),this[ky]=!0}static isInstance(e){return ye.hasMarker(e,by)}};ky=$E;var Cy="AI_NoSuchToolError",Sy=`vercel.ai.error.${Cy}`,RE=Symbol.for(Sy),Iy,md=class extends ye{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:Cy,message:r}),this[Iy]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ye.hasMarker(e,Sy)}};Iy=RE;var Ey="AI_ToolCallRepairError",xy=`vercel.ai.error.${Ey}`,PE=Symbol.for(xy),$y,ME=class extends ye{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${jn(e)}`}){super({name:Ey,message:r,cause:e}),this[$y]=!0,this.originalError=t}static isInstance(e){return ye.hasMarker(e,xy)}};$y=PE;var OE=class extends ye{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}},Ry="AI_UIMessageStreamError",Py=`vercel.ai.error.${Ry}`,AE=Symbol.for(Py),My,xo=class extends ye{constructor({chunkType:e,chunkId:t,message:r}){super({name:Ry,message:r}),this[My]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ye.hasMarker(e,Py)}};My=AE;var Oy="AI_InvalidMessageRoleError",Ay=`vercel.ai.error.${Oy}`,NE=Symbol.for(Ay),Ny,qE=class extends ye{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Oy,message:t}),this[Ny]=!0,this.role=e}static isInstance(e){return ye.hasMarker(e,Ay)}};Ny=NE;var qy="AI_RetryError",Ly=`vercel.ai.error.${qy}`,LE=Symbol.for(Ly),jy,Dy=class extends ye{constructor({message:e,reason:t,errors:r}){super({name:qy,message:e}),this[jy]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ye.hasMarker(e,Ly)}};jy=LE;function jE({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 DE="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Uy=!1,gd=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Uy||(Uy=!0,console.info(DE));for(const r of e.warnings)console.warn(jE({warning:r,provider:e.provider,model:e.model}))}};function UE({provider:e,modelId:t}){gd({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function zE(e){return e.specificationVersion==="v3"?e:(UE({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:zy(o.finishReason),usage:Zy(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:ZE(o.stream)}};default:return t[r]}}}))}function ZE(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:zy(t.finishReason),usage:Zy(t.usage)});break;default:r.enqueue(t);break}}}))}function zy(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function Zy(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 Ji(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new OE({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return zE(e)}return FE().languageModel(e)}function FE(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:a8}function yd(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function Fy(e){if(!(e==null||typeof e=="number"))return e.stepMs}function VE(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var HE=[{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]}],BE=e=>{const t=typeof e=="string"?Co(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function JE(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?BE(e):e}function WE({data:e,signatures:t}){const r=JE(e),n=typeof r=="string"?Co(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 Vy="6.0.85",GE=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:gn({},`ai-sdk/${Vy}`,Ms()),signal:r});if(!s.ok)throw new mn({url:o,statusCode:s.status,statusText:s.statusText});return{data:await Z2({response:s,url:o,maxBytes:t??Vu}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw mn.isInstance(s)?s:new mn({url:o,cause:s})}},KE=(e=GE)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function YE(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 Hy=oe([d(),di(Uint8Array),di(ArrayBuffer),Ah(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function By(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}=YE(e.toString());if(t==null||r==null)throw new ye({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function QE(e){return typeof e=="string"?e:e instanceof ArrayBuffer?So(new Uint8Array(e)):So(e)}function Us(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Jy({prompt:e,supportedUrls:t,download:r=KE()}){const n=await ex(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 f=o.get(u.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Us(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>XE({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 gy({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new gy({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function XE({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=>tx(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}=By(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:Wy(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:Wy(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 qE({role:n})}}}async function ex(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&&u5({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 tx(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}=By(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=WE({data:l,signatures:HE}))!=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 Wy(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 zs({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:Gy(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:Gy(r)}}function Gy(e){return e===void 0?null:e}function vd({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 Rr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Rr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Rr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Rr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Rr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Rr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Rr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Rr({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 rx(e){return e!=null&&Object.keys(e).length>0}async function Ky({tools:e,toolChoice:t,activeTools:r}){if(!rx(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 Fn(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 Zs=Wl(()=>oe([ui(),d(),j(),me(),ge(d(),Zs.optional()),q(Zs)])),it=ge(d(),ge(d(),Zs.optional())),Yy=C({type:P("text"),text:d(),providerOptions:it.optional()}),nx=C({type:P("image"),image:oe([Hy,di(URL)]),mediaType:d().optional(),providerOptions:it.optional()}),Qy=C({type:P("file"),data:oe([Hy,di(URL)]),filename:d().optional(),mediaType:d(),providerOptions:it.optional()}),ox=C({type:P("reasoning"),text:d(),providerOptions:it.optional()}),sx=C({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Le(),providerOptions:it.optional(),providerExecuted:me().optional()}),ax=tt("type",[C({type:P("text"),value:d(),providerOptions:it.optional()}),C({type:P("json"),value:Zs,providerOptions:it.optional()}),C({type:P("execution-denied"),reason:d().optional(),providerOptions:it.optional()}),C({type:P("error-text"),value:d(),providerOptions:it.optional()}),C({type:P("error-json"),value:Zs,providerOptions:it.optional()}),C({type:P("content"),value:q(oe([C({type:P("text"),text:d(),providerOptions:it.optional()}),C({type:P("media"),data:d(),mediaType:d()}),C({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:it.optional()}),C({type:P("file-url"),url:d(),providerOptions:it.optional()}),C({type:P("file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:it.optional()}),C({type:P("image-data"),data:d(),mediaType:d(),providerOptions:it.optional()}),C({type:P("image-url"),url:d(),providerOptions:it.optional()}),C({type:P("image-file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:it.optional()}),C({type:P("custom"),providerOptions:it.optional()})]))})]),Xy=C({type:P("tool-result"),toolCallId:d(),toolName:d(),output:ax,providerOptions:it.optional()}),ix=C({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),lx=C({type:P("tool-approval-response"),approvalId:d(),approved:me(),reason:d().optional()}),cx=C({role:P("system"),content:d(),providerOptions:it.optional()}),ux=C({role:P("user"),content:oe([d(),q(oe([Yy,nx,Qy]))]),providerOptions:it.optional()}),dx=C({role:P("assistant"),content:oe([d(),q(oe([Yy,Qy,ox,sx,Xy,ix]))]),providerOptions:it.optional()}),px=C({role:P("tool"),content:q(oe([Xy,lx])),providerOptions:it.optional()}),fx=oe([cx,ux,dx,px]);async function ev(e){if(e.prompt==null&&e.messages==null)throw new Dn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Dn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Us(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Dn({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 Dn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Dn({prompt:e,message:"messages must not be empty"});const r=await nr({value:t,schema:q(fx)});if(!r.success)throw new Dn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function tv(e){if(!td.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 ye({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
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 V1({message:s,statusCode:r,cause:n,generationId:o})}};function sy(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 on(e,t){var r;return Ft.isInstance(e)?e:sy(e)?oy.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ut.isInstance(e)?e.cause&&sy(e.cause)?oy.createTimeoutError({originalMessage:e.message,cause:e}):await Xg({response:JI(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Xg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function JI(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 ay="ai-gateway-auth-method";async function eo(e){const t=await cr({value:e[ay],schema:WI});return t.success?t.value:void 0}var WI=Ce(()=>Te(oe([R("api-key"),R("oidc")]))),iy=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await cg({url:`${this.config.baseURL}/config`,headers:await Gt(this.config.headers()),successfulResponseHandler:dr(GI),failedResponseHandler:En({errorSchema:kt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await on(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await cg({url:`${e.origin}/v1/credits`,headers:await Gt(this.config.headers()),successfulResponseHandler:dr(KI),failedResponseHandler:En({errorSchema:kt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await on(e)}}},GI=Ce(()=>Te(T({models:q(T({id:d(),name:d(),description:d().nullish(),pricing:T({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:T({specificationVersion:R("v3"),provider:d(),modelId:d()}),modelType:me(["embedding","image","language","video"]).nullish()}))}))),KI=Ce(()=>Te(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),YI=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 Gt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Wt({url:this.getUrl(),headers:At(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Gt(this.config.o11yHeaders)),body:t,successfulResponseHandler:dr(kt()),failedResponseHandler:En({errorSchema:kt(),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 on(s,await eo(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Gt(this.config.headers());try{const{value:s,responseHeaders:a}=await Wt({url:this.getUrl(),headers:At(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Gt(this.config.o11yHeaders)),body:t,successfulResponseHandler:rl(kt()),failedResponseHandler:En({errorSchema:kt(),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 on(s,await eo(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)}}},QI=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 Gt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Wt({url:this.getUrl(),headers:At(s,t??{},this.getModelConfigHeaders(),await Gt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:dr(XI),failedResponseHandler:En({errorSchema:kt(),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 on(a,await eo(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},XI=Ce(()=>Te(T({embeddings:q(q(j())),usage:T({tokens:j()}).nullish(),providerMetadata:ye(d(),ye(d(),Me())).optional()}))),ex=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 Gt(this.config.headers());try{const{responseHeaders:_,value:y,rawValue:w}=await Wt({url:this.getUrl(),headers:At(g,l??{},this.getModelConfigHeaders(),await Gt(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=>ly(v))},...a&&{mask:ly(a)}},successfulResponseHandler:dr(ox),failedResponseHandler:En({errorSchema:kt(),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 on(_,await eo(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function ly(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Oo(e.data)}:e}var tx=T({images:q(Me()).optional()}).catchall(Me()),rx=ze("type",[T({type:R("unsupported"),feature:d(),details:d().optional()}),T({type:R("compatibility"),feature:d(),details:d().optional()}),T({type:R("other"),message:d()})]),nx=T({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),ox=T({images:q(d()),warnings:q(rx).optional(),providerMetadata:ye(d(),tx).optional(),usage:nx.optional()}),sx=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 Gt(this.config.headers());try{const{responseHeaders:f,value:g}=await Wt({url:this.getUrl(),headers:At(p,c??{},this.getModelConfigHeaders(),await Gt(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:ax(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=vg({stream:_.body,schema:ux}).getReader(),{done:C,value:k}=await m.read();if(m.releaseLock(),C||!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 b=k.value;if(b.type==="error")throw new ut({message:b.message,statusCode:b.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([..._.headers]),responseBody:JSON.stringify(b),data:{error:{message:b.message,type:b.errorType,param:b.param}}});return{value:{videos:b.videos,warnings:b.warnings,providerMetadata:b.providerMetadata},responseHeaders:Object.fromEntries([..._.headers])}},failedResponseHandler:En({errorSchema:kt(),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 on(f,await eo(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function ax(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Oo(e.data)}:e}var ix=T({videos:q(Me()).optional()}).catchall(Me()),lx=oe([T({type:R("url"),url:d(),mediaType:d()}),T({type:R("base64"),data:d(),mediaType:d()})]),cx=ze("type",[T({type:R("unsupported"),feature:d(),details:d().optional()}),T({type:R("compatibility"),feature:d(),details:d().optional()}),T({type:R("other"),message:d()})]),ux=ze("type",[T({type:R("result"),videos:q(lx),warnings:q(cx).optional(),providerMetadata:ye(d(),ix).optional()}),T({type:R("error"),message:d(),errorType:d(),statusCode:j(),param:Me().nullable()})]),dx=Ce(()=>Te(Vt({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:Yr(Fe()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:ls(["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:Vt({include_domains:Yr(Fe()).optional().describe("List of domains to include in search results."),exclude_domains:Yr(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:Vt({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:Vt({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.")}))),px=Ce(()=>Te(fi([Vt({searchId:Fe(),results:Yr(Vt({url:Fe(),title:Fe(),excerpt:Fe(),publishDate:Fe().nullable().optional(),relevanceScore:sr().optional()}))}),Vt({error:ls(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:sr().optional(),message:Fe()})]))),fx=xr({id:"gateway.parallel_search",inputSchema:dx,outputSchema:px}),hx=(e={})=>fx(e),mx=Ce(()=>Te(Vt({query:fi([Fe(),Yr(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:Yr(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:Yr(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:ls(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),gx=Ce(()=>Te(fi([Vt({results:Yr(Vt({title:Fe(),url:Fe(),snippet:Fe(),date:Fe().optional(),lastUpdated:Fe().optional()})),id:Fe()}),Vt({error:ls(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:sr().optional(),message:Fe()})]))),yx=xr({id:"gateway.perplexity_search",inputSchema:mx,outputSchema:gx}),vx=(e={})=>yx(e),_x={parallelSearch:hx,perplexitySearch:vx};async function wx(){var e;return(e=Sg.getContext().headers)==null?void 0:e["x-vercel-id"]}var bx="3.0.58",kx="0.0.1";function Tx(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=kg(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const _=await Sx(e);return xn({Authorization:`Bearer ${_.token}`,"ai-gateway-protocol-version":kx,[ay]:_.authMethod,...e.headers},`ai-sdk/gateway/${bx}`)}catch(_){throw _d.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:_})}},c=()=>{const _=Ao({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Ao({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=Ao({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),v=Ao({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const m=await wx();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 YI(_,{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 iy({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(m=>(o=m,m)).catch(async m=>{throw await on(m,await eo(await l()))})),o?Promise.resolve(o):n},p=async()=>new iy({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async _=>{throw await on(_,await eo(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 ex(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=_=>new QI(_,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=_=>new sx(_,{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=_x,f}var Cx=Tx();async function Sx(e){const t=Ao({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Sg.getVercelOidcToken(),authMethod:"oidc"}}var Ix=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},to="1.9.0",cy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function xx(e){var t=new Set([e]),r=new Set,n=e.match(cy);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(cy);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 Ex=xx(to),$x=to.split(".")[0],Fs=Symbol.for("opentelemetry.js.api."+$x),Vs=Ix;function Hs(e,t,r,n){var o;n===void 0&&(n=!1);var s=Vs[Fs]=(o=Vs[Fs])!==null&&o!==void 0?o:{version:to};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!==to){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+to);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+to+"."),!0}function ro(e){var t,r,n=(t=Vs[Fs])===null||t===void 0?void 0:t.version;if(!(!n||!Ex(n)))return(r=Vs[Fs])===null||r===void 0?void 0:r[e]}function Bs(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+to+".");var r=Vs[Fs];r&&delete r[e]}var Rx=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},Px=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))},Mx=(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 Js("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Js("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Js("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Js("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Js("verbose",this._namespace,t)},e})();function Js(e,t,r){var n=ro("diag");if(n)return r.unshift(t),n[e].apply(n,Px([],Rx(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 Ox(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 Nx=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))},qx="diag",Dr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=ro("diag");if(i)return i[o].apply(i,Ax([],Nx(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=ro("diag"),h=Ox((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 Hs("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Bs(qx,r)},r.createComponentLogger=function(o){return new Mx(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})(),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},jx=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.")},Dx=(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=Lx(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=jx(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})();Dr.instance();function Ux(e){return e===void 0&&(e={}),new Dx(new Map(Object.entries(e)))}function uy(e){return Symbol.for(e)}var zx=(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})(),Zx=new zx,no=(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)}})(),Fx=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Xx},e.prototype.createHistogram=function(t,r){return eE},e.prototype.createCounter=function(t,r){return Qx},e.prototype.createUpDownCounter=function(t,r){return tE},e.prototype.createObservableGauge=function(t,r){return nE},e.prototype.createObservableCounter=function(t,r){return rE},e.prototype.createObservableUpDownCounter=function(t,r){return oE},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),nl=(function(){function e(){}return e})(),Vx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(nl),Hx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(nl),Bx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(nl),Jx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(nl),wd=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Wx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(wd),Gx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(wd),Kx=(function(e){no(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(wd),Yx=new Fx,Qx=new Vx,Xx=new Bx,eE=new Jx,tE=new Hx,rE=new Wx,nE=new Gx,oE=new Kx,sE={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},aE={set:function(e,t,r){e!=null&&(e[t]=r)}},iE=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},lE=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))},cE=(function(){function e(){}return e.prototype.active=function(){return Zx},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,lE([n],iE(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),uE=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},dE=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))},bd="context",pE=new cE,ol=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Hs(bd,t,Dr.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,dE([t,r,n],uE(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return ro(bd)||pE},e.prototype.disable=function(){this._getContextManager().disable(),Bs(bd,Dr.instance())},e})(),kd;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(kd||(kd={}));var dy="0000000000000000",py="00000000000000000000000000000000",fE={traceId:py,spanId:dy,traceFlags:kd.NONE},Ws=(function(){function e(t){t===void 0&&(t=fE),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})(),Td=uy("OpenTelemetry Context Key SPAN");function Cd(e){return e.getValue(Td)||void 0}function hE(){return Cd(ol.getInstance().active())}function Sd(e,t){return e.setValue(Td,t)}function mE(e){return e.deleteValue(Td)}function gE(e,t){return Sd(e,new Ws(t))}function fy(e){var t;return(t=Cd(e))===null||t===void 0?void 0:t.spanContext()}var yE=/^([0-9a-f]{32})$/i,vE=/^[0-9a-f]{16}$/i;function _E(e){return yE.test(e)&&e!==py}function wE(e){return vE.test(e)&&e!==dy}function hy(e){return _E(e.traceId)&&wE(e.spanId)}function bE(e){return new Ws(e)}var Id=ol.getInstance(),my=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Id.active());var o=!!r?.root;if(o)return new Ws;var s=n&&fy(n);return kE(s)&&hy(s)?new Ws(s):new Ws},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??Id.active(),c=this.startSpan(t,s,l),u=Sd(l,c);return Id.with(u,i,void 0,c)}},e})();function kE(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var TE=new my,CE=(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):TE},e})(),SE=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new my},e})(),IE=new SE,gy=(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 CE(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:IE},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})(),sl;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(sl||(sl={}));var yy=ol.getInstance();Dr.instance();var xE=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return Yx},e})(),EE=new xE,xd="metrics",$E=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Hs(xd,t,Dr.instance())},e.prototype.getMeterProvider=function(){return ro(xd)||EE},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Bs(xd,Dr.instance())},e})();$E.getInstance();var RE=(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=uy("OpenTelemetry Baggage Key");function vy(e){return e.getValue(Ed)||void 0}function PE(){return vy(ol.getInstance().active())}function ME(e,t){return e.setValue(Ed,t)}function OE(e){return e.deleteValue(Ed)}var $d="propagation",NE=new RE,AE=(function(){function e(){this.createBaggage=Ux,this.getBaggage=vy,this.getActiveBaggage=PE,this.setBaggage=ME,this.deleteBaggage=OE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Hs($d,t,Dr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=aE),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=sE),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Bs($d,Dr.instance())},e.prototype._getGlobalPropagator=function(){return ro($d)||NE},e})();AE.getInstance();var Rd="trace",qE=(function(){function e(){this._proxyTracerProvider=new gy,this.wrapSpanContext=bE,this.isSpanContextValid=hy,this.deleteSpan=mE,this.getSpan=Cd,this.getActiveSpan=hE,this.getSpanContext=fy,this.setSpan=Sd,this.setSpanContext=gE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Hs(Rd,this._proxyTracerProvider,Dr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return ro(Rd)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Bs(Rd,Dr.instance()),this._proxyTracerProvider=new gy},e})(),LE=qE.getInstance(),jE=Object.defineProperty,DE=(e,t)=>{for(var r in t)jE(e,r,{get:t[r],enumerable:!0})},_y="AI_InvalidArgumentError",wy=`vercel.ai.error.${_y}`,UE=Symbol.for(wy),by,Ur=class extends ve{constructor({parameter:t,value:r,message:n}){super({name:_y,message:`Invalid argument for parameter ${t}: ${n}`}),this[by]=!0,this.parameter=t,this.value=r}static isInstance(t){return ve.hasMarker(t,wy)}};by=UE;var ky="AI_InvalidToolApprovalError",Ty=`vercel.ai.error.${ky}`,zE=Symbol.for(Ty),Cy,ZE=class extends ve{constructor({approvalId:e}){super({name:ky,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Cy]=!0,this.approvalId=e}static isInstance(e){return ve.hasMarker(e,Ty)}};Cy=zE;var Sy="AI_InvalidToolInputError",Iy=`vercel.ai.error.${Sy}`,FE=Symbol.for(Iy),xy,Pd=class extends ve{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Wn(r)}`}){super({name:Sy,message:n,cause:r}),this[xy]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ve.hasMarker(e,Iy)}};xy=FE;var Ey="AI_ToolCallNotFoundForApprovalError",$y=`vercel.ai.error.${Ey}`,VE=Symbol.for($y),Ry,Md=class extends ve{constructor({toolCallId:e,approvalId:t}){super({name:Ey,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Ry]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ve.hasMarker(e,$y)}};Ry=VE;var Py="AI_MissingToolResultsError",My=`vercel.ai.error.${Py}`,HE=Symbol.for(My),Oy,Ny=class extends ve{constructor({toolCallIds:e}){super({name:Py,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Oy]=!0,this.toolCallIds=e}static isInstance(e){return ve.hasMarker(e,My)}};Oy=HE;var Ay="AI_NoObjectGeneratedError",qy=`vercel.ai.error.${Ay}`,BE=Symbol.for(qy),Ly,$n=class extends ve{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Ay,message:e,cause:t}),this[Ly]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ve.hasMarker(e,qy)}};Ly=BE;var jy="AI_NoOutputGeneratedError",Dy=`vercel.ai.error.${jy}`,JE=Symbol.for(Dy),Uy,zy=class extends ve{constructor({message:e="No output generated.",cause:t}={}){super({name:jy,message:e,cause:t}),this[Uy]=!0}static isInstance(e){return ve.hasMarker(e,Dy)}};Uy=JE;var Zy="AI_NoSuchToolError",Fy=`vercel.ai.error.${Zy}`,WE=Symbol.for(Fy),Vy,Od=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[Vy]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ve.hasMarker(e,Fy)}};Vy=WE;var Hy="AI_ToolCallRepairError",By=`vercel.ai.error.${Hy}`,GE=Symbol.for(By),Jy,KE=class extends ve{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Wn(e)}`}){super({name:Hy,message:r,cause:e}),this[Jy]=!0,this.originalError=t}static isInstance(e){return ve.hasMarker(e,By)}};Jy=GE;var YE=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}},Wy="AI_UIMessageStreamError",Gy=`vercel.ai.error.${Wy}`,QE=Symbol.for(Gy),Ky,Lo=class extends ve{constructor({chunkType:e,chunkId:t,message:r}){super({name:Wy,message:r}),this[Ky]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ve.hasMarker(e,Gy)}};Ky=QE;var Yy="AI_InvalidMessageRoleError",Qy=`vercel.ai.error.${Yy}`,XE=Symbol.for(Qy),Xy,e8=class extends ve{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Yy,message:t}),this[Xy]=!0,this.role=e}static isInstance(e){return ve.hasMarker(e,Qy)}};Xy=XE;var ev="AI_RetryError",tv=`vercel.ai.error.${ev}`,t8=Symbol.for(tv),rv,nv=class extends ve{constructor({message:e,reason:t,errors:r}){super({name:ev,message:e}),this[rv]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ve.hasMarker(e,tv)}};rv=t8;function jo(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Er(e){for(const t of jo(e.callbacks))try{await t(e.event)}catch{}}function r8({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 n8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",ov=!1,Nd=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}ov||(ov=!0,console.info(n8));for(const r of e.warnings)console.warn(r8({warning:r,provider:e.provider,model:e.model}))}};function o8({provider:e,modelId:t}){Nd({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function s8(e){return e.specificationVersion==="v3"?e:(o8({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:sv(o.finishReason),usage:av(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:a8(o.stream)}};default:return t[r]}}}))}function a8(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:sv(t.finishReason),usage:av(t.usage)});break;default:r.enqueue(t);break}}}))}function sv(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function av(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 al(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new YE({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return s8(e)}return i8().languageModel(e)}function i8(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Cx}function Ad(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function iv(e){if(!(e==null||typeof e=="number"))return e.stepMs}function l8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var c8=[{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]}],u8=e=>{const t=typeof e=="string"?Mo(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function d8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?u8(e):e}function p8({data:e,signatures:t}){const r=d8(e),n=typeof r=="string"?Mo(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 lv="6.0.104",f8=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:xn({},`ai-sdk/${lv}`,Zs()),signal:r});if(!s.ok)throw new In({url:o,statusCode:s.status,statusText:s.statusText});return{data:await sg({response:s,url:o,maxBytes:t??ld}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw In.isInstance(s)?s:new In({url:o,cause:s})}},h8=(e=f8)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function m8(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 cv=oe([d(),Ci(Uint8Array),Ci(ArrayBuffer),Yh(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function uv(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}=m8(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 g8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Oo(new Uint8Array(e)):Oo(e)}async function dv({prompt:e,supportedUrls:t,download:r=h8()}){const n=await v8(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}]:jo(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>y8({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 Ny({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Ny({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function y8({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=>_8(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}=uv(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:pv(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:pv(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 e8({role:n})}}}async function v8(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&&$5({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 _8(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}=uv(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=p8({data:l,signatures:c8}))!=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 pv(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 Gs({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Wn(r)}:o==="json"?{type:"error-json",value:fv(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:fv(r)}}function fv(e){return e===void 0?null:e}function qd({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 Ur({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Ur({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Ur({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Ur({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Ur({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Ur({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Ur({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Ur({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 w8(e){return e!=null&&Object.keys(e).length>0}async function hv({tools:e,toolChoice:t,activeTools:r}){if(!w8(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 Xn(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 Ks=pc(()=>oe([Ti(),d(),j(),he(),ye(d(),Ks.optional()),q(Ks)])),dt=ye(d(),ye(d(),Ks.optional())),mv=T({type:R("text"),text:d(),providerOptions:dt.optional()}),b8=T({type:R("image"),image:oe([cv,Ci(URL)]),mediaType:d().optional(),providerOptions:dt.optional()}),gv=T({type:R("file"),data:oe([cv,Ci(URL)]),filename:d().optional(),mediaType:d(),providerOptions:dt.optional()}),k8=T({type:R("reasoning"),text:d(),providerOptions:dt.optional()}),T8=T({type:R("tool-call"),toolCallId:d(),toolName:d(),input:Me(),providerOptions:dt.optional(),providerExecuted:he().optional()}),C8=ze("type",[T({type:R("text"),value:d(),providerOptions:dt.optional()}),T({type:R("json"),value:Ks,providerOptions:dt.optional()}),T({type:R("execution-denied"),reason:d().optional(),providerOptions:dt.optional()}),T({type:R("error-text"),value:d(),providerOptions:dt.optional()}),T({type:R("error-json"),value:Ks,providerOptions:dt.optional()}),T({type:R("content"),value:q(oe([T({type:R("text"),text:d(),providerOptions:dt.optional()}),T({type:R("media"),data:d(),mediaType:d()}),T({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:dt.optional()}),T({type:R("file-url"),url:d(),providerOptions:dt.optional()}),T({type:R("file-id"),fileId:oe([d(),ye(d(),d())]),providerOptions:dt.optional()}),T({type:R("image-data"),data:d(),mediaType:d(),providerOptions:dt.optional()}),T({type:R("image-url"),url:d(),providerOptions:dt.optional()}),T({type:R("image-file-id"),fileId:oe([d(),ye(d(),d())]),providerOptions:dt.optional()}),T({type:R("custom"),providerOptions:dt.optional()})]))})]),yv=T({type:R("tool-result"),toolCallId:d(),toolName:d(),output:C8,providerOptions:dt.optional()}),S8=T({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),I8=T({type:R("tool-approval-response"),approvalId:d(),approved:he(),reason:d().optional()}),x8=T({role:R("system"),content:d(),providerOptions:dt.optional()}),E8=T({role:R("user"),content:oe([d(),q(oe([mv,b8,gv]))]),providerOptions:dt.optional()}),$8=T({role:R("assistant"),content:oe([d(),q(oe([mv,gv,k8,T8,yv,S8]))]),providerOptions:dt.optional()}),R8=T({role:R("tool"),content:q(oe([yv,I8])),providerOptions:dt.optional()}),P8=oe([x8,E8,$8,R8]);async function vv(e){if(e.prompt==null&&e.messages==null)throw new Gn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Gn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!jo(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Gn({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 Gn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Gn({prompt:e,message:"messages must not be empty"});const r=await cr({value:t,schema:q(P8)});if(!r.success)throw new Gn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function _v(e){if(!_d.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
573
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
574
574
 
@@ -576,25 +576,25 @@ Alternatively, you can use a provider module instead of the AI Gateway.
576
576
 
577
577
  Learn more: \x1B[34m${r}\x1B[0m
578
578
 
579
- `),{name:"GatewayAuthenticationError"})}function Fs({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 rv({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=yd(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 hx={startSpan(){return Wi},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Wi);if(typeof r=="function")return r(Wi);if(typeof n=="function")return n(Wi)}},Wi={spanContext(){return mx},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}},mx={traceId:"",spanId:"",traceFlags:0};function nv({isEnabled:e=!1,tracer:t}={}){return e?t||_E.getTracer("ai"):hx}async function Vs({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=Xg.active();try{const i=await Xg.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{ov(s,i)}finally{s.end()}throw i}})}function ov(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Bi.ERROR,message:t.message})):e.setStatus({code:Bi.ERROR})}async function Pr({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 sv(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?QE(r.data):r.data}:r)})))}function av(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:wr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function _d(){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 iv(e,t){var r,n,o,s,a,i,l,c,u,f;return{inputTokens:wr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:wr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:wr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:wr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:wr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:wr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:wr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:wr(e.totalTokens,t.totalTokens),reasoningTokens:wr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:wr(e.cachedInputTokens,t.cachedInputTokens)}}function wr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Gi(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]=Gi(s,o):r[n]=o}return r}function gx({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 yx=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>lv(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function lv(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(zn(a)||t===0)throw a;const i=Hu(a),l=[...s,a],c=l.length;if(c>t)throw new Dy({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&ht.isInstance(a)&&a.isRetryable===!0&&c<=t)return await X6(gx({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),lv(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new Dy({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function cv({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Rr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Rr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:yx({maxRetries:r,abortSignal:t})}}function uv({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 CE({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new hd({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}async function wd({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,onPreliminaryToolResult:i}){const{toolName:l,toolCallId:c,input:u}=e,f=t?.[l];if(f?.execute!=null)return Vs({name:"ai.toolCall",attributes:Pr({telemetry:n,attributes:{...Fs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async p=>{let h;try{const y=pI({execute:f.execute.bind(f),input:u,options:{toolCallId:c,messages:o,abortSignal:s,experimental_context:a}});for await(const w of y)w.type==="preliminary"?i?.({...e,type:"tool-result",output:w.output,preliminary:!0}):h=w.output}catch(y){return ov(p,y),{type:"tool-error",toolCallId:c,toolName:l,input:u,error:y,dynamic:f.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}try{p.setAttributes(await Pr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(h)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:u,output:h,dynamic:f.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function dv(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
580
- `)}function pv(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var fv=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=So(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Co(this.base64Data)),this.uint8ArrayData}},vx=class extends fv{constructor(e){super(e),this.type="file"}};async function hv({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 _x={};bE(_x,{array:()=>kx,choice:()=>Tx,json:()=>Cx,object:()=>bx,text:()=>Ki});function wx(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 f=e.substring(n,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(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 Hs(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await or({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await or({text:wx(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Ki=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),bx=({schema:e,name:t,description:r})=>{const n=Fn(e);return{name:"object",responseFormat:Ft(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await or({text:o});if(!a.success)throw new vn({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 nr({value:a.value,schema:n});if(!i.success)throw new vn({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 Hs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},kx=({element:e,name:t,description:r})=>{const n=Fn(e);return{name:"array",responseFormat:Ft(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 or({text:o});if(!a.success)throw new vn({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 vn({message:"No object generated: response did not match schema.",cause:new Un({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 nr({value:l,schema:n});if(!c.success)throw new vn({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 Hs(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 nr({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])}})}}},Tx=({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 or({text:n});if(!s.success)throw new vn({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 vn({message:"No object generated: response did not match schema.",cause:new Un({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 Hs(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(){}}),Cx=({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 or({text:r});if(!o.success)throw new vn({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 Hs(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 gv(e);throw new md({toolName:e.toolName})}try{return await yv({toolCall:e,tools:t})}catch(a){if(r==null||!(md.isInstance(a)||fd.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 Fn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new ME({cause:l,originalError:a})}if(i==null)throw a;return await yv({toolCall:i,tools:t})}}catch(a){const i=await or({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 gv(e){const t=e.input.trim()===""?{success:!0,value:{}}:await or({text:e.input});if(t.success===!1)throw new fd({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 yv({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await gv(e);throw new md({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Fn(n.inputSchema),s=e.input.trim()===""?await nr({value:{},schema:o}):await or({text:e.input,schema:o});if(s.success===!1)throw new fd({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 vv=class{constructor({content:e,finishReason:t,rawFinishReason:r,usage:n,warnings:o,request:s,response:a,providerMetadata:i}){this.content=e,this.finishReason=t,this.rawFinishReason=r,this.usage=n,this.warnings=o,this.request=s,this.response=a,this.providerMetadata=i}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 bd(e){return({steps:t})=>t.length===e}async function _v({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function kd({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 zs({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 zs({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 zs({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 wv(...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 Sx=Ps({prefix:"aitxt",size:24});async function bv({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=bd(1),experimental_output:f,output:p=f,experimental_telemetry:h,providerOptions:y,experimental_activeTools:w,activeTools:g=w,experimental_prepareStep:b,prepareStep:v=b,experimental_repairToolCall:m,experimental_download:T,experimental_context:k,experimental_include:_,_internal:{generateId:S=Sx}={},onStepFinish:$,onFinish:x,...U}){const M=Ji(e),O=Us(u),A=yd(l),L=Fy(l),Y=L!=null?new AbortController:void 0,J=wv(i,A!=null?AbortSignal.timeout(A):void 0,Y?.signal),{maxRetries:de,retry:K}=cv({maxRetries:a,abortSignal:J}),$e=vd(U),Z=gn(c??{},`ai/${Vy}`),N=rv({model:M,telemetry:h,headers:Z,settings:{...$e,maxRetries:de}}),H=await ev({system:n,prompt:o,messages:s}),z=nv(h);try{return await Vs({name:"ai.generateText",attributes:Pr({telemetry:h,attributes:{...Fs({operationId:"ai.generateText",telemetry:h}),...N,"ai.model.provider":M.provider,"ai.model.id":M.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:z,fn:async I=>{var E,V,te,Q,_e,xe,D,F,G,ee,pe;const ke=H.messages,R=[],{approvedToolApprovals:re,deniedToolApprovals:ve}=uv({messages:ke}),Te=re.filter(Je=>!Je.toolCall.providerExecuted);if(ve.length>0||Te.length>0){const Je=await kv({toolCalls:Te.map(Se=>Se.toolCall),tools:t,tracer:z,telemetry:h,messages:ke,abortSignal:J,experimental_context:k}),St=[];for(const Se of Je){const et=await zs({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"});St.push({type:"tool-result",toolCallId:Se.toolCallId,toolName:Se.toolName,output:et})}for(const Se of ve)St.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}}}}});R.push({role:"tool",content:St})}const Re=[...re,...ve].filter(Je=>Je.toolCall.providerExecuted);Re.length>0&&R.push({role:"tool",content:Re.map(Je=>({type:"tool-approval-response",approvalId:Je.approvalResponse.approvalId,approved:Je.approvalResponse.approved,reason:Je.approvalResponse.reason,providerExecuted:!0}))});const Xe=vd(U);let ie,lt=[],Ct=[];const ne=[],ze=new Map;do{const Je=L!=null?setTimeout(()=>Y.abort(),L):void 0;try{const St=[...ke,...R],Se=await v?.({model:M,steps:ne,stepNumber:ne.length,messages:St,experimental_context:k}),et=Ji((E=Se?.model)!=null?E:M),ct=await Jy({prompt:{system:(V=Se?.system)!=null?V:H.system,messages:(te=Se?.messages)!=null?te:St},supportedUrls:await et.supportedUrls,download:T});k=(Q=Se?.experimental_context)!=null?Q:k;const{toolChoice:_n,tools:Po}=await Ky({tools:t,toolChoice:(_e=Se?.toolChoice)!=null?_e:r,activeTools:(xe=Se?.activeTools)!=null?xe:g});ie=await K(()=>{var Pe;return Vs({name:"ai.generateText.doGenerate",attributes:Pr({telemetry:h,attributes:{...Fs({operationId:"ai.generateText.doGenerate",telemetry:h}),...N,"ai.model.provider":et.provider,"ai.model.id":et.modelId,"ai.prompt.messages":{input:()=>sv(ct)},"ai.prompt.tools":{input:()=>Po?.map(Rt=>JSON.stringify(Rt))},"ai.prompt.toolChoice":{input:()=>_n!=null?JSON.stringify(_n):void 0},"gen_ai.system":et.provider,"gen_ai.request.model":et.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":(Pe=U.temperature)!=null?Pe:void 0,"gen_ai.request.top_k":U.topK,"gen_ai.request.top_p":U.topP}}),tracer:z,fn:async Rt=>{var Kn,Qr,dl,pl,Xs,Mo,Xr,ea;const Ud=Gi(y,Se?.providerOptions),vt=await et.doGenerate({...Xe,tools:Po,toolChoice:_n,responseFormat:await p?.responseFormat,prompt:ct,providerOptions:Ud,abortSignal:J,headers:Z}),sr={id:(Qr=(Kn=vt.response)==null?void 0:Kn.id)!=null?Qr:S(),timestamp:(pl=(dl=vt.response)==null?void 0:dl.timestamp)!=null?pl:new Date,modelId:(Mo=(Xs=vt.response)==null?void 0:Xs.modelId)!=null?Mo:et.modelId,headers:(Xr=vt.response)==null?void 0:Xr.headers,body:(ea=vt.response)==null?void 0:ea.body};return Rt.setAttributes(await Pr({telemetry:h,attributes:{"ai.response.finishReason":vt.finishReason.unified,"ai.response.text":{output:()=>pv(vt.content)},"ai.response.reasoning":{output:()=>dv(vt.content)},"ai.response.toolCalls":{output:()=>{const bn=Tv(vt.content);return bn==null?void 0:JSON.stringify(bn)}},"ai.response.id":sr.id,"ai.response.model":sr.modelId,"ai.response.timestamp":sr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(vt.providerMetadata),"ai.usage.promptTokens":vt.usage.inputTokens.total,"ai.usage.completionTokens":vt.usage.outputTokens.total,"gen_ai.response.finish_reasons":[vt.finishReason.unified],"gen_ai.response.id":sr.id,"gen_ai.response.model":sr.modelId,"gen_ai.usage.input_tokens":vt.usage.inputTokens.total,"gen_ai.usage.output_tokens":vt.usage.outputTokens.total}})),{...vt,response:sr}}})});const wn=await Promise.all(ie.content.filter(Pe=>Pe.type==="tool-call").map(Pe=>mv({toolCall:Pe,tools:t,repairToolCall:m,system:n,messages:St}))),Mr={};for(const Pe of wn){if(Pe.invalid)continue;const Rt=t?.[Pe.toolName];Rt!=null&&(Rt?.onInputAvailable!=null&&await Rt.onInputAvailable({input:Pe.input,toolCallId:Pe.toolCallId,messages:St,abortSignal:J,experimental_context:k}),await hv({tool:Rt,toolCall:Pe,messages:St,experimental_context:k})&&(Mr[Pe.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Pe}))}const Dd=wn.filter(Pe=>Pe.invalid&&Pe.dynamic);Ct=[];for(const Pe of Dd)Ct.push({type:"tool-error",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:Pe.input,error:Hu(Pe.error),dynamic:!0});lt=wn.filter(Pe=>!Pe.providerExecuted),t!=null&&Ct.push(...await kv({toolCalls:lt.filter(Pe=>!Pe.invalid&&Mr[Pe.toolCallId]==null),tools:t,tracer:z,telemetry:h,messages:St,abortSignal:J,experimental_context:k}));for(const Pe of wn){if(!Pe.providerExecuted)continue;const Rt=t?.[Pe.toolName];Rt?.type==="provider"&&Rt.supportsDeferredResults&&(ie.content.some(Qr=>Qr.type==="tool-result"&&Qr.toolCallId===Pe.toolCallId)||ze.set(Pe.toolCallId,{toolName:Pe.toolName}))}for(const Pe of ie.content)Pe.type==="tool-result"&&ze.delete(Pe.toolCallId);const Qs=Ex({content:ie.content,toolCalls:wn,toolOutputs:Ct,toolApprovalRequests:Object.values(Mr),tools:t});R.push(...await kd({content:Qs,tools:t}));const ul=(D=_?.requestBody)==null||D?(F=ie.request)!=null?F:{}:{...ie.request,body:void 0},Gn={...ie.response,messages:structuredClone(R),body:(G=_?.responseBody)==null||G?(ee=ie.response)==null?void 0:ee.body:void 0},It=new vv({content:Qs,finishReason:ie.finishReason.unified,rawFinishReason:ie.finishReason.raw,usage:av(ie.usage),warnings:ie.warnings,providerMetadata:ie.providerMetadata,request:ul,response:Gn});gd({warnings:(pe=ie.warnings)!=null?pe:[],provider:et.provider,model:et.modelId}),ne.push(It),await $?.(It)}finally{Je!=null&&clearTimeout(Je)}}while((lt.length>0&&Ct.length===lt.length||ze.size>0)&&!await _v({stopConditions:O,steps:ne}));I.setAttributes(await Pr({telemetry:h,attributes:{"ai.response.finishReason":ie.finishReason.unified,"ai.response.text":{output:()=>pv(ie.content)},"ai.response.reasoning":{output:()=>dv(ie.content)},"ai.response.toolCalls":{output:()=>{const Je=Tv(ie.content);return Je==null?void 0:JSON.stringify(Je)}},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.promptTokens":ie.usage.inputTokens.total,"ai.usage.completionTokens":ie.usage.outputTokens.total}}));const De=ne[ne.length-1],kr=ne.reduce((Je,St)=>iv(Je,St.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await x?.({finishReason:De.finishReason,rawFinishReason:De.rawFinishReason,usage:De.usage,content:De.content,text:De.text,reasoningText:De.reasoningText,reasoning:De.reasoning,files:De.files,sources:De.sources,toolCalls:De.toolCalls,staticToolCalls:De.staticToolCalls,dynamicToolCalls:De.dynamicToolCalls,toolResults:De.toolResults,staticToolResults:De.staticToolResults,dynamicToolResults:De.dynamicToolResults,request:De.request,response:De.response,warnings:De.warnings,providerMetadata:De.providerMetadata,steps:ne,totalUsage:kr,experimental_context:k});let Yr;return De.finishReason==="stop"&&(Yr=await(p??Ki()).parseCompleteOutput({text:De.text},{response:De.response,usage:De.usage,finishReason:De.finishReason})),new Ix({steps:ne,totalUsage:kr,output:Yr})}})}catch(I){throw tv(I)}}async function kv({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async l=>wd({toolCall:l,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a})))).filter(l=>l!=null)}var Ix=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 Ty;return this._output}};function Tv(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 Ex({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 fv(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 hd({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function Yi(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 xx({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Yi(r,{"content-type":"text/plain; charset=utf-8"})})}function Cv({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(f=>{e.once("drain",f)})}}catch(l){throw l}finally{e.end()}})()}function $x({response:e,status:t,statusText:r,headers:n,textStream:o}){Cv({response:e,status:t,statusText:r,headers:Object.fromEntries(Yi(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var Sv=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
579
+ `),{name:"GatewayAuthenticationError"})}function Ys({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 wv({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=Ad(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 M8={startSpan(){return il},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(il);if(typeof r=="function")return r(il);if(typeof n=="function")return n(il)}},il={spanContext(){return O8},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}},O8={traceId:"",spanId:"",traceFlags:0};function bv({isEnabled:e=!1,tracer:t}={}){return e?t||LE.getTracer("ai"):M8}async function Qs({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=yy.active();try{const i=await yy.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{kv(s,i)}finally{s.end()}throw i}})}function kv(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:sl.ERROR,message:t.message})):e.setStatus({code:sl.ERROR})}async function zr({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 Tv(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?g8(r.data):r.data}:r)})))}function Cv(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:$r(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Ld(){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 Sv(e,t){var r,n,o,s,a,i,l,c,u,h;return{inputTokens:$r(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:$r((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:$r((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:$r((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:$r(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:$r((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:$r((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(h=t.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:$r(e.totalTokens,t.totalTokens),reasoningTokens:$r(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:$r(e.cachedInputTokens,t.cachedInputTokens)}}function $r(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ll(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]=ll(s,o):r[n]=o}return r}function N8({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 A8=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Iv(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Iv(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(Yn(a)||t===0)throw a;const i=cd(a),l=[...s,a],c=l.length;if(c>t)throw new nv({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 v5(N8({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),Iv(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new nv({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function xv({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Ur({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Ur({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:A8({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 ZE({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Md({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 cl(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function jd({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 Qs({name:"ai.toolCall",attributes:zr({telemetry:n,attributes:{...Ys({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;await Er({event:y,callbacks:u});const m=cl();try{const k=RI({execute:_.execute.bind(_),input:g,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:a}});for await(const b of k)b.type==="preliminary"?c?.({...e,type:"tool-result",output:b.output,preliminary:!0}):v=b.output}catch(k){const b=cl()-m;return await Er({event:{...y,success:!1,error:k,durationMs:b},callbacks:h}),kv(w,k),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:k,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const C=cl()-m;await Er({event:{...y,success:!0,output:v,durationMs:C},callbacks:h});try{w.setAttributes(await zr({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 $v(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
580
+ `)}function Rv(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Pv=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=Oo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Mo(this.base64Data)),this.uint8ArrayData}},q8=class extends Pv{constructor(e){super(e),this.type="file"}};async function Mv({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 L8={};DE(L8,{array:()=>U8,choice:()=>z8,json:()=>Z8,object:()=>D8,text:()=>ul});function j8(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 Xs(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:j8(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ul=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),D8=({schema:e,name:t,description:r})=>{const n=Xn(e);return{name:"object",responseFormat:Gt(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 $n({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 $n({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 Xs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},U8=({element:e,name:t,description:r})=>{const n=Xn(e);return{name:"array",responseFormat:Gt(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 $n({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 $n({message:"No object generated: response did not match schema.",cause:new Kn({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 $n({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 Xs(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])}})}}},z8=({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 $n({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 $n({message:"No object generated: response did not match schema.",cause:new Kn({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 Xs(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(){}}),Z8=({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 $n({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 Xs(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 Ov({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Nv(e);throw new Od({toolName:e.toolName})}try{return await Av({toolCall:e,tools:t})}catch(a){if(r==null||!(Od.isInstance(a)||Pd.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 Xn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new KE({cause:l,originalError:a})}if(i==null)throw a;return await Av({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 Nv(e){const t=e.input.trim()===""?{success:!0,value:{}}:await ur({text:e.input});if(t.success===!1)throw new Pd({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 Av({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await Nv(e);throw new Od({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Xn(n.inputSchema),s=e.input.trim()===""?await cr({value:{},schema:o}):await ur({text:e.input,schema:o});if(s.success===!1)throw new Pd({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 qv=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 Dd(e){return({steps:t})=>t.length===e}async function Lv({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Ud({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 Gs({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 Gs({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 Gs({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 jv(...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 F8=zs({prefix:"aitxt",size:24});async function Dv({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Dd(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:C,experimental_context:k,experimental_include:b,_internal:{generateId:S=F8}={},experimental_onStart:x,experimental_onStepStart:I,experimental_onToolCallStart:L,experimental_onToolCallFinish:$,onStepFinish:N,onFinish:A,...U}){const V=al(e),Q=jo(u),_e=Ad(l),te=iv(l),ge=te!=null?new AbortController:void 0,H=jv(i,_e!=null?AbortSignal.timeout(_e):void 0,ge?.signal),{maxRetries:M,retry:B}=xv({maxRetries:a,abortSignal:H}),Z=qd(U),E=xn(c??{},`ai/${lv}`),O=wv({model:V,telemetry:f,headers:E,settings:{...Z,maxRetries:M}}),D={provider:V.provider,modelId:V.modelId},G=await vv({system:n,prompt:o,messages:s});await Er({event:{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:M,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:i,include:b,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k},callbacks:x});const re=bv(f);try{return await Qs({name:"ai.generateText",attributes:zr({telemetry:f,attributes:{...Ys({operationId:"ai.generateText",telemetry:f}),...O,"ai.model.provider":V.provider,"ai.model.id":V.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:re,fn:async ie=>{var Ie,z,F,K,ee,le,we,et,pt,mt,st,P,ne;const Oe=G.messages,qe=[],{approvedToolApprovals:pr,deniedToolApprovals:tt}=Ev({messages:Oe}),nr=pr.filter(it=>!it.toolCall.providerExecuted);if(tt.length>0||nr.length>0){const it=await Uv({toolCalls:nr.map(Se=>Se.toolCall),tools:t,tracer:re,telemetry:f,messages:Oe,abortSignal:H,experimental_context:k,stepNumber:0,model:D,onToolCallStart:L,onToolCallFinish:$}),St=[];for(const Se of it){const qt=await Gs({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"});St.push({type:"tool-result",toolCallId:Se.toolCallId,toolName:Se.toolName,output:qt})}for(const Se of tt)St.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}}}}});qe.push({role:"tool",content:St})}const ln=[...pr,...tt].filter(it=>it.toolCall.providerExecuted);ln.length>0&&qe.push({role:"tool",content:ln.map(it=>({type:"tool-approval-response",approvalId:it.approvalResponse.approvalId,approved:it.approvalResponse.approved,reason:it.approvalResponse.reason,providerExecuted:!0}))});const rt=qd(U);let xe,at=[],Ee=[];const Ye=[],Pr=new Map;do{const it=te!=null?setTimeout(()=>ge.abort(),te):void 0;try{const St=[...Oe,...qe],Se=await v?.({model:V,steps:Ye,stepNumber:Ye.length,messages:St,experimental_context:k}),qt=al((Ie=Se?.model)!=null?Ie:V),gt={provider:qt.provider,modelId:qt.modelId},It=await dv({prompt:{system:(z=Se?.system)!=null?z:G.system,messages:(F=Se?.messages)!=null?F:St},supportedUrls:await qt.supportedUrls,download:C});k=(K=Se?.experimental_context)!=null?K:k;const ft=(ee=Se?.activeTools)!=null?ee:y,{toolChoice:cn,tools:zo}=await hv({tools:t,toolChoice:(le=Se?.toolChoice)!=null?le:r,activeTools:ft}),Cl=(we=Se?.messages)!=null?we:St,Sl=(et=Se?.system)!=null?et:G.system,aa=ll(g,Se?.providerOptions);await Er({event:{stepNumber:Ye.length,model:gt,system:Sl,messages:Cl,tools:t,toolChoice:cn,activeTools:ft,steps:[...Ye],providerOptions:aa,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:b,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k},callbacks:I}),xe=await B(()=>{var Le;return Qs({name:"ai.generateText.doGenerate",attributes:zr({telemetry:f,attributes:{...Ys({operationId:"ai.generateText.doGenerate",telemetry:f}),...O,"ai.model.provider":qt.provider,"ai.model.id":qt.modelId,"ai.prompt.messages":{input:()=>Tv(It)},"ai.prompt.tools":{input:()=>zo?.map(Lt=>JSON.stringify(Lt))},"ai.prompt.toolChoice":{input:()=>cn!=null?JSON.stringify(cn):void 0},"gen_ai.system":qt.provider,"gen_ai.request.model":qt.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":(Le=U.temperature)!=null?Le:void 0,"gen_ai.request.top_k":U.topK,"gen_ai.request.top_p":U.topP}}),tracer:re,fn:async Lt=>{var Pn,un,xl,El,ua,$l,da,Zo;const ht=await qt.doGenerate({...rt,tools:zo,toolChoice:cn,responseFormat:await p?.responseFormat,prompt:It,providerOptions:aa,abortSignal:H,headers:E}),dn={id:(un=(Pn=ht.response)==null?void 0:Pn.id)!=null?un:S(),timestamp:(El=(xl=ht.response)==null?void 0:xl.timestamp)!=null?El:new Date,modelId:($l=(ua=ht.response)==null?void 0:ua.modelId)!=null?$l:qt.modelId,headers:(da=ht.response)==null?void 0:da.headers,body:(Zo=ht.response)==null?void 0:Zo.body};return Lt.setAttributes(await zr({telemetry:f,attributes:{"ai.response.finishReason":ht.finishReason.unified,"ai.response.text":{output:()=>Rv(ht.content)},"ai.response.reasoning":{output:()=>$v(ht.content)},"ai.response.toolCalls":{output:()=>{const Rl=zv(ht.content);return Rl==null?void 0:JSON.stringify(Rl)}},"ai.response.id":dn.id,"ai.response.model":dn.modelId,"ai.response.timestamp":dn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ht.providerMetadata),"ai.usage.promptTokens":ht.usage.inputTokens.total,"ai.usage.completionTokens":ht.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ht.finishReason.unified],"gen_ai.response.id":dn.id,"gen_ai.response.model":dn.modelId,"gen_ai.usage.input_tokens":ht.usage.inputTokens.total,"gen_ai.usage.output_tokens":ht.usage.outputTokens.total}})),{...ht,response:dn}}})});const fr=await Promise.all(xe.content.filter(Le=>Le.type==="tool-call").map(Le=>Ov({toolCall:Le,tools:t,repairToolCall:m,system:n,messages:St}))),ia={};for(const Le of fr){if(Le.invalid)continue;const Lt=t?.[Le.toolName];Lt!=null&&(Lt?.onInputAvailable!=null&&await Lt.onInputAvailable({input:Le.input,toolCallId:Le.toolCallId,messages:St,abortSignal:H,experimental_context:k}),await Mv({tool:Lt,toolCall:Le,messages:St,experimental_context:k})&&(ia[Le.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Le}))}const Il=fr.filter(Le=>Le.invalid&&Le.dynamic);Ee=[];for(const Le of Il)Ee.push({type:"tool-error",toolCallId:Le.toolCallId,toolName:Le.toolName,input:Le.input,error:cd(Le.error),dynamic:!0});at=fr.filter(Le=>!Le.providerExecuted),t!=null&&Ee.push(...await Uv({toolCalls:at.filter(Le=>!Le.invalid&&ia[Le.toolCallId]==null),tools:t,tracer:re,telemetry:f,messages:St,abortSignal:H,experimental_context:k,stepNumber:Ye.length,model:gt,onToolCallStart:L,onToolCallFinish:$}));for(const Le of fr){if(!Le.providerExecuted)continue;const Lt=t?.[Le.toolName];Lt?.type==="provider"&&Lt.supportsDeferredResults&&(xe.content.some(un=>un.type==="tool-result"&&un.toolCallId===Le.toolCallId)||Pr.set(Le.toolCallId,{toolName:Le.toolName}))}for(const Le of xe.content)Le.type==="tool-result"&&Pr.delete(Le.toolCallId);const la=H8({content:xe.content,toolCalls:fr,toolOutputs:Ee,toolApprovalRequests:Object.values(ia),tools:t});qe.push(...await Ud({content:la,tools:t}));const Rn=(pt=b?.requestBody)==null||pt?(mt=xe.request)!=null?mt:{}:{...xe.request,body:void 0},_t={...xe.response,messages:structuredClone(qe),body:(st=b?.responseBody)==null||st?(P=xe.response)==null?void 0:P.body:void 0},Zr=Ye.length,ca=new qv({stepNumber:Zr,model:gt,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k,content:la,finishReason:xe.finishReason.unified,rawFinishReason:xe.finishReason.raw,usage:Cv(xe.usage),warnings:xe.warnings,providerMetadata:xe.providerMetadata,request:Rn,response:_t});Nd({warnings:(ne=xe.warnings)!=null?ne:[],provider:gt.provider,model:gt.modelId}),Ye.push(ca),await Er({event:ca,callbacks:N})}finally{it!=null&&clearTimeout(it)}}while((at.length>0&&Ee.length===at.length||Pr.size>0)&&!await Lv({stopConditions:Q,steps:Ye}));ie.setAttributes(await zr({telemetry:f,attributes:{"ai.response.finishReason":xe.finishReason.unified,"ai.response.text":{output:()=>Rv(xe.content)},"ai.response.reasoning":{output:()=>$v(xe.content)},"ai.response.toolCalls":{output:()=>{const it=zv(xe.content);return it==null?void 0:JSON.stringify(it)}},"ai.response.providerMetadata":JSON.stringify(xe.providerMetadata),"ai.usage.promptTokens":xe.usage.inputTokens.total,"ai.usage.completionTokens":xe.usage.outputTokens.total}}));const Y=Ye[Ye.length-1],Qe=Ye.reduce((it,St)=>Sv(it,St.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await Er({event:{stepNumber:Y.stepNumber,model:Y.model,functionId:Y.functionId,metadata:Y.metadata,experimental_context:Y.experimental_context,finishReason:Y.finishReason,rawFinishReason:Y.rawFinishReason,usage:Y.usage,content:Y.content,text:Y.text,reasoningText:Y.reasoningText,reasoning:Y.reasoning,files:Y.files,sources:Y.sources,toolCalls:Y.toolCalls,staticToolCalls:Y.staticToolCalls,dynamicToolCalls:Y.dynamicToolCalls,toolResults:Y.toolResults,staticToolResults:Y.staticToolResults,dynamicToolResults:Y.dynamicToolResults,request:Y.request,response:Y.response,warnings:Y.warnings,providerMetadata:Y.providerMetadata,steps:Ye,totalUsage:Qe},callbacks:A});let Mr;return Y.finishReason==="stop"&&(Mr=await(p??ul()).parseCompleteOutput({text:Y.text},{response:Y.response,usage:Y.usage,finishReason:Y.finishReason})),new V8({steps:Ye,totalUsage:Qe,output:Mr})}})}catch(ie){throw _v(ie)}}async function Uv({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=>jd({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 V8=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 zy;return this._output}};function zv(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 H8({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 Pv(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 Md({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function dl(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 B8({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:dl(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 J8({response:e,status:t,statusText:r,headers:n,textStream:o}){Zv({response:e,status:t,statusText:r,headers:Object.fromEntries(dl(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var Fv=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
581
581
 
582
582
  `)},flush(e){e.enqueue(`data: [DONE]
583
583
 
584
- `)}})}},Iv={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Rx({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new Sv);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Yi(r,Iv)})}function Px({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 Mx(e){return e.type.startsWith("data-")}function Td(e){return e.type.startsWith("tool-")}function Ox(e){return e.type==="dynamic-tool"}function Ax(e){return Td(e)||Ox(e)}function Ev(e){return e.type.split("-").slice(1).join("-")}function Nx({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function qx({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 f,p,h,y;function w(m){const k=c.message.parts.filter(Ax).find(_=>_.toolCallId===m);if(k==null)throw new xo({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return k}function g(m){var T;const k=c.message.parts.find($=>Td($)&&$.toolCallId===m.toolCallId),_=m,S=k;k!=null?(k.state=m.state,S.input=_.input,S.output=_.output,S.errorText=_.errorText,S.rawInput=_.rawInput,S.preliminary=_.preliminary,m.title!==void 0&&(S.title=m.title),S.providerExecuted=(T=_.providerExecuted)!=null?T:k.providerExecuted,_.providerMetadata!=null&&(k.callProviderMetadata=_.providerMetadata)):c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null?{callProviderMetadata:_.providerMetadata}:{}})}function b(m){var T,k;const _=c.message.parts.find(x=>x.type==="dynamic-tool"&&x.toolCallId===m.toolCallId),S=m,$=_;_!=null?(_.state=m.state,$.toolName=m.toolName,$.input=S.input,$.output=S.output,$.errorText=S.errorText,$.rawInput=(T=S.rawInput)!=null?T:$.rawInput,$.preliminary=S.preliminary,m.title!==void 0&&($.title=m.title),$.providerExecuted=(k=S.providerExecuted)!=null?k:_.providerExecuted,S.providerMetadata!=null&&(_.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:m.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function v(m){if(m!=null){const T=c.message.metadata!=null?Gi(c.message.metadata,m):m;t!=null&&await qt({value:T,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=T}}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 xo({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=(f=i.providerMetadata)!=null?f:m.providerMetadata,u();break}case"text-end":{const m=c.activeTextParts[i.id];if(m==null)throw new xo({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 xo({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=(h=i.providerMetadata)!=null?h:m.providerMetadata,u();break}case"reasoning-end":{const m=c.activeReasoningParts[i.id];if(m==null)throw new xo({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=(y=i.providerMetadata)!=null?y: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(Td);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:m.length,dynamic:i.dynamic,title:i.title},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):g({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 xo({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:T}=await Hs(m.text);m.dynamic?b({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:T,title:m.title}):g({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:T,title:m.title}),u();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):g({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?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):g({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=w(i.toolCallId);m.state="approval-requested",m.approval={id:i.approvalId},u();break}case"tool-output-denied":{const m=w(i.toolCallId);m.state="output-denied",u();break}case"tool-output-available":{const m=w(i.toolCallId);m.type==="dynamic-tool"?b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:m.title}):g({toolCallId:i.toolCallId,toolName:Ev(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=w(i.toolCallId);m.type==="dynamic-tool"?b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:m.title}):g({toolCallId:i.toolCallId,toolName:Ev(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(Mx(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),_=k>=0?k:c.message.parts.length;await qt({value:i.data,schema:r[i.type],context:{field:`message.parts[${_}].data`,entityName:i.type,entityId:i.id}})}const m=i;if(m.transient){a?.(m);break}const T=m.id!=null?c.message.parts.find(k=>m.type===k.type&&m.id===k.id):void 0;T!=null?T.data=m.data:c.message.parts.push(m),a?.(m),u()}}l.enqueue(i)})}}))}function Lx({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(y,w){if(y.type==="start"){const g=y;g.messageId==null&&e!=null&&(g.messageId=e)}y.type==="abort"&&(i=!0),w.enqueue(y)}}));if(n==null&&r==null)return l;const c=Nx({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async y=>{await y({state:c,write:()=>{}})};let f=!1;const p=async()=>{if(f||!n)return;f=!0;const y=c.message.id===a?.id;await n({isAborted:i,isContinuation:y,responseMessage:c.message,messages:[...y?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},h=async()=>{if(!r)return;const y=c.message.id===a?.id;try{await r({isContinuation:y,responseMessage:structuredClone(c.message),messages:[...y?t.slice(0,-1):t,structuredClone(c.message)]})}catch(w){o(w)}};return qx({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(y,w){y.type==="finish-step"&&await h(),w.enqueue(y)},async cancel(){await p()},async flush(){await p()}}))}function jx({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new Sv);if(s){const[i,l]=a.tee();a=i,s({stream:l})}Cv({response:e,status:t,statusText:r,headers:Object.fromEntries(Yi(n,Iv).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Bs(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 Dx({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 xv(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Ux(){let e=[],t=null,r=!1,n=xv();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=xv(),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 zx(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Zx({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c}){let u=null;const f=new ReadableStream({start(m){u=m}}),p=new Set,h=new Map,y=new Map;let w=!1,g;function b(){w&&p.size===0&&(g!=null&&u.enqueue(g),u.close())}const v=new TransformStream({async transform(m,T){const k=m.type;switch(k){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":{T.enqueue(m);break}case"file":{T.enqueue({type:"file",file:new vx({data:m.data,mediaType:m.mediaType})});break}case"finish":{g={type:"finish",finishReason:m.finishReason.unified,rawFinishReason:m.finishReason.raw,usage:av(m.usage),providerMetadata:m.providerMetadata};break}case"tool-approval-request":{const _=y.get(m.toolCallId);if(_==null){u.enqueue({type:"error",error:new hd({toolCallId:m.toolCallId,approvalId:m.approvalId})});break}T.enqueue({type:"tool-approval-request",approvalId:m.approvalId,toolCall:_});break}case"tool-call":{try{const _=await mv({toolCall:m,tools:e,repairToolCall:i,system:o,messages:s});if(y.set(_.toolCallId,_),T.enqueue(_),_.invalid){u.enqueue({type:"tool-error",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input,error:Hu(_.error),dynamic:!0,title:_.title});break}const S=e?.[_.toolName];if(S==null)break;if(S.onInputAvailable!=null&&await S.onInputAvailable({input:_.input,toolCallId:_.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await hv({tool:S,toolCall:_,messages:s,experimental_context:l})){u.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:_});break}if(h.set(_.toolCallId,_.input),S.execute!=null&&_.providerExecuted!==!0){const $=c();p.add($),wd({toolCall:_,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,onPreliminaryToolResult:x=>{u.enqueue(x)}}).then(x=>{u.enqueue(x)}).catch(x=>{u.enqueue({type:"error",error:x})}).finally(()=>{p.delete($),b()})}}catch(_){u.enqueue({type:"error",error:_})}break}case"tool-result":{const _=m.toolName;m.isError?u.enqueue({type:"tool-error",toolCallId:m.toolCallId,toolName:_,input:h.get(m.toolCallId),providerExecuted:!0,error:m.result,dynamic:m.dynamic}):T.enqueue({type:"tool-result",toolCallId:m.toolCallId,toolName:_,input:h.get(m.toolCallId),output:m.result,providerExecuted:!0,dynamic:m.dynamic});break}default:{const _=k;throw new Error(`Unhandled chunk type: ${_}`)}}},flush(){w=!0,b()}});return new ReadableStream({async start(m){return Promise.all([t.pipeThrough(v).pipeTo(new WritableStream({write(T){m.enqueue(T)},close(){}})),f.pipeTo(new WritableStream({write(T){m.enqueue(T)},close(){m.close()}}))])}})}var Fx=Ps({prefix:"aitxt",size:24});function Cd({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=bd(1),experimental_output:f,output:p=f,experimental_telemetry:h,prepareStep:y,providerOptions:w,experimental_activeTools:g,activeTools:b=g,experimental_repairToolCall:v,experimental_transform:m,experimental_download:T,includeRawChunks:k=!1,onChunk:_,onError:S=({error:J})=>{console.error(J)},onFinish:$,onAbort:x,onStepFinish:U,experimental_context:M,experimental_include:O,_internal:{now:A=zx,generateId:L=Fx}={},...Y}){const J=yd(l),de=Fy(l),K=VE(l),$e=de!=null?new AbortController:void 0,Z=K!=null?new AbortController:void 0;return new Hx({model:Ji(e),telemetry:h,headers:c,settings:Y,maxRetries:a,abortSignal:wv(i,J!=null?AbortSignal.timeout(J):void 0,$e?.signal,Z?.signal),stepTimeoutMs:de,stepAbortController:$e,chunkTimeoutMs:K,chunkAbortController:Z,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Us(m),activeTools:b,repairToolCall:v,stopConditions:Us(u),output:p,providerOptions:w,prepareStep:y,includeRawChunks:k,onChunk:_,onError:S,onFinish:$,onAbort:x,onStepFinish:U,now:A,generateId:L,experimental_context:M,download:T,include:O})}function Vx(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 f=JSON.stringify(u.partial);f!==s&&(a({controller:l,partialOutput:u.partial}),s=f)}}})}var Hx=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:f,messages:p,tools:h,toolChoice:y,transforms:w,activeTools:g,repairToolCall:b,stopConditions:v,output:m,providerOptions:T,prepareStep:k,includeRawChunks:_,now:S,generateId:$,onChunk:x,onError:U,onFinish:M,onAbort:O,onStepFinish:A,experimental_context:L,download:Y,include:J}){this._totalUsage=new Rs,this._finishReason=new Rs,this._rawFinishReason=new Rs,this._steps=new Rs,this.outputSpecification=m,this.includeRawChunks=_,this.tools=h;let de,K=[];const $e=[];let Z,N,H,z={},I=[];const E=[],V=new Map;let te,Q={},_e={};const xe=new TransformStream({async transform(Te,Re){var Xe,ie,lt,Ct;Re.enqueue(Te);const{part:ne}=Te;if((ne.type==="text-delta"||ne.type==="reasoning-delta"||ne.type==="source"||ne.type==="tool-call"||ne.type==="tool-result"||ne.type==="tool-input-start"||ne.type==="tool-input-delta"||ne.type==="raw")&&await x?.({chunk:ne}),ne.type==="error"&&await U({error:tv(ne.error)}),ne.type==="text-start"&&(Q[ne.id]={type:"text",text:"",providerMetadata:ne.providerMetadata},K.push(Q[ne.id])),ne.type==="text-delta"){const ze=Q[ne.id];if(ze==null){Re.enqueue({part:{type:"error",error:`text part ${ne.id} not found`},partialOutput:void 0});return}ze.text+=ne.text,ze.providerMetadata=(Xe=ne.providerMetadata)!=null?Xe:ze.providerMetadata}if(ne.type==="text-end"){const ze=Q[ne.id];if(ze==null){Re.enqueue({part:{type:"error",error:`text part ${ne.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(ie=ne.providerMetadata)!=null?ie:ze.providerMetadata,delete Q[ne.id]}if(ne.type==="reasoning-start"&&(_e[ne.id]={type:"reasoning",text:"",providerMetadata:ne.providerMetadata},K.push(_e[ne.id])),ne.type==="reasoning-delta"){const ze=_e[ne.id];if(ze==null){Re.enqueue({part:{type:"error",error:`reasoning part ${ne.id} not found`},partialOutput:void 0});return}ze.text+=ne.text,ze.providerMetadata=(lt=ne.providerMetadata)!=null?lt:ze.providerMetadata}if(ne.type==="reasoning-end"){const ze=_e[ne.id];if(ze==null){Re.enqueue({part:{type:"error",error:`reasoning part ${ne.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(Ct=ne.providerMetadata)!=null?Ct:ze.providerMetadata,delete _e[ne.id]}if(ne.type==="file"&&K.push({type:"file",file:ne.file}),ne.type==="source"&&K.push(ne),ne.type==="tool-call"&&K.push(ne),ne.type==="tool-result"&&!ne.preliminary&&K.push(ne),ne.type==="tool-approval-request"&&K.push(ne),ne.type==="tool-error"&&K.push(ne),ne.type==="start-step"&&(K=[],_e={},Q={},z=ne.request,I=ne.warnings),ne.type==="finish-step"){const ze=await kd({content:K,tools:h}),De=new vv({content:K,finishReason:ne.finishReason,rawFinishReason:ne.rawFinishReason,usage:ne.usage,warnings:I,request:z,response:{...ne.response,messages:[...$e,...ze]},providerMetadata:ne.providerMetadata});await A?.(De),gd({warnings:I,provider:e.provider,model:e.modelId}),E.push(De),$e.push(...ze),de.resolve()}ne.type==="finish"&&(H=ne.totalUsage,Z=ne.finishReason,N=ne.rawFinishReason)},async flush(Te){try{if(E.length===0){const lt=s?.aborted?s.reason:new Ty({message:"No output generated. Check the stream for errors."});ve._finishReason.reject(lt),ve._rawFinishReason.reject(lt),ve._totalUsage.reject(lt),ve._steps.reject(lt);return}const Re=Z??"other",Xe=H??_d();ve._finishReason.resolve(Re),ve._rawFinishReason.resolve(N),ve._totalUsage.resolve(Xe),ve._steps.resolve(E);const ie=E[E.length-1];await M?.({finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,totalUsage:Xe,usage:ie.usage,content:ie.content,text:ie.text,reasoningText:ie.reasoningText,reasoning:ie.reasoning,files:ie.files,sources:ie.sources,toolCalls:ie.toolCalls,staticToolCalls:ie.staticToolCalls,dynamicToolCalls:ie.dynamicToolCalls,toolResults:ie.toolResults,staticToolResults:ie.staticToolResults,dynamicToolResults:ie.dynamicToolResults,request:ie.request,response:ie.response,warnings:ie.warnings,providerMetadata:ie.providerMetadata,steps:E,experimental_context:L}),te.setAttributes(await Pr({telemetry:t,attributes:{"ai.response.finishReason":Re,"ai.response.text":{output:()=>ie.text},"ai.response.reasoning":{output:()=>ie.reasoningText},"ai.response.toolCalls":{output:()=>{var lt;return(lt=ie.toolCalls)!=null&&lt.length?JSON.stringify(ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.inputTokens":Xe.inputTokens,"ai.usage.outputTokens":Xe.outputTokens,"ai.usage.totalTokens":Xe.totalTokens,"ai.usage.reasoningTokens":Xe.reasoningTokens,"ai.usage.cachedInputTokens":Xe.cachedInputTokens}}))}catch(Re){Te.error(Re)}finally{te.end()}}}),D=Ux();this.addStream=D.addStream,this.closeStream=D.close;const F=D.stream.getReader();let G=new ReadableStream({async start(Te){Te.enqueue({type:"start"})},async pull(Te){function Re(){O?.({steps:E}),Te.enqueue({type:"abort",...s?.reason!==void 0?{reason:jn(s.reason)}:{}}),Te.close()}try{const{done:Xe,value:ie}=await F.read();if(Xe){Te.close();return}if(s?.aborted){Re();return}Te.enqueue(ie)}catch(Xe){zn(Xe)&&s?.aborted?Re():Te.error(Xe)}},cancel(Te){return D.stream.cancel(Te)}});for(const Te of w)G=G.pipeThrough(Te({tools:h,stopStream(){D.terminate()}}));this.baseStream=G.pipeThrough(Vx(m??Ki())).pipeThrough(xe);const{maxRetries:ee,retry:pe}=cv({maxRetries:o,abortSignal:s}),ke=nv(t),R=vd(n),re=rv({model:e,telemetry:t,headers:r,settings:{...R,maxRetries:ee}}),ve=this;Vs({name:"ai.streamText",attributes:Pr({telemetry:t,attributes:{...Fs({operationId:"ai.streamText",telemetry:t}),...re,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:f,messages:p})}}}),tracer:ke,endWhenDone:!1,fn:async Te=>{te=Te;const Re=await ev({system:u,prompt:f,messages:p}),Xe=Re.messages,ie=[],{approvedToolApprovals:lt,deniedToolApprovals:Ct}=uv({messages:Xe});if(Ct.length>0||lt.length>0){const ze=[...lt,...Ct].filter(Se=>Se.toolCall.providerExecuted),De=lt.filter(Se=>!Se.toolCall.providerExecuted),kr=Ct.filter(Se=>!Se.toolCall.providerExecuted),Yr=Ct.filter(Se=>Se.toolCall.providerExecuted);let Je;const St=new ReadableStream({start(Se){Je=Se}});ve.addStream(St);try{for(const et of[...kr,...Yr])Je?.enqueue({type:"tool-output-denied",toolCallId:et.toolCall.toolCallId,toolName:et.toolCall.toolName});const Se=[];if(await Promise.all(De.map(async et=>{const ct=await wd({toolCall:et.toolCall,tools:h,tracer:ke,telemetry:t,messages:Xe,abortSignal:s,experimental_context:L,onPreliminaryToolResult:_n=>{Je?.enqueue(_n)}});ct!=null&&(Je?.enqueue(ct),Se.push(ct))})),ze.length>0&&ie.push({role:"tool",content:ze.map(et=>({type:"tool-approval-response",approvalId:et.approvalResponse.approvalId,approved:et.approvalResponse.approved,reason:et.approvalResponse.reason,providerExecuted:!0}))}),Se.length>0||kr.length>0){const et=[];for(const ct of Se)et.push({type:"tool-result",toolCallId:ct.toolCallId,toolName:ct.toolName,output:await zs({toolCallId:ct.toolCallId,input:ct.input,tool:h?.[ct.toolName],output:ct.type==="tool-result"?ct.output:ct.error,errorMode:ct.type==="tool-error"?"json":"none"})});for(const ct of kr)et.push({type:"tool-result",toolCallId:ct.toolCall.toolCallId,toolName:ct.toolCall.toolName,output:{type:"execution-denied",reason:ct.approvalResponse.reason}});ie.push({role:"tool",content:et})}}finally{Je?.close()}}$e.push(...ie);async function ne({currentStep:ze,responseMessages:De,usage:kr}){var Yr,Je,St,Se,et,ct,_n;const Po=ve.includeRawChunks,wn=a!=null?setTimeout(()=>i.abort(),a):void 0;let Mr;function Dd(){l!=null&&(Mr!=null&&clearTimeout(Mr),Mr=setTimeout(()=>c.abort(),l))}function Qs(){Mr!=null&&(clearTimeout(Mr),Mr=void 0)}function ul(){wn!=null&&clearTimeout(wn)}try{de=new Rs;const Gn=[...Xe,...De],It=await k?.({model:e,steps:E,stepNumber:E.length,messages:Gn,experimental_context:L}),Pe=Ji((Yr=It?.model)!=null?Yr:e),Rt=await Jy({prompt:{system:(Je=It?.system)!=null?Je:Re.system,messages:(St=It?.messages)!=null?St:Gn},supportedUrls:await Pe.supportedUrls,download:Y}),{toolChoice:Kn,tools:Qr}=await Ky({tools:h,toolChoice:(Se=It?.toolChoice)!=null?Se:y,activeTools:(et=It?.activeTools)!=null?et:g});L=(ct=It?.experimental_context)!=null?ct:L;const dl=Gi(T,It?.providerOptions),{result:{stream:pl,response:Xs,request:Mo},doStreamSpan:Xr,startTimestampMs:ea}=await pe(()=>Vs({name:"ai.streamText.doStream",attributes:Pr({telemetry:t,attributes:{...Fs({operationId:"ai.streamText.doStream",telemetry:t}),...re,"ai.model.provider":Pe.provider,"ai.model.id":Pe.modelId,"ai.prompt.messages":{input:()=>sv(Rt)},"ai.prompt.tools":{input:()=>Qr?.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>Kn!=null?JSON.stringify(Kn):void 0},"gen_ai.system":Pe.provider,"gen_ai.request.model":Pe.modelId,"gen_ai.request.frequency_penalty":R.frequencyPenalty,"gen_ai.request.max_tokens":R.maxOutputTokens,"gen_ai.request.presence_penalty":R.presencePenalty,"gen_ai.request.stop_sequences":R.stopSequences,"gen_ai.request.temperature":R.temperature,"gen_ai.request.top_k":R.topK,"gen_ai.request.top_p":R.topP}}),tracer:ke,endWhenDone:!1,fn:async we=>({startTimestampMs:S(),doStreamSpan:we,result:await Pe.doStream({...R,tools:Qr,toolChoice:Kn,responseFormat:await m?.responseFormat,prompt:Rt,providerOptions:dl,abortSignal:s,headers:r,includeRawChunks:Po})})})),Ud=Zx({tools:h,generatorStream:pl,tracer:ke,telemetry:t,system:u,messages:Gn,repairToolCall:b,abortSignal:s,experimental_context:L,generateId:$}),vt=(_n=J?.requestBody)==null||_n?Mo??{}:{...Mo,body:void 0},sr=[],bn=[];let zd;const Zd={};let Oo="other",Fd,Tr=_d(),Vd,_1=!0,Or={id:$(),timestamp:new Date,modelId:e.modelId},w1="";ve.addStream(Ud.pipeThrough(new TransformStream({async transform(we,Et){var ta,ra,fl,ut,Ar;if(Dd(),we.type==="stream-start"){zd=we.warnings;return}if(_1){const dt=S()-ea;_1=!1,Xr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":dt}),Xr.setAttributes({"ai.response.msToFirstChunk":dt}),Et.enqueue({type:"start-step",request:vt,warnings:zd??[]})}const Hd=we.type;switch(Hd){case"tool-approval-request":case"text-start":case"text-end":{Et.enqueue(we);break}case"text-delta":{we.delta.length>0&&(Et.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),w1+=we.delta);break}case"reasoning-start":case"reasoning-end":{Et.enqueue(we);break}case"reasoning-delta":{Et.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{Et.enqueue(we),sr.push(we);break}case"tool-result":{Et.enqueue(we),we.preliminary||bn.push(we);break}case"tool-error":{Et.enqueue(we),bn.push(we);break}case"response-metadata":{Or={id:(ta=we.id)!=null?ta:Or.id,timestamp:(ra=we.timestamp)!=null?ra:Or.timestamp,modelId:(fl=we.modelId)!=null?fl:Or.modelId};break}case"finish":{Tr=we.usage,Oo=we.finishReason,Fd=we.rawFinishReason,Vd=we.providerMetadata;const dt=S()-ea;Xr.addEvent("ai.stream.finish"),Xr.setAttributes({"ai.response.msToFinish":dt,"ai.response.avgOutputTokensPerSecond":1e3*((ut=Tr.outputTokens)!=null?ut:0)/dt});break}case"file":{Et.enqueue(we);break}case"source":{Et.enqueue(we);break}case"tool-input-start":{Zd[we.id]=we.toolName;const dt=h?.[we.toolName];dt?.onInputStart!=null&&await dt.onInputStart({toolCallId:we.id,messages:Gn,abortSignal:s,experimental_context:L}),Et.enqueue({...we,dynamic:(Ar=we.dynamic)!=null?Ar:dt?.type==="dynamic",title:dt?.title});break}case"tool-input-end":{delete Zd[we.id],Et.enqueue(we);break}case"tool-input-delta":{const dt=Zd[we.id],Bd=h?.[dt];Bd?.onInputDelta!=null&&await Bd.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:Gn,abortSignal:s,experimental_context:L}),Et.enqueue(we);break}case"error":{Et.enqueue(we),Oo="error";break}case"raw":{Po&&Et.enqueue(we);break}default:{const dt=Hd;throw new Error(`Unknown chunk type: ${dt}`)}}},async flush(we){const Et=sr.length>0?JSON.stringify(sr):void 0;try{Xr.setAttributes(await Pr({telemetry:t,attributes:{"ai.response.finishReason":Oo,"ai.response.text":{output:()=>w1},"ai.response.reasoning":{output:()=>{const ut=K.filter(Ar=>Ar.type==="reasoning");return ut.length>0?ut.map(Ar=>Ar.text).join(`
585
- `):void 0}},"ai.response.toolCalls":{output:()=>Et},"ai.response.id":Or.id,"ai.response.model":Or.modelId,"ai.response.timestamp":Or.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Vd),"ai.usage.inputTokens":Tr.inputTokens,"ai.usage.outputTokens":Tr.outputTokens,"ai.usage.totalTokens":Tr.totalTokens,"ai.usage.reasoningTokens":Tr.reasoningTokens,"ai.usage.cachedInputTokens":Tr.cachedInputTokens,"gen_ai.response.finish_reasons":[Oo],"gen_ai.response.id":Or.id,"gen_ai.response.model":Or.modelId,"gen_ai.usage.input_tokens":Tr.inputTokens,"gen_ai.usage.output_tokens":Tr.outputTokens}}))}catch{}finally{Xr.end()}we.enqueue({type:"finish-step",finishReason:Oo,rawFinishReason:Fd,usage:Tr,providerMetadata:Vd,response:{...Or,headers:Xs?.headers}});const ta=iv(kr,Tr);await de.promise;const ra=sr.filter(ut=>ut.providerExecuted!==!0),fl=bn.filter(ut=>ut.providerExecuted!==!0);for(const ut of sr){if(ut.providerExecuted!==!0)continue;const Ar=h?.[ut.toolName];Ar?.type==="provider"&&Ar.supportsDeferredResults&&(bn.some(dt=>(dt.type==="tool-result"||dt.type==="tool-error")&&dt.toolCallId===ut.toolCallId)||V.set(ut.toolCallId,{toolName:ut.toolName}))}for(const ut of bn)(ut.type==="tool-result"||ut.type==="tool-error")&&V.delete(ut.toolCallId);if(ul(),Qs(),(ra.length>0&&fl.length===ra.length||V.size>0)&&!await _v({stopConditions:v,steps:E})){De.push(...await kd({content:E[E.length-1].content,tools:h}));try{await ne({currentStep:ze+1,responseMessages:De,usage:ta})}catch(ut){we.enqueue({type:"error",error:ut}),ve.closeStream()}}else we.enqueue({type:"finish",finishReason:Oo,rawFinishReason:Fd,totalUsage:ta}),ve.closeStream()}})))}finally{ul(),Qs()}}await ne({currentStep:0,responseMessages:ie,usage:_d()})}}).catch(Te=>{ve.addStream(new ReadableStream({start(Re){Re.enqueue({type:"error",error:Te}),Re.close()}})),ve.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 Bs(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Bs(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Dx({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 Bs(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 xr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Bs(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Ki()).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?Px({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var h;const y=(h=this.tools)==null?void 0:h[p.toolName];return y==null?p.dynamic:y?.type==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const y=n?.({part:p}),w=p.type;switch(w){case"text-start":{h.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{s&&p.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&h.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 g=u(p);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...g!=null?{dynamic:g}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const g=u(p);p.invalid?h.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}:{},...g!=null?{dynamic:g}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):h.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}:{},...g!=null?{dynamic:g}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const g=u(p);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...g!=null?{dynamic:g}:{}});break}case"tool-error":{const g=u(p);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...g!=null?{dynamic:g}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{a&&h.enqueue({type:"start",...y!=null?{messageMetadata:y}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&h.enqueue({type:"finish",finishReason:p.finishReason,...y!=null?{messageMetadata:y}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const g=w;throw new Error(`Unknown chunk type: ${g}`)}}y!=null&&w!=="start"&&w!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:y})}}));return Bs(Lx({stream:f,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}={}){jx({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){$x({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 Rx({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 xx({textStream:this.textStream,...e})}};Ps({prefix:"aiobj",size:24}),Ps({prefix:"aiobj",size:24});var Bx="AI_MCPClientError",$v=`vercel.ai.error.${Bx}`,Jx=Symbol.for($v),Rv,Pv,Fe=class extends(Pv=ye,Rv=Jx,Pv){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Rv]=!0,this.data=n,this.code=o}static isInstance(e){return ye.hasMarker(e,$v)}},$o="2025-06-18",Wx=[$o,"2025-03-26","2024-11-05"],Gx=ue(ge(d(),Le())),Kx=at({name:d(),version:d()}),Qi=at({_meta:ue(C({}).loose())}),Gr=Qi,Mv=C({method:d(),params:ue(Qi)}),Ov=C({applyDefaults:ue(me())}).loose(),Yx=at({experimental:ue(C({}).loose()),logging:ue(C({}).loose()),prompts:ue(at({listChanged:ue(me())})),resources:ue(at({subscribe:ue(me()),listChanged:ue(me())})),tools:ue(at({listChanged:ue(me())})),elicitation:ue(Ov)});C({elicitation:ue(Ov)}).loose();var Qx=Gr.extend({protocolVersion:d(),capabilities:Yx,serverInfo:Kx,instructions:ue(d())}),Sd=Gr.extend({nextCursor:ue(d())}),Xx=C({name:d(),title:ue(d()),description:ue(d()),inputSchema:C({type:P("object"),properties:ue(C({}).loose())}).loose(),outputSchema:ue(C({}).loose()),annotations:ue(C({title:ue(d())}).loose()),_meta:Gx}).loose(),e$=Sd.extend({tools:q(Xx)}),Av=C({type:P("text"),text:d()}).loose(),Nv=C({type:P("image"),data:Ih(),mimeType:d()}).loose(),t$=C({uri:d(),name:d(),title:ue(d()),description:ue(d()),mimeType:ue(d()),size:ue(j())}).loose(),r$=Sd.extend({resources:q(t$)}),qv=C({uri:d(),name:ue(d()),title:ue(d()),mimeType:ue(d())}).loose(),Lv=qv.extend({text:d()}),jv=qv.extend({blob:Ih()}),Dv=C({type:P("resource"),resource:oe([Lv,jv])}).loose(),n$=Gr.extend({content:q(oe([Av,Nv,Dv])),structuredContent:ue(Le()),isError:me().default(!1).optional()}).or(Gr.extend({toolResult:Le()})),o$=C({uriTemplate:d(),name:d(),title:ue(d()),description:ue(d()),mimeType:ue(d())}).loose(),s$=Gr.extend({resourceTemplates:q(o$)}),a$=Gr.extend({contents:q(oe([Lv,jv]))}),i$=C({name:d(),description:ue(d()),required:ue(me())}).loose(),l$=C({name:d(),title:ue(d()),description:ue(d()),arguments:ue(q(i$))}).loose(),c$=Sd.extend({prompts:q(l$)}),u$=C({role:oe([P("user"),P("assistant")]),content:oe([Av,Nv,Dv])}).loose(),d$=Gr.extend({description:ue(d()),messages:q(u$)}),p$=Qi.extend({message:d(),requestedSchema:Le()}),Uv=Mv.extend({method:P("elicitation/create"),params:p$}),f$=Gr.extend({action:oe([P("accept"),P("decline"),P("cancel")]),content:ue(ge(d(),Le()))}),Xi="2.0",h$=C({jsonrpc:P(Xi),id:oe([d(),j().int()])}).merge(Mv).strict(),m$=C({jsonrpc:P(Xi),id:oe([d(),j().int()]),result:Gr}).strict(),g$=C({jsonrpc:P(Xi),id:oe([d(),j().int()]),error:C({code:j().int(),message:d(),data:ue(Le())})}).strict(),y$=C({jsonrpc:P(Xi)}).merge(C({method:d(),params:ue(Qi)})).strict(),Js=oe([h$,y$,m$,g$]),zv=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Zv=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Vt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:qh.custom,message:"URL must be parseable",fatal:!0}),Of}).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"}),v$=C({resource:d().url(),authorization_servers:q(Vt).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(),Fv=C({issuer:d(),authorization_endpoint:Vt,token_endpoint:Vt,registration_endpoint:Vt.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(),_$=C({issuer:d(),authorization_endpoint:Vt,token_endpoint:Vt,userinfo_endpoint:Vt.optional(),jwks_uri:Vt,registration_endpoint:Vt.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(),w$=_$.merge(Fv.pick({code_challenge_methods_supported:!0})),b$=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),k$=C({redirect_uris:q(Vt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Vt.optional(),logo_uri:Vt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Vt.optional(),policy_uri:d().optional(),jwks_uri:Vt.optional(),jwks:mt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),T$=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),C$=k$.merge(b$),S$="AI_MCPClientOAuthError",Vv=`vercel.ai.error.${S$}`,I$=Symbol.for(Vv),Hv,Bv,Ws=class extends(Bv=ye,Hv=I$,Bv){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Hv]=!0}static isInstance(e){return ye.hasMarker(e,Vv)}},Ro=class extends Ws{};Ro.errorCode="server_error";var el=class extends Ws{};el.errorCode="invalid_client";var tl=class extends Ws{};tl.errorCode="invalid_grant";var rl=class extends Ws{};rl.errorCode="unauthorized_client";var E$={[Ro.errorCode]:Ro,[el.errorCode]:el,[tl.errorCode]:tl,[rl.errorCode]:rl};function x$(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function $$({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 nl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function ol(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 R$(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Id(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Id(e,void 0,r):void 0;throw n}}async function Jv(e,t,r=fetch){return await Id(e,{"MCP-Protocol-Version":t},r)}function P$(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function M$(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:$o;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=R$(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await Jv(l,i,r);if(!n?.metadataUrl&&P$(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await Jv(u,i,r)}return c}async function O$(e,t,r=fetch){const n=await M$(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 v$.parse(await n.json())}function A$(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 N$(e,{fetchFn:t=fetch,protocolVersion:r=$o}={}){var n;const o={"MCP-Protocol-Version":r},s=A$(e);for(const{url:a,type:i}of s){const l=await Id(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 Fv.parse(await l.json());{const c=w$.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 q$(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 Um(),f=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:f}}function Wv(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 Gv(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":L$(o,s,r);return;case"client_secret_post":j$(o,s,n);return;case"none":D$(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function L$(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 j$(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function D$(e,t){t.set("client_id",e)}async function Ed(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=T$.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=E$[o]||Ro;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Ro({message:o})}}async function U$(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",f=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"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,h,e,t);else{const w=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],g=Wv(r,w);Gv(g,r,p,h)}a&&h.set("resource",a.href);const y=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!y.ok)throw await Ed(y);return Zv.parse(await y.json())}async function z$(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"}),f=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,f,e,t);else{const h=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],y=Wv(r,h);Gv(y,r,u,f)}o&&f.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await Ed(p);return Zv.parse({refresh_token:n,...await p.json()})}async function Z$(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 Ed(s);return C$.parse(await s.json())}async function sl(e,t){var r,n;try{return await xd(e,t)}catch(o){if(o instanceof el||o instanceof rl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await xd(e,t);if(o instanceof tl)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await xd(e,t);throw o}}async function F$(e,t,r){const n=x$(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!$$({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 xd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await O$(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await F$(t,e,a),c=await N$(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 w=await Z$(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(w),u=w}if(r!==void 0){const w=await e.codeVerifier(),g=await U$(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:w,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}const f=await e.tokens();if(f?.refresh_token)try{const w=await z$(i,{metadata:c,clientInformation:u,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Ws)||w instanceof Ro))throw w}const p=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:y}=await q$(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(h),"REDIRECT"}var V$=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":$o};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return gn(t,`ai-sdk/${zv}`,Ms())}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=ol(u);try{if(await sl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new nl;return(s=this.onerror)==null||s.call(this,w),t(w)}}catch(y){return(a=this.onerror)==null||a.call(this,y),t(y)}return r(!0)}if(!u.ok||!u.body){let y=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(y+=". This server does not support SSE transport. Try using `http` transport instead");const w=new Fe({message:y});return(i=this.onerror)==null||i.call(this,w),t(w)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),h=async()=>{var y,w,g;try{for(;;){const{done:b,value:v}=await p.read();if(b){if(this.connected)throw this.connected=!1,new Fe({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:T}=v;if(m==="endpoint"){if(this.endpoint=new URL(T,this.url),this.endpoint.origin!==this.url.origin)throw new Fe({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=Js.parse(JSON.parse(T));(y=this.onmessage)==null||y.call(this,k)}catch(k){const _=new Fe({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,_)}}}catch(b){if(b instanceof Error&&b.name==="AbortError")return;(g=this.onerror)==null||g.call(this,b),t(b)}};this.sseConnection={close:()=>p.cancel()},h()}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 Fe({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},f=await fetch(t,u);if(f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ol(f);try{if(await sl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new nl;(s=this.onerror)==null||s.call(this,h);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!f.ok){const p=await f.text().catch(()=>null),h=new Fe({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${f.status}): ${p}`});(i=this.onerror)==null||i.call(this,h);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},H$=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":$o};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 gn(t,`ai-sdk/${zv}`,Ms())}async start(){if(this.abortController)throw new Fe({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 f={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,f),h=p.headers.get("mcp-session-id");if(h&&(this.sessionId=h),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=ol(p);try{if(await sl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new nl}catch(b){throw(o=this.onerror)==null||o.call(this,b),b}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const b=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${b}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const m=new Fe({message:v});throw(s=this.onerror)==null||s.call(this,m),m}if(!("id"in e))return;const w=p.headers.get("content-type")||"";if(w.includes("application/json")){const b=await p.json(),v=Array.isArray(b)?b.map(m=>Js.parse(m)):[Js.parse(b)];for(const m of v)(a=this.onmessage)==null||a.call(this,m);return}if(w.includes("text/event-stream")){if(!p.body){const T=new Fe({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,T),T}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader();(async()=>{var T,k,_;try{for(;;){const{done:S,value:$}=await v.read();if(S)return;const{event:x,data:U}=$;if(x==="message")try{const M=Js.parse(JSON.parse(U));(T=this.onmessage)==null||T.call(this,M)}catch(M){const O=new Fe({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(k=this.onerror)==null||k.call(this,O)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(_=this.onerror)==null||_.call(this,S)}})();return}const g=new Fe({message:`MCP HTTP Transport Error: Unexpected content type: ${w}`});throw(l=this.onerror)==null||l.call(this,g),g}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 Fe({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=ol(c);try{if(await sl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new nl;(n=this.onerror)==null||n.call(this,w);return}}catch(y){(o=this.onerror)==null||o.call(this,y);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const y=new Fe({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,y);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),h=async()=>{var y,w,g,b;try{for(;;){const{done:v,value:m}=await p.read();if(v)return;const{event:T,data:k,id:_}=m;if(_&&(this.lastInboundEventId=_),T==="message")try{const S=Js.parse(JSON.parse(k));(y=this.onmessage)==null||y.call(this,S)}catch(S){const $=new Fe({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(w=this.onerror)==null||w.call(this,$)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(g=this.onerror)==null||g.call(this,v),(b=this.abortController)!=null&&b.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,h()}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 B$(e){switch(e.type){case"sse":return new V$(e);case"http":return new H$(e);default:throw new Fe({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function J$(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var W$="1.0.0";function Kv({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 G$(e){const t=new K$(e);return await t.init(),t}var K$=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=W$,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},J$(e)?this.transport=e:this.transport=B$(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 Fe({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:$o,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Qx});if(e===void 0)throw new Fe({message:"Server sent invalid initialize result"});if(!Wx.includes(e.protocolVersion))throw new Fe({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 Fe({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Fe({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Fe({message:"Server does not support prompts"});break;default:throw new Fe({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Fe({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 Fe({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 f=new Fe({message:"Failed to parse server response",cause:u});o(f)}}),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:e$,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:n$,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:r$,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:a$,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:s$,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:d$,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 f=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,h=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,y=async(g,b)=>{var v;(v=b?.abortSignal)==null||v.throwIfAborted();const m=await p.callTool({name:s,args:g,options:b});return h!=null?p.extractStructuredContent(m,h,s):m},w=t==="automatic"?ng({description:i,title:f,inputSchema:Eo({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:y,toModelOutput:Kv}):{description:i,title:f,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:y,toModelOutput:Kv};o[s]={...w,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await nr({value:e.structuredContent,schema:Fn(t)});if(!n.success)throw new Fe({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 or({text:n.text,schema:t});if(!o.success)throw new Fe({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new Fe({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!==Uv)throw new Fe({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=Uv.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=f$.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 Fe({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 Fe({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Fe({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},$d=C({error:C({message:d(),type:d().nullish(),param:mt().nullish(),code:oe([d(),j()]).nullish()})}),br=yn({errorSchema:$d,errorToMessage:e=>e.error.message});function Yv(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 Qv(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 Y$({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,f;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,${Io(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 xr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Io(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Io(i.data),format:"mp3"}};default:throw new xr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new xr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(f=i.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Io(i.data)}`}}}else throw new xr({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 Rd({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Xv(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 Q$=Ie(()=>Ce(C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({message:C({role:P("assistant").nullish(),content:d().nullish(),tool_calls:q(C({id:d().nullish(),type:P("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:q(C({type:P("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()}))),X$=Ie(()=>Ce(oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:Ee(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(C({index:j(),id:d().nullish(),type:P("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(C({type:P("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()}),$d]))),e7=Ie(()=>Ce(C({logitBias:ge(Lh(),j()).optional(),logprobs:oe([me(),j()]).optional(),parallelToolCalls:me().optional(),user:d().optional(),reasoningEffort:Ee(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:me().optional(),metadata:ge(d().max(64),d().max(512)).optional(),prediction:ge(d(),mt()).optional(),serviceTier:Ee(["auto","flex","priority","default"]).optional(),strictJsonSchema:me().optional(),textVerbosity:Ee(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:Ee(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:Ee(["system","developer","remove"]).optional(),forceReasoning:me().optional()})));function t7({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 xr({functionality:`tool choice type: ${s}`})}}}var r7=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:f,providerOptions:p}){var h,y,w,g,b;const v=[],m=(h=await Jr({provider:"openai",providerOptions:p,schema:e7}))!=null?h:{},T=Yv(this.modelId),k=(y=m.forceReasoning)!=null?y:T.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:_,warnings:S}=Y$({prompt:e,systemMessageMode:(w=m.systemMessageMode)!=null?w:k?"developer":T.systemMessageMode});v.push(...S);const $=(g=m.strictJsonSchema)!=null?g:!0,x={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:$,name:(b=l.name)!=null?b:"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:_};k?((m.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,v.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,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),m.serviceTier==="flex"&&!T.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),m.serviceTier==="priority"&&!T.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"}),x.service_tier=void 0);const{tools:U,toolChoice:M,toolWarnings:O}=t7({tools:u,toolChoice:f});return{args:{...x,tools:U,tool_choice:M},warnings:[...v,...O]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:f,rawValue:p}=await Zt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:l,failedResponseHandler:br,successfulResponseHandler:Kt(Q$),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.choices[0],y=[],w=h.message.content;w!=null&&w.length>0&&y.push({type:"text",text:w});for(const v of(t=h.message.tool_calls)!=null?t:[])y.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:At(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=h.message.annotations)!=null?n:[])y.push({type:"source",sourceType:"url",id:At(),url:v.url_citation.url,title:v.url_citation.title});const g=(o=f.usage)==null?void 0:o.completion_tokens_details;(s=f.usage)==null||s.prompt_tokens_details;const b={openai:{}};return g?.accepted_prediction_tokens!=null&&(b.openai.acceptedPredictionTokens=g?.accepted_prediction_tokens),g?.rejected_prediction_tokens!=null&&(b.openai.rejectedPredictionTokens=g?.rejected_prediction_tokens),((a=h.logprobs)==null?void 0:a.content)!=null&&(b.openai.logprobs=h.logprobs.content),{content:y,finishReason:{unified:Xv(h.finish_reason),raw:(i=h.finish_reason)!=null?i:void 0},usage:Qv(f.usage),request:{body:l},response:{...Rd(f),headers:u,body:p},warnings:c,providerMetadata:b}}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 Zt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:n,failedResponseHandler:br,successfulResponseHandler:Fi(X$),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,h){var y,w,g,b,v,m,T,k,_,S,$,x,U,M,O,A,L;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}const Y=p.value;if("error"in Y){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:Y.error});return}if(!c){const K=Rd(Y);Object.values(K).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...Rd(Y)}))}Y.usage!=null&&(l=Y.usage,((y=Y.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(w=Y.usage.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens),((g=Y.usage.completion_tokens_details)==null?void 0:g.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(b=Y.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens));const J=Y.choices[0];if(J?.finish_reason!=null&&(i={unified:Xv(J.finish_reason),raw:J.finish_reason}),((v=J?.logprobs)==null?void 0:v.content)!=null&&(f.openai.logprobs=J.logprobs.content),J?.delta==null)return;const de=J.delta;if(de.content!=null&&(u||(h.enqueue({type:"text-start",id:"0"}),u=!0),h.enqueue({type:"text-delta",id:"0",delta:de.content})),de.tool_calls!=null)for(const K of de.tool_calls){const $e=K.index;if(a[$e]==null){if(K.type!=="function")throw new Fu({data:K,message:"Expected 'function' type."});if(K.id==null)throw new Fu({data:K,message:"Expected 'id' to be a string."});if(((m=K.function)==null?void 0:m.name)==null)throw new Fu({data:K,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),a[$e]={id:K.id,type:"function",function:{name:K.function.name,arguments:(T=K.function.arguments)!=null?T:""},hasFinished:!1};const N=a[$e];((k=N.function)==null?void 0:k.name)!=null&&((_=N.function)==null?void 0:_.arguments)!=null&&(N.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:N.id,delta:N.function.arguments}),eg(N.function.arguments)&&(h.enqueue({type:"tool-input-end",id:N.id}),h.enqueue({type:"tool-call",toolCallId:(S=N.id)!=null?S:At(),toolName:N.function.name,input:N.function.arguments}),N.hasFinished=!0));continue}const Z=a[$e];Z.hasFinished||((($=K.function)==null?void 0:$.arguments)!=null&&(Z.function.arguments+=(U=(x=K.function)==null?void 0:x.arguments)!=null?U:""),h.enqueue({type:"tool-input-delta",id:Z.id,delta:(M=K.function.arguments)!=null?M:""}),((O=Z.function)==null?void 0:O.name)!=null&&((A=Z.function)==null?void 0:A.arguments)!=null&&eg(Z.function.arguments)&&(h.enqueue({type:"tool-input-end",id:Z.id}),h.enqueue({type:"tool-call",toolCallId:(L=Z.id)!=null?L:At(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}if(de.annotations!=null)for(const K of de.annotations)h.enqueue({type:"source",sourceType:"url",id:At(),url:K.url_citation.url,title:K.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:Qv(l),...f!=null?{providerMetadata:f}:{}})}})),request:{body:n},response:{headers:o}}}};function e_(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 n7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
584
+ `)}})}},Vv={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function W8({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new Fv);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:dl(r,Vv)})}function G8({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 K8(e){return e.type.startsWith("data-")}function zd(e){return e.type.startsWith("tool-")}function Y8(e){return e.type==="dynamic-tool"}function Hv(e){return zd(e)||Y8(e)}function Bv(e){return e.type.split("-").slice(1).join("-")}function Q8({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function X8({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(Hv).find(b=>b.toolCallId===m);if(k==null)throw new Lo({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return k}function y(m){var C;const k=c.message.parts.find(x=>zd(x)&&x.toolCallId===m.toolCallId),b=m,S=k;k!=null?(k.state=m.state,S.input=b.input,S.output=b.output,S.errorText=b.errorText,S.rawInput=b.rawInput,S.preliminary=b.preliminary,m.title!==void 0&&(S.title=m.title),S.providerExecuted=(C=b.providerExecuted)!=null?C:k.providerExecuted,b.providerMetadata!=null&&(k.callProviderMetadata=b.providerMetadata)):c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,input:b.input,output:b.output,rawInput:b.rawInput,errorText:b.errorText,providerExecuted:b.providerExecuted,preliminary:b.preliminary,...b.providerMetadata!=null?{callProviderMetadata:b.providerMetadata}:{}})}function w(m){var C,k;const b=c.message.parts.find(I=>I.type==="dynamic-tool"&&I.toolCallId===m.toolCallId),S=m,x=b;b!=null?(b.state=m.state,x.toolName=m.toolName,x.input=S.input,x.output=S.output,x.errorText=S.errorText,x.rawInput=(C=S.rawInput)!=null?C:x.rawInput,x.preliminary=S.preliminary,m.title!==void 0&&(x.title=m.title),x.providerExecuted=(k=S.providerExecuted)!=null?k:b.providerExecuted,S.providerMetadata!=null&&(b.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:m.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function v(m){if(m!=null){const C=c.message.metadata!=null?ll(c.message.metadata,m):m;t!=null&&await Mt({value:C,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=C}}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 Lo({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 Lo({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 Lo({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 Lo({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(zd);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 Lo({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:C}=await Xs(m.text);m.dynamic?w({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:C,title:m.title}):y({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:C,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":{const m=c.message.parts.filter(Hv).find(k=>k.toolCallId===i.toolCallId);(m!=null?m.type==="dynamic-tool":!!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:Bv(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:Bv(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(K8(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),b=k>=0?k:c.message.parts.length;await Mt({value:i.data,schema:r[i.type],context:{field:`message.parts[${b}].data`,entityName:i.type,entityId:i.id}})}const m=i;if(m.transient){a?.(m);break}const C=m.id!=null?c.message.parts.find(k=>m.type===k.type&&m.id===k.id):void 0;C!=null?C.data=m.data:c.message.parts.push(m),a?.(m),u()}}l.enqueue(i)})}}))}function e$({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=Q8({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 X8({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 t$({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new Fv);if(s){const[i,l]=a.tee();a=i,s({stream:l})}Zv({response:e,status:t,statusText:r,headers:Object.fromEntries(dl(n,Vv).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function ea(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 r$({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 Jv(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function n$(){let e=[],t=null,r=!1,n=Jv();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=Jv(),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 o$({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(S){g=S}}),y=new Set,w=new Map,v=new Map;let m=!1,C;function k(){m&&y.size===0&&(C!=null&&g.enqueue(C),g.close())}const b=new TransformStream({async transform(S,x){const I=S.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(S);break}case"file":{x.enqueue({type:"file",file:new q8({data:S.data,mediaType:S.mediaType})});break}case"finish":{C={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:Cv(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const L=v.get(S.toolCallId);if(L==null){g.enqueue({type:"error",error:new Md({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}x.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:L});break}case"tool-call":{try{const L=await Ov({toolCall:S,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:cd(L.error),dynamic:!0,title:L.title});break}const $=e?.[L.toolName];if($==null)break;if($.onInputAvailable!=null&&await $.onInputAvailable({input:L.input,toolCallId:L.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await Mv({tool:$,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),$.execute!=null&&L.providerExecuted!==!0){const N=c();y.add(N),jd({toolCall:L,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:h,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:A=>{g.enqueue(A)}}).then(A=>{g.enqueue(A)}).catch(A=>{g.enqueue({type:"error",error:A})}).finally(()=>{y.delete(N),k()})}}catch(L){g.enqueue({type:"error",error:L})}break}case"tool-result":{const L=S.toolName;S.isError?g.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:L,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):x.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:L,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const L=I;throw new Error(`Unhandled chunk type: ${L}`)}}},flush(){m=!0,k()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(b).pipeTo(new WritableStream({write(x){S.enqueue(x)},close(){}})),_.pipeTo(new WritableStream({write(x){S.enqueue(x)},close(){S.close()}}))])}})}var s$=zs({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=Dd(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:C,includeRawChunks:k=!1,onChunk:b,onError:S=({error:H})=>{console.error(H)},onFinish:x,onAbort:I,onStepFinish:L,experimental_onStart:$,experimental_onStepStart:N,experimental_onToolCallStart:A,experimental_onToolCallFinish:U,experimental_context:V,experimental_include:Q,_internal:{now:_e=cl,generateId:te=s$}={},...ge}){const H=Ad(l),M=iv(l),B=l8(l),Z=M!=null?new AbortController:void 0,E=B!=null?new AbortController:void 0;return new i$({model:al(e),telemetry:f,headers:c,settings:ge,maxRetries:a,abortSignal:jv(i,H!=null?AbortSignal.timeout(H):void 0,Z?.signal,E?.signal),stepTimeoutMs:M,stepAbortController:Z,chunkTimeoutMs:B,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:jo(m),activeTools:w,repairToolCall:v,stopConditions:jo(u),output:p,providerOptions:_,prepareStep:g,includeRawChunks:k,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:b,onError:S,onFinish:x,onAbort:I,onStepFinish:L,onStart:$,onStepStart:N,onToolCallStart:A,onToolCallFinish:U,now:_e,generateId:te,experimental_context:V,download:C,include:Q})}function a$(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 i$=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:C,prepareStep:k,includeRawChunks:b,now:S,generateId:x,timeout:I,stopWhen:L,originalAbortSignal:$,onChunk:N,onError:A,onFinish:U,onAbort:V,onStepFinish:Q,onStart:_e,onStepStart:te,onToolCallStart:ge,onToolCallFinish:H,experimental_context:M,download:B,include:Z}){this._totalUsage=new Us,this._finishReason=new Us,this._rawFinishReason=new Us,this._steps=new Us,this.outputSpecification=m,this.includeRawChunks=b,this.tools=f;let E,O=[];const D=[];let G,re,ie,Ie={},z=[];const F=[],K=new Map;let ee,le={},we={};const et=new TransformStream({async transform(rt,xe){var at,Ee,Ye,Pr;xe.enqueue(rt);const{part:Y}=rt;if((Y.type==="text-delta"||Y.type==="reasoning-delta"||Y.type==="source"||Y.type==="tool-call"||Y.type==="tool-result"||Y.type==="tool-input-start"||Y.type==="tool-input-delta"||Y.type==="raw")&&await N?.({chunk:Y}),Y.type==="error"&&await A({error:_v(Y.error)}),Y.type==="text-start"&&(le[Y.id]={type:"text",text:"",providerMetadata:Y.providerMetadata},O.push(le[Y.id])),Y.type==="text-delta"){const Qe=le[Y.id];if(Qe==null){xe.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Qe.text+=Y.text,Qe.providerMetadata=(at=Y.providerMetadata)!=null?at:Qe.providerMetadata}if(Y.type==="text-end"){const Qe=le[Y.id];if(Qe==null){xe.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Qe.providerMetadata=(Ee=Y.providerMetadata)!=null?Ee:Qe.providerMetadata,delete le[Y.id]}if(Y.type==="reasoning-start"&&(we[Y.id]={type:"reasoning",text:"",providerMetadata:Y.providerMetadata},O.push(we[Y.id])),Y.type==="reasoning-delta"){const Qe=we[Y.id];if(Qe==null){xe.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Qe.text+=Y.text,Qe.providerMetadata=(Ye=Y.providerMetadata)!=null?Ye:Qe.providerMetadata}if(Y.type==="reasoning-end"){const Qe=we[Y.id];if(Qe==null){xe.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Qe.providerMetadata=(Pr=Y.providerMetadata)!=null?Pr:Qe.providerMetadata,delete we[Y.id]}if(Y.type==="file"&&O.push({type:"file",file:Y.file}),Y.type==="source"&&O.push(Y),Y.type==="tool-call"&&O.push(Y),Y.type==="tool-result"&&!Y.preliminary&&O.push(Y),Y.type==="tool-approval-request"&&O.push(Y),Y.type==="tool-error"&&O.push(Y),Y.type==="start-step"&&(O=[],we={},le={},Ie=Y.request,z=Y.warnings),Y.type==="finish-step"){const Qe=await Ud({content:O,tools:f}),Mr=new qv({stepNumber:F.length,model:nr,...ln,experimental_context:M,content:O,finishReason:Y.finishReason,rawFinishReason:Y.rawFinishReason,usage:Y.usage,warnings:z,request:Ie,response:{...Y.response,messages:[...D,...Qe]},providerMetadata:Y.providerMetadata});await Er({event:Mr,callbacks:Q}),Nd({warnings:z,provider:nr.provider,model:nr.modelId}),F.push(Mr),D.push(...Qe),E.resolve()}Y.type==="finish"&&(ie=Y.totalUsage,G=Y.finishReason,re=Y.rawFinishReason)},async flush(rt){try{if(F.length===0){const Ye=s?.aborted?s.reason:new zy({message:"No output generated. Check the stream for errors."});tt._finishReason.reject(Ye),tt._rawFinishReason.reject(Ye),tt._totalUsage.reject(Ye),tt._steps.reject(Ye);return}const xe=G??"other",at=ie??Ld();tt._finishReason.resolve(xe),tt._rawFinishReason.resolve(re),tt._totalUsage.resolve(at),tt._steps.resolve(F);const Ee=F[F.length-1];await Er({event:{stepNumber:Ee.stepNumber,model:Ee.model,functionId:Ee.functionId,metadata:Ee.metadata,experimental_context:Ee.experimental_context,finishReason:Ee.finishReason,rawFinishReason:Ee.rawFinishReason,totalUsage:at,usage:Ee.usage,content:Ee.content,text:Ee.text,reasoningText:Ee.reasoningText,reasoning:Ee.reasoning,files:Ee.files,sources:Ee.sources,toolCalls:Ee.toolCalls,staticToolCalls:Ee.staticToolCalls,dynamicToolCalls:Ee.dynamicToolCalls,toolResults:Ee.toolResults,staticToolResults:Ee.staticToolResults,dynamicToolResults:Ee.dynamicToolResults,request:Ee.request,response:Ee.response,warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,steps:F},callbacks:U}),ee.setAttributes(await zr({telemetry:t,attributes:{"ai.response.finishReason":xe,"ai.response.text":{output:()=>Ee.text},"ai.response.reasoning":{output:()=>Ee.reasoningText},"ai.response.toolCalls":{output:()=>{var Ye;return(Ye=Ee.toolCalls)!=null&&Ye.length?JSON.stringify(Ee.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ee.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(xe){rt.error(xe)}finally{ee.end()}}}),pt=n$();this.addStream=pt.addStream,this.closeStream=pt.close;const mt=pt.stream.getReader();let st=new ReadableStream({async start(rt){rt.enqueue({type:"start"})},async pull(rt){function xe(){V?.({steps:F}),rt.enqueue({type:"abort",...s?.reason!==void 0?{reason:Wn(s.reason)}:{}}),rt.close()}try{const{done:at,value:Ee}=await mt.read();if(at){rt.close();return}if(s?.aborted){xe();return}rt.enqueue(Ee)}catch(at){Yn(at)&&s?.aborted?xe():rt.error(at)}},cancel(rt){return pt.stream.cancel(rt)}});for(const rt of _)st=st.pipeThrough(rt({tools:f,stopStream(){pt.terminate()}}));this.baseStream=st.pipeThrough(a$(m??ul())).pipeThrough(et);const{maxRetries:P,retry:ne}=xv({maxRetries:o,abortSignal:s}),Oe=bv(t),qe=qd(n),pr=wv({model:e,telemetry:t,headers:r,settings:{...qe,maxRetries:P}}),tt=this,nr={provider:e.provider,modelId:e.modelId},ln={functionId:t?.functionId,metadata:t?.metadata};Qs({name:"ai.streamText",attributes:zr({telemetry:t,attributes:{...Ys({operationId:"ai.streamText",telemetry:t}),...pr,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:Oe,endWhenDone:!1,fn:async rt=>{ee=rt;const xe=await vv({system:u,prompt:h,messages:p});await Er({event:{model:nr,system:u,prompt:h,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:qe.maxOutputTokens,temperature:qe.temperature,topP:qe.topP,topK:qe.topK,presencePenalty:qe.presencePenalty,frequencyPenalty:qe.frequencyPenalty,stopSequences:qe.stopSequences,seed:qe.seed,maxRetries:P,timeout:I,headers:r,providerOptions:C,stopWhen:L,output:m,abortSignal:$,include:Z,...ln,experimental_context:M},callbacks:_e});const at=xe.messages,Ee=[],{approvedToolApprovals:Ye,deniedToolApprovals:Pr}=Ev({messages:at});if(Pr.length>0||Ye.length>0){const Qe=[...Ye,...Pr].filter(gt=>gt.toolCall.providerExecuted),Mr=Ye.filter(gt=>!gt.toolCall.providerExecuted),it=Pr.filter(gt=>!gt.toolCall.providerExecuted),St=Pr.filter(gt=>gt.toolCall.providerExecuted);let Se;const qt=new ReadableStream({start(gt){Se=gt}});tt.addStream(qt);try{for(const It of[...it,...St])Se?.enqueue({type:"tool-output-denied",toolCallId:It.toolCall.toolCallId,toolName:It.toolCall.toolName});const gt=[];if(await Promise.all(Mr.map(async It=>{const ft=await jd({toolCall:It.toolCall,tools:f,tracer:Oe,telemetry:t,messages:at,abortSignal:s,experimental_context:M,stepNumber:F.length,model:nr,onToolCallStart:ge,onToolCallFinish:H,onPreliminaryToolResult:cn=>{Se?.enqueue(cn)}});ft!=null&&(Se?.enqueue(ft),gt.push(ft))})),Qe.length>0&&Ee.push({role:"tool",content:Qe.map(It=>({type:"tool-approval-response",approvalId:It.approvalResponse.approvalId,approved:It.approvalResponse.approved,reason:It.approvalResponse.reason,providerExecuted:!0}))}),gt.length>0||it.length>0){const It=[];for(const ft of gt)It.push({type:"tool-result",toolCallId:ft.toolCallId,toolName:ft.toolName,output:await Gs({toolCallId:ft.toolCallId,input:ft.input,tool:f?.[ft.toolName],output:ft.type==="tool-result"?ft.output:ft.error,errorMode:ft.type==="tool-error"?"json":"none"})});for(const ft of it)It.push({type:"tool-result",toolCallId:ft.toolCall.toolCallId,toolName:ft.toolCall.toolName,output:{type:"execution-denied",reason:ft.approvalResponse.reason}});Ee.push({role:"tool",content:It})}}finally{Se?.close()}}D.push(...Ee);async function Y({currentStep:Qe,responseMessages:Mr,usage:it}){var St,Se,qt,gt,It,ft,cn,zo,Cl;const Sl=tt.includeRawChunks,aa=a!=null?setTimeout(()=>i.abort(),a):void 0;let fr;function ia(){l!=null&&(fr!=null&&clearTimeout(fr),fr=setTimeout(()=>c.abort(),l))}function Il(){fr!=null&&(clearTimeout(fr),fr=void 0)}function la(){aa!=null&&clearTimeout(aa)}try{E=new Us;const Rn=[...at,...Mr],_t=await k?.({model:e,steps:F,stepNumber:F.length,messages:Rn,experimental_context:M}),Zr=al((St=_t?.model)!=null?St:e),ca={provider:Zr.provider,modelId:Zr.modelId},Le=await dv({prompt:{system:(Se=_t?.system)!=null?Se:xe.system,messages:(qt=_t?.messages)!=null?qt:Rn},supportedUrls:await Zr.supportedUrls,download:B}),Lt=(gt=_t?.activeTools)!=null?gt:y,{toolChoice:Pn,tools:un}=await hv({tools:f,toolChoice:(It=_t?.toolChoice)!=null?It:g,activeTools:Lt});M=(ft=_t?.experimental_context)!=null?ft:M;const xl=(cn=_t?.messages)!=null?cn:Rn,El=(zo=_t?.system)!=null?zo:xe.system,ua=ll(C,_t?.providerOptions);await Er({event:{stepNumber:F.length,model:ca,system:El,messages:xl,tools:f,toolChoice:Pn,activeTools:Lt,steps:[...F],providerOptions:ua,timeout:I,headers:r,stopWhen:L,output:m,abortSignal:$,include:Z,...ln,experimental_context:M},callbacks:te});const{result:{stream:$l,response:da,request:Zo},doStreamSpan:ht,startTimestampMs:dn}=await ne(()=>Qs({name:"ai.streamText.doStream",attributes:zr({telemetry:t,attributes:{...Ys({operationId:"ai.streamText.doStream",telemetry:t}),...pr,"ai.model.provider":Zr.provider,"ai.model.id":Zr.modelId,"ai.prompt.messages":{input:()=>Tv(Le)},"ai.prompt.tools":{input:()=>un?.map(be=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>Pn!=null?JSON.stringify(Pn):void 0},"gen_ai.system":Zr.provider,"gen_ai.request.model":Zr.modelId,"gen_ai.request.frequency_penalty":qe.frequencyPenalty,"gen_ai.request.max_tokens":qe.maxOutputTokens,"gen_ai.request.presence_penalty":qe.presencePenalty,"gen_ai.request.stop_sequences":qe.stopSequences,"gen_ai.request.temperature":qe.temperature,"gen_ai.request.top_k":qe.topK,"gen_ai.request.top_p":qe.topP}}),tracer:Oe,endWhenDone:!1,fn:async be=>({startTimestampMs:S(),doStreamSpan:be,result:await Zr.doStream({...qe,tools:un,toolChoice:Pn,responseFormat:await m?.responseFormat,prompt:Le,providerOptions:ua,abortSignal:s,headers:r,includeRawChunks:Sl})})})),Rl=o$({tools:f,generatorStream:$l,tracer:Oe,telemetry:t,system:u,messages:Rn,repairToolCall:w,abortSignal:s,experimental_context:M,generateId:x,stepNumber:F.length,model:ca,onToolCallStart:ge,onToolCallFinish:H}),FP=(Cl=Z?.requestBody)==null||Cl?Zo??{}:{...Zo,body:void 0},pa=[],fa=[];let op;const sp={};let Fo="other",ap,Or=Ld(),ip,j1=!0,Fr={id:x(),timestamp:new Date,modelId:nr.modelId},D1="";tt.addStream(Rl.pipeThrough(new TransformStream({async transform(be,Ot){var ha,ma,Pl,yt,Vr;if(ia(),be.type==="stream-start"){op=be.warnings;return}if(j1){const vt=S()-dn;j1=!1,ht.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":vt}),ht.setAttributes({"ai.response.msToFirstChunk":vt}),Ot.enqueue({type:"start-step",request:FP,warnings:op??[]})}const lp=be.type;switch(lp){case"tool-approval-request":case"text-start":case"text-end":{Ot.enqueue(be);break}case"text-delta":{be.delta.length>0&&(Ot.enqueue({type:"text-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata}),D1+=be.delta);break}case"reasoning-start":case"reasoning-end":{Ot.enqueue(be);break}case"reasoning-delta":{Ot.enqueue({type:"reasoning-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata});break}case"tool-call":{Ot.enqueue(be),pa.push(be);break}case"tool-result":{Ot.enqueue(be),be.preliminary||fa.push(be);break}case"tool-error":{Ot.enqueue(be),fa.push(be);break}case"response-metadata":{Fr={id:(ha=be.id)!=null?ha:Fr.id,timestamp:(ma=be.timestamp)!=null?ma:Fr.timestamp,modelId:(Pl=be.modelId)!=null?Pl:Fr.modelId};break}case"finish":{Or=be.usage,Fo=be.finishReason,ap=be.rawFinishReason,ip=be.providerMetadata;const vt=S()-dn;ht.addEvent("ai.stream.finish"),ht.setAttributes({"ai.response.msToFinish":vt,"ai.response.avgOutputTokensPerSecond":1e3*((yt=Or.outputTokens)!=null?yt:0)/vt});break}case"file":{Ot.enqueue(be);break}case"source":{Ot.enqueue(be);break}case"tool-input-start":{sp[be.id]=be.toolName;const vt=f?.[be.toolName];vt?.onInputStart!=null&&await vt.onInputStart({toolCallId:be.id,messages:Rn,abortSignal:s,experimental_context:M}),Ot.enqueue({...be,dynamic:(Vr=be.dynamic)!=null?Vr:vt?.type==="dynamic",title:vt?.title});break}case"tool-input-end":{delete sp[be.id],Ot.enqueue(be);break}case"tool-input-delta":{const vt=sp[be.id],cp=f?.[vt];cp?.onInputDelta!=null&&await cp.onInputDelta({inputTextDelta:be.delta,toolCallId:be.id,messages:Rn,abortSignal:s,experimental_context:M}),Ot.enqueue(be);break}case"error":{Ot.enqueue(be),Fo="error";break}case"raw":{Sl&&Ot.enqueue(be);break}default:{const vt=lp;throw new Error(`Unknown chunk type: ${vt}`)}}},async flush(be){const Ot=pa.length>0?JSON.stringify(pa):void 0;try{ht.setAttributes(await zr({telemetry:t,attributes:{"ai.response.finishReason":Fo,"ai.response.text":{output:()=>D1},"ai.response.reasoning":{output:()=>{const yt=O.filter(Vr=>Vr.type==="reasoning");return yt.length>0?yt.map(Vr=>Vr.text).join(`
585
+ `):void 0}},"ai.response.toolCalls":{output:()=>Ot},"ai.response.id":Fr.id,"ai.response.model":Fr.modelId,"ai.response.timestamp":Fr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ip),"ai.usage.inputTokens":Or.inputTokens,"ai.usage.outputTokens":Or.outputTokens,"ai.usage.totalTokens":Or.totalTokens,"ai.usage.reasoningTokens":Or.reasoningTokens,"ai.usage.cachedInputTokens":Or.cachedInputTokens,"gen_ai.response.finish_reasons":[Fo],"gen_ai.response.id":Fr.id,"gen_ai.response.model":Fr.modelId,"gen_ai.usage.input_tokens":Or.inputTokens,"gen_ai.usage.output_tokens":Or.outputTokens}}))}catch{}finally{ht.end()}be.enqueue({type:"finish-step",finishReason:Fo,rawFinishReason:ap,usage:Or,providerMetadata:ip,response:{...Fr,headers:da?.headers}});const ha=Sv(it,Or);await E.promise;const ma=pa.filter(yt=>yt.providerExecuted!==!0),Pl=fa.filter(yt=>yt.providerExecuted!==!0);for(const yt of pa){if(yt.providerExecuted!==!0)continue;const Vr=f?.[yt.toolName];Vr?.type==="provider"&&Vr.supportsDeferredResults&&(fa.some(vt=>(vt.type==="tool-result"||vt.type==="tool-error")&&vt.toolCallId===yt.toolCallId)||K.set(yt.toolCallId,{toolName:yt.toolName}))}for(const yt of fa)(yt.type==="tool-result"||yt.type==="tool-error")&&K.delete(yt.toolCallId);if(la(),Il(),(ma.length>0&&Pl.length===ma.length||K.size>0)&&!await Lv({stopConditions:v,steps:F})){Mr.push(...await Ud({content:F[F.length-1].content,tools:f}));try{await Y({currentStep:Qe+1,responseMessages:Mr,usage:ha})}catch(yt){be.enqueue({type:"error",error:yt}),tt.closeStream()}}else be.enqueue({type:"finish",finishReason:Fo,rawFinishReason:ap,totalUsage:ha}),tt.closeStream()}})))}finally{la(),Il()}}await Y({currentStep:0,responseMessages:Ee,usage:Ld()})}}).catch(rt=>{tt.addStream(new ReadableStream({start(xe){xe.enqueue({type:"error",error:rt}),xe.close()}})),tt.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 ea(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ea(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await r$({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 ea(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 jr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return ea(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:ul()).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=Wn}={}){const c=t!=null?G8({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 ea(e$({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}={}){t$({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){J8({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 W8({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 B8({textStream:this.textStream,...e})}};zs({prefix:"aiobj",size:24}),zs({prefix:"aiobj",size:24});var l$="AI_MCPClientError",Wv=`vercel.ai.error.${l$}`,c$=Symbol.for(Wv),Gv,Kv,Ze=class extends(Kv=ve,Gv=c$,Kv){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Gv]=!0,this.data=n,this.code=o}static isInstance(e){return ve.hasMarker(e,Wv)}},Do="2025-06-18",u$=[Do,"2025-03-26","2024-11-05"],d$=de(ye(d(),Me())),p$=ct({name:d(),version:d()}),pl=ct({_meta:de(T({}).loose())}),sn=pl,Yv=T({method:d(),params:de(pl)}),Qv=T({applyDefaults:de(he())}).loose(),f$=ct({experimental:de(T({}).loose()),logging:de(T({}).loose()),prompts:de(ct({listChanged:de(he())})),resources:de(ct({subscribe:de(he()),listChanged:de(he())})),tools:de(ct({listChanged:de(he())})),elicitation:de(Qv)});T({elicitation:de(Qv)}).loose();var h$=sn.extend({protocolVersion:d(),capabilities:f$,serverInfo:p$,instructions:de(d())}),Fd=sn.extend({nextCursor:de(d())}),m$=T({name:d(),title:de(d()),description:de(d()),inputSchema:T({type:R("object"),properties:de(T({}).loose())}).loose(),outputSchema:de(T({}).loose()),annotations:de(T({title:de(d())}).loose()),_meta:d$}).loose(),g$=Fd.extend({tools:q(m$)}),Xv=T({type:R("text"),text:d()}).loose(),e_=T({type:R("image"),data:Fh(),mimeType:d()}).loose(),y$=T({uri:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d()),size:de(j())}).loose(),v$=Fd.extend({resources:q(y$)}),t_=T({uri:d(),name:de(d()),title:de(d()),mimeType:de(d())}).loose(),r_=t_.extend({text:d()}),n_=t_.extend({blob:Fh()}),o_=T({type:R("resource"),resource:oe([r_,n_])}).loose(),_$=sn.extend({content:q(oe([Xv,e_,o_])),structuredContent:de(Me()),isError:he().default(!1).optional()}).or(sn.extend({toolResult:Me()})),w$=T({uriTemplate:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d())}).loose(),b$=sn.extend({resourceTemplates:q(w$)}),k$=sn.extend({contents:q(oe([r_,n_]))}),T$=T({name:d(),description:de(d()),required:de(he())}).loose(),C$=T({name:d(),title:de(d()),description:de(d()),arguments:de(q(T$))}).loose(),S$=Fd.extend({prompts:q(C$)}),I$=T({role:oe([R("user"),R("assistant")]),content:oe([Xv,e_,o_])}).loose(),x$=sn.extend({description:de(d()),messages:q(I$)}),E$=pl.extend({message:d(),requestedSchema:Me()}),s_=Yv.extend({method:R("elicitation/create"),params:E$}),$$=sn.extend({action:oe([R("accept"),R("decline"),R("cancel")]),content:de(ye(d(),Me()))}),fl="2.0",R$=T({jsonrpc:R(fl),id:oe([d(),j().int()])}).merge(Yv).strict(),P$=T({jsonrpc:R(fl),id:oe([d(),j().int()]),result:sn}).strict(),M$=T({jsonrpc:R(fl),id:oe([d(),j().int()]),error:T({code:j().int(),message:d(),data:de(Me())})}).strict(),O$=T({jsonrpc:R(fl)}).merge(T({method:d(),params:de(pl)})).strict(),ta=oe([R$,O$,P$,M$]),a_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",i_=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Kt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xh.custom,message:"URL must be parseable",fatal:!0}),Kf}).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"}),N$=T({resource:d().url(),authorization_servers:q(Kt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}).passthrough(),l_=T({issuer:d(),authorization_endpoint:Kt,token_endpoint:Kt,registration_endpoint:Kt.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(),A$=T({issuer:d(),authorization_endpoint:Kt,token_endpoint:Kt,userinfo_endpoint:Kt.optional(),jwks_uri:Kt,registration_endpoint:Kt.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(),q$=A$.merge(l_.pick({code_challenge_methods_supported:!0})),L$=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),j$=T({redirect_uris:q(Kt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Kt.optional(),logo_uri:Kt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Kt.optional(),policy_uri:d().optional(),jwks_uri:Kt.optional(),jwks:kt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),D$=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),U$=j$.merge(L$),z$="AI_MCPClientOAuthError",c_=`vercel.ai.error.${z$}`,Z$=Symbol.for(c_),u_,d_,ra=class extends(d_=ve,u_=Z$,d_){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[u_]=!0}static isInstance(e){return ve.hasMarker(e,c_)}},Uo=class extends ra{};Uo.errorCode="server_error";var hl=class extends ra{};hl.errorCode="invalid_client";var ml=class extends ra{};ml.errorCode="invalid_grant";var gl=class extends ra{};gl.errorCode="unauthorized_client";var F$={[Uo.errorCode]:Uo,[hl.errorCode]:hl,[ml.errorCode]:ml,[gl.errorCode]:gl};function V$(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function H$({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 yl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function vl(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 B$(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Vd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Vd(e,void 0,r):void 0;throw n}}async function p_(e,t,r=fetch){return await Vd(e,{"MCP-Protocol-Version":t},r)}function J$(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function W$(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Do;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=B$(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await p_(l,i,r);if(!n?.metadataUrl&&J$(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await p_(u,i,r)}return c}async function G$(e,t,r=fetch){const n=await W$(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 N$.parse(await n.json())}function K$(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 Y$(e,{fetchFn:t=fetch,protocolVersion:r=Do}={}){var n;const o={"MCP-Protocol-Version":r},s=K$(e);for(const{url:a,type:i}of s){const l=await Vd(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 l_.parse(await l.json());{const c=q$.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 Q$(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 n0(),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 f_(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 h_(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":X$(o,s,r);return;case"client_secret_post":e7(o,s,n);return;case"none":t7(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function X$(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 e7(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function t7(e,t){t.set("client_id",e)}async function Hd(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=D$.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=F$[o]||Uo;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Uo({message:o})}}async function r7(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=f_(r,_);h_(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 Hd(g);return i_.parse(await g.json())}async function n7(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=f_(r,f);h_(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 Hd(p);return i_.parse({refresh_token:n,...await p.json()})}async function o7(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 Hd(s);return U$.parse(await s.json())}async function _l(e,t){var r,n;try{return await Bd(e,t)}catch(o){if(o instanceof hl||o instanceof gl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Bd(e,t);if(o instanceof ml)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Bd(e,t);throw o}}async function s7(e,t,r){const n=V$(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!H$({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 Bd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await G$(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await s7(t,e,a),c=await Y$(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 o7(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(_),u=_}if(r!==void 0){const _=await e.codeVerifier(),y=await r7(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 n7(i,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof ra)||_ instanceof Uo))throw _}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await Q$(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 a7=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":Do};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return xn(t,`ai-sdk/${a_}`,Zs())}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=vl(u);try{if(await _l(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new yl;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 xo).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:C}=v;if(m==="endpoint"){if(this.endpoint=new URL(C,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=ta.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,k)}catch(k){const b=new Ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(_=this.onerror)==null||_.call(this,b)}}}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=vl(h);try{if(await _l(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new yl;(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()}},i7=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":Do};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 xn(t,`ai-sdk/${a_}`,Zs())}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=vl(p);try{if(await _l(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new yl}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=>ta.parse(m)):[ta.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 C=new Ze({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,C),C}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new xo).getReader();(async()=>{var C,k,b;try{for(;;){const{done:S,value:x}=await v.read();if(S)return;const{event:I,data:L}=x;if(I==="message")try{const $=ta.parse(JSON.parse(L));(C=this.onmessage)==null||C.call(this,$)}catch($){const N=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:$});(k=this.onerror)==null||k.call(this,N)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(b=this.onerror)==null||b.call(this,S)}})();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=vl(c);try{if(await _l(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new yl;(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 xo).getReader(),f=async()=>{var g,_,y,w;try{for(;;){const{done:v,value:m}=await p.read();if(v)return;const{event:C,data:k,id:b}=m;if(b&&(this.lastInboundEventId=b),C==="message")try{const S=ta.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,S)}catch(S){const x=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(_=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 l7(e){switch(e.type){case"sse":return new a7(e);case"http":return new i7(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 c7(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var u7="1.0.0";function m_({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 d7(e){const t=new p7(e);return await t.init(),t}var p7=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=u7,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},c7(e)?this.transport=e:this.transport=l7(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:Do,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:h$});if(e===void 0)throw new Ze({message:"Server sent invalid initialize result"});if(!u$.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:g$,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:_$,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:v$,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:k$,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:b$,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:S$,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:x$,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"?bg({description:i,title:h,inputSchema:qo({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:m_}):{description:i,title:h,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:m_};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:Xn(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!==s_)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=s_.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=$$.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}))}},Jd=T({error:T({message:d(),type:d().nullish(),param:kt().nullish(),code:oe([d(),j()]).nullish()})}),Rr=En({errorSchema:Jd,errorToMessage:e=>e.error.message});function g_(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 y_(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 f7({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,${No(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 jr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:No(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:No(i.data),format:"mp3"}};default:throw new jr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new jr({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,${No(i.data)}`}}}else throw new jr({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 Wd({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function v_(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 h7=Ce(()=>Te(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:R("assistant").nullish(),content:d().nullish(),tool_calls:q(T({id:d().nullish(),type:R("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:q(T({type:R("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}),index:j(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),m7=Ce(()=>Te(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:me(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),type:R("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(T({type:R("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:j()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Jd]))),g7=Ce(()=>Te(T({logitBias:ye(em(),j()).optional(),logprobs:oe([he(),j()]).optional(),parallelToolCalls:he().optional(),user:d().optional(),reasoningEffort:me(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:he().optional(),metadata:ye(d().max(64),d().max(512)).optional(),prediction:ye(d(),kt()).optional(),serviceTier:me(["auto","flex","priority","default"]).optional(),strictJsonSchema:he().optional(),textVerbosity:me(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:me(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));function y7({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 jr({functionality:`tool choice type: ${s}`})}}}var v7=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 nn({provider:"openai",providerOptions:p,schema:g7}))!=null?f:{},C=g_(this.modelId),k=(g=m.forceReasoning)!=null?g:C.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:b,warnings:S}=f7({prompt:e,systemMessageMode:(_=m.systemMessageMode)!=null?_:k?"developer":C.systemMessageMode});v.push(...S);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:b};k?((m.reasoningEffort!=="none"||!C.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"&&!C.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"&&!C.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:$,toolWarnings:N}=y7({tools:u,toolChoice:h});return{args:{...I,tools:L,tool_choice:$},warnings:[...v,...N]}}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 Wt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:l,failedResponseHandler:Rr,successfulResponseHandler:dr(h7),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:zt(),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:zt(),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:v_(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:y_(h.usage),request:{body:l},response:{...Wd(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 Wt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:rl(m7),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,C,k,b,S,x,I,L,$,N,A,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 V=p.value;if("error"in V){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:V.error});return}if(!c){const te=Wd(V);Object.values(te).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Wd(V)}))}V.usage!=null&&(l=V.usage,((g=V.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(_=V.usage.completion_tokens_details)==null?void 0:_.accepted_prediction_tokens),((y=V.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=V.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const Q=V.choices[0];if(Q?.finish_reason!=null&&(i={unified:v_(Q.finish_reason),raw:Q.finish_reason}),((v=Q?.logprobs)==null?void 0:v.content)!=null&&(h.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const _e=Q.delta;if(_e.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:_e.content})),_e.tool_calls!=null)for(const te of _e.tool_calls){const ge=te.index;if(a[ge]==null){if(te.type!=null&&te.type!=="function")throw new id({data:te,message:"Expected 'function' type."});if(te.id==null)throw new id({data:te,message:"Expected 'id' to be a string."});if(((m=te.function)==null?void 0:m.name)==null)throw new id({data:te,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),a[ge]={id:te.id,type:"function",function:{name:te.function.name,arguments:(C=te.function.arguments)!=null?C:""},hasFinished:!1};const M=a[ge];((k=M.function)==null?void 0:k.name)!=null&&((b=M.function)==null?void 0:b.arguments)!=null&&(M.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),yg(M.function.arguments)&&(f.enqueue({type:"tool-input-end",id:M.id}),f.enqueue({type:"tool-call",toolCallId:(S=M.id)!=null?S:zt(),toolName:M.function.name,input:M.function.arguments}),M.hasFinished=!0));continue}const H=a[ge];H.hasFinished||(((x=te.function)==null?void 0:x.arguments)!=null&&(H.function.arguments+=(L=(I=te.function)==null?void 0:I.arguments)!=null?L:""),f.enqueue({type:"tool-input-delta",id:H.id,delta:($=te.function.arguments)!=null?$:""}),((N=H.function)==null?void 0:N.name)!=null&&((A=H.function)==null?void 0:A.arguments)!=null&&yg(H.function.arguments)&&(f.enqueue({type:"tool-input-end",id:H.id}),f.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:zt(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(_e.annotations!=null)for(const te of _e.annotations)f.enqueue({type:"source",sourceType:"url",id:zt(),url:te.url_citation.url,title:te.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:y_(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function __(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 _7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
586
586
 
587
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Dn({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}:
587
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Gn({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}:
588
588
  ${a}
589
589
 
590
- `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new xr({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 jr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
591
591
  ${a}
592
592
 
593
- `;break}case"tool":throw new xr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
593
+ `;break}case"tool":throw new jr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
594
594
  `,{prompt:n,stopSequences:[`
595
- ${t}:`]}}function t_({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 r_(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 o7=Ie(()=>Ce(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(ge(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),s7=Ie(()=>Ce(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(ge(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),$d]))),n_=Ie(()=>Ce(C({echo:me().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([me(),j()]).optional()}))),a7=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:f,providerOptions:p}){const h=[],y={...await Jr({provider:"openai",providerOptions:p,schema:n_}),...await Jr({provider:this.providerOptionsName,providerOptions:p,schema:n_})};o!=null&&h.push({type:"unsupported",feature:"topK"}),c?.length&&h.push({type:"unsupported",feature:"tools"}),u!=null&&h.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:g}=n7({prompt:e}),b=[...g??[],...i??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,logprobs:y?.logprobs===!0?0:y?.logprobs===!1?void 0:y?.logprobs,suffix:y.suffix,user:y.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:f,prompt:w,stop:b.length>0?b:void 0},warnings:h}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await Zt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:r,failedResponseHandler:br,successfulResponseHandler:Kt(o7),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:e_(s.usage),finishReason:{unified:r_(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...t_(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 Zt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:n,failedResponseHandler:br,successfulResponseHandler:Fi(s7),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,f){if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...t_(p)}),f.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const h=p.choices[0];h?.finish_reason!=null&&(a={unified:r_(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(i.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:e_(l)})}})),request:{body:n},response:{headers:o}}}},i7=Ie(()=>Ce(C({dimensions:j().optional(),user:d().optional()}))),l7=Ie(()=>Ce(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 G6({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Jr({provider:"openai",providerOptions:n,schema:i7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Zt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:$t(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:br,successfulResponseHandler:Kt(l7),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}}}},o_=Ie(()=>Ce(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()}))),u7={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},d7=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function p7(e){return d7.some(t=>e.startsWith(t))}var f7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=u7[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,f,p,h,y,w,g,b,v,m,T;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 _=(p=(f=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:f.call(u))!=null?p:new Date;if(t!=null){const{value:x,responseHeaders:U}=await tg({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:$t(this.config.headers(),l),formData:r5({model:this.modelId,prompt:e,image:await Promise.all(t.map(M=>M.type==="file"?new Blob([M.data instanceof Uint8Array?new Blob([M.data],{type:M.mediaType}):new Blob([Co(M.data)],{type:M.mediaType})],{type:M.mediaType}):F2(M.url))),mask:r!=null?await h7(r):void 0,n,size:o,...(h=i.openai)!=null?h:{}}),failedResponseHandler:br,successfulResponseHandler:Kt(o_),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(M=>M.b64_json),warnings:k,usage:x.usage!=null?{inputTokens:(y=x.usage.input_tokens)!=null?y:void 0,outputTokens:(w=x.usage.output_tokens)!=null?w:void 0,totalTokens:(g=x.usage.total_tokens)!=null?g:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:U},providerMetadata:{openai:{images:x.data.map(M=>{var O,A,L,Y,J;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(O=x.created)!=null?O:void 0,size:(A=x.size)!=null?A:void 0,quality:(L=x.quality)!=null?L:void 0,background:(Y=x.background)!=null?Y:void 0,outputFormat:(J=x.output_format)!=null?J:void 0}})}}}}const{value:S,responseHeaders:$}=await Zt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:$t(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(b=i.openai)!=null?b:{},...p7(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:br,successfulResponseHandler:Kt(o_),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(x=>x.b64_json),warnings:k,usage:S.usage!=null?{inputTokens:(v=S.usage.input_tokens)!=null?v:void 0,outputTokens:(m=S.usage.output_tokens)!=null?m:void 0,totalTokens:(T=S.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:$},providerMetadata:{openai:{images:S.data.map(x=>{var U,M,O,A,L;return{...x.revised_prompt?{revisedPrompt:x.revised_prompt}:{},created:(U=S.created)!=null?U:void 0,size:(M=S.size)!=null?M:void 0,quality:(O=S.quality)!=null?O:void 0,background:(A=S.background)!=null?A:void 0,outputFormat:(L=S.output_format)!=null?L:void 0}})}}}}};async function h7(e){if(!e)return;if(e.type==="url")return F2(e.url);const t=e.data instanceof Uint8Array?e.data:Co(e.data);return new Blob([t],{type:e.mediaType})}var s_=Ie(()=>Ce(C({callId:d(),operation:tt("type",[C({type:P("create_file"),path:d(),diff:d()}),C({type:P("delete_file"),path:d()}),C({type:P("update_file"),path:d(),diff:d()})])}))),a_=Ie(()=>Ce(C({status:Ee(["completed","failed"]),output:d().optional()}))),m7=_r({id:"openai.apply_patch",inputSchema:s_,outputSchema:a_}),g7=m7,y7=Ie(()=>Ce(C({code:d().nullish(),containerId:d()}))),v7=Ie(()=>Ce(C({outputs:q(tt("type",[C({type:P("logs"),logs:d()}),C({type:P("image"),url:d()})])).nullish()}))),_7=Ie(()=>Ce(C({container:oe([d(),C({fileIds:q(d()).optional()})]).optional()}))),w7=_r({id:"openai.code_interpreter",inputSchema:y7,outputSchema:v7}),b7=(e={})=>w7(e),i_=C({key:d(),type:Ee(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),me(),q(d())])}),l_=C({type:Ee(["and","or"]),filters:q(oe([i_,Wl(()=>l_)]))}),k7=Ie(()=>Ce(C({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:C({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([i_,l_]).optional()}))),T7=Ie(()=>Ce(C({queries:q(d()),results:q(C({attributes:ge(d(),Le()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),C7=_r({id:"openai.file_search",inputSchema:C({}),outputSchema:T7}),S7=Ie(()=>Ce(C({background:Ee(["auto","opaque","transparent"]).optional(),inputFidelity:Ee(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:Ee(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ee(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ee(["auto","low","medium","high"]).optional(),size:Ee(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),I7=Ie(()=>Ce(C({}))),E7=Ie(()=>Ce(C({result:d()}))),x7=_r({id:"openai.image_generation",inputSchema:I7,outputSchema:E7}),$7=(e={})=>x7(e),c_=Ie(()=>Ce(C({action:C({type:P("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:ge(d(),d()).optional()})}))),u_=Ie(()=>Ce(C({output:d()}))),R7=_r({id:"openai.local_shell",inputSchema:c_,outputSchema:u_}),d_=Ie(()=>Ce(C({action:C({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),p_=Ie(()=>Ce(C({output:q(C({stdout:d(),stderr:d(),outcome:tt("type",[C({type:P("timeout")}),C({type:P("exit"),exitCode:j()})])}))}))),P7=_r({id:"openai.shell",inputSchema:d_,outputSchema:p_}),M7=Ie(()=>Ce(C({externalWebAccess:me().optional(),filters:C({allowedDomains:q(d()).optional()}).optional(),searchContextSize:Ee(["low","medium","high"]).optional(),userLocation:C({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),O7=Ie(()=>Ce(C({}))),A7=Ie(()=>Ce(C({action:tt("type",[C({type:P("search"),query:d().optional()}),C({type:P("openPage"),url:d().nullish()}),C({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]),sources:q(tt("type",[C({type:P("url"),url:d()}),C({type:P("api"),name:d()})])).optional()}))),N7=_r({id:"openai.web_search",inputSchema:O7,outputSchema:A7}),q7=(e={})=>N7(e),L7=Ie(()=>Ce(C({searchContextSize:Ee(["low","medium","high"]).optional(),userLocation:C({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),j7=Ie(()=>Ce(C({}))),D7=Ie(()=>Ce(C({action:tt("type",[C({type:P("search"),query:d().optional()}),C({type:P("openPage"),url:d().nullish()}),C({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})])}))),U7=_r({id:"openai.web_search_preview",inputSchema:j7,outputSchema:D7}),Pd=Wl(()=>oe([d(),j(),me(),ui(),q(Pd),ge(d(),Pd)])),z7=Ie(()=>Ce(C({serverLabel:d(),allowedTools:oe([q(d()),C({readOnly:me().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ge(d(),d()).optional(),requireApproval:oe([Ee(["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."))),Z7=Ie(()=>Ce(C({}))),F7=Ie(()=>Ce(C({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),Pd]).optional()}))),V7=_r({id:"openai.mcp",inputSchema:Z7,outputSchema:F7}),H7=e=>V7(e),B7={applyPatch:g7,codeInterpreter:b7,fileSearch:C7,imageGeneration:$7,localShell:R7,shell:P7,webSearchPreview:U7,webSearch:q7,mcp:H7};function f_(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 h_(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function J7({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,f,p,h,y,w,g,b,v,m,T,k,_;const S=[],$=[],x=new Set;for(const{role:U,content:M}of e)switch(U){case"system":{switch(r){case"system":{S.push({role:"system",content:M});break}case"developer":{S.push({role:"developer",content:M});break}case"remove":{$.push({type:"other",message:"system messages are removed for this model"});break}default:{const O=r;throw new Error(`Unsupported system message mode: ${O}`)}}break}case"user":{S.push({role:"user",content:M.map((O,A)=>{var L,Y,J;switch(O.type){case"text":return{type:"input_text",text:O.text};case"file":if(O.mediaType.startsWith("image/")){const de=O.mediaType==="image/*"?"image/jpeg":O.mediaType;return{type:"input_image",...O.data instanceof URL?{image_url:O.data.toString()}:typeof O.data=="string"&&h_(O.data,o)?{file_id:O.data}:{image_url:`data:${de};base64,${Io(O.data)}`},detail:(Y=(L=O.providerOptions)==null?void 0:L[n])==null?void 0:Y.imageDetail}}else{if(O.mediaType==="application/pdf")return O.data instanceof URL?{type:"input_file",file_url:O.data.toString()}:{type:"input_file",...typeof O.data=="string"&&h_(O.data,o)?{file_id:O.data}:{filename:(J=O.filename)!=null?J:`part-${A}.pdf`,file_data:`data:application/pdf;base64,${Io(O.data)}`}};throw new xr({functionality:`file part media type ${O.mediaType}`})}}})});break}case"assistant":{const O={};for(const A of M)switch(A.type){case"text":{const L=(f=(u=A.providerOptions)==null?void 0:u[n])==null?void 0:f.itemId;if(a&&L!=null)break;if(s&&L!=null){S.push({type:"item_reference",id:L});break}S.push({role:"assistant",content:[{type:"output_text",text:A.text}],id:L});break}case"tool-call":{const L=(g=(h=(p=A.providerOptions)==null?void 0:p[n])==null?void 0:h.itemId)!=null?g:(w=(y=A.providerMetadata)==null?void 0:y[n])==null?void 0:w.itemId;if(a&&L!=null)break;if(A.providerExecuted){s&&L!=null&&S.push({type:"item_reference",id:L});break}if(s&&L!=null){S.push({type:"item_reference",id:L});break}const Y=t.toProviderToolName(A.toolName);if(i&&Y==="local_shell"){const J=await qt({value:A.input,schema:c_});S.push({type:"local_shell_call",call_id:A.toolCallId,id:L,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&&Y==="shell"){const J=await qt({value:A.input,schema:d_});S.push({type:"shell_call",call_id:A.toolCallId,id:L,status:"completed",action:{commands:J.action.commands,timeout_ms:J.action.timeoutMs,max_output_length:J.action.maxOutputLength}});break}if(c&&Y==="apply_patch"){const J=await qt({value:A.input,schema:s_});S.push({type:"apply_patch_call",call_id:J.callId,id:L,status:"completed",operation:J.operation});break}S.push({type:"function_call",call_id:A.toolCallId,name:Y,arguments:JSON.stringify(A.input),id:L});break}case"tool-result":{if(A.output.type==="execution-denied"||A.output.type==="json"&&typeof A.output.value=="object"&&A.output.value!=null&&"type"in A.output.value&&A.output.value.type==="execution-denied"||a)break;if(s){const L=(m=(v=(b=A.providerMetadata)==null?void 0:b[n])==null?void 0:v.itemId)!=null?m:A.toolCallId;S.push({type:"item_reference",id:L})}else $.push({type:"other",message:`Results for OpenAI tool ${A.toolName} are not sent to the API when store is false`});break}case"reasoning":{const L=await Jr({provider:n,providerOptions:A.providerOptions,schema:W7}),Y=L?.itemId;if(a&&Y!=null)break;if(Y!=null){const J=O[Y];if(s)J===void 0&&(S.push({type:"item_reference",id:Y}),O[Y]={type:"reasoning",id:Y,summary:[]});else{const de=[];A.text.length>0?de.push({type:"summary_text",text:A.text}):J!==void 0&&$.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(A)}.`}),J===void 0?(O[Y]={type:"reasoning",id:Y,encrypted_content:L?.reasoningEncryptedContent,summary:de},S.push(O[Y])):(J.summary.push(...de),L?.reasoningEncryptedContent!=null&&(J.encrypted_content=L.reasoningEncryptedContent))}}else $.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(A)}.`});break}}break}case"tool":{for(const O of M){if(O.type==="tool-approval-response"){const J=O;if(x.has(J.approvalId))continue;x.add(J.approvalId),s&&S.push({type:"item_reference",id:J.approvalId}),S.push({type:"mcp_approval_response",approval_request_id:J.approvalId,approve:J.approved});continue}const A=O.output;if(A.type==="execution-denied"&&((k=(T=A.providerOptions)==null?void 0:T.openai)==null?void 0:k.approvalId))continue;const L=t.toProviderToolName(O.toolName);if(i&&L==="local_shell"&&A.type==="json"){const J=await qt({value:A.value,schema:u_});S.push({type:"local_shell_call_output",call_id:O.toolCallId,output:J.output});continue}if(l&&L==="shell"&&A.type==="json"){const J=await qt({value:A.value,schema:p_});S.push({type:"shell_call_output",call_id:O.toolCallId,output:J.output.map(de=>({stdout:de.stdout,stderr:de.stderr,outcome:de.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:de.outcome.exitCode}}))});continue}if(c&&O.toolName==="apply_patch"&&A.type==="json"){const J=await qt({value:A.value,schema:a_});S.push({type:"apply_patch_call_output",call_id:O.toolCallId,status:J.status,output:J.output});continue}let Y;switch(A.type){case"text":case"error-text":Y=A.value;break;case"execution-denied":Y=(_=A.reason)!=null?_:"Tool execution denied.";break;case"json":case"error-json":Y=JSON.stringify(A.value);break;case"content":Y=A.value.map(J=>{var de;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:(de=J.filename)!=null?de:"data",file_data:`data:${J.mediaType};base64,${J.data}`};default:{$.push({type:"other",message:`unsupported tool content part type: ${J.type}`});return}}}).filter(c5);break}S.push({type:"function_call_output",call_id:O.toolCallId,output:Y})}break}default:{const O=U;throw new Error(`Unsupported role: ${O}`)}}return{input:S,warnings:$}}var W7=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 G7=Ie(()=>Ce(oe([C({type:P("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:Ee(["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:P("response.created"),response:C({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),C({type:P("response.output_item.added"),output_index:j(),item:tt("type",[C({type:P("message"),id:d()}),C({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:P("web_search_call"),id:d(),status:d()}),C({type:P("computer_call"),id:d(),status:d()}),C({type:P("file_search_call"),id:d()}),C({type:P("image_generation_call"),id:d()}),C({type:P("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(tt("type",[C({type:P("logs"),logs:d()}),C({type:P("image"),url:d()})])).nullable(),status:d()}),C({type:P("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),C({type:P("mcp_list_tools"),id:d()}),C({type:P("mcp_approval_request"),id:d()}),C({type:P("apply_patch_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed"]),operation:tt("type",[C({type:P("create_file"),path:d(),diff:d()}),C({type:P("delete_file"),path:d()}),C({type:P("update_file"),path:d(),diff:d()})])}),C({type:P("shell_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed","incomplete"]),action:C({commands:q(d())})})])}),C({type:P("response.output_item.done"),output_index:j(),item:tt("type",[C({type:P("message"),id:d()}),C({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:P("completed")}),C({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(tt("type",[C({type:P("logs"),logs:d()}),C({type:P("image"),url:d()})])).nullable()}),C({type:P("image_generation_call"),id:d(),result:d()}),C({type:P("web_search_call"),id:d(),status:d(),action:tt("type",[C({type:P("search"),query:d().nullish(),sources:q(tt("type",[C({type:P("url"),url:d()}),C({type:P("api"),name:d()})])).nullish()}),C({type:P("open_page"),url:d().nullish()}),C({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:P("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ge(d(),oe([d(),j(),me()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:P("local_shell_call"),id:d(),call_id:d(),action:C({type:P("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),C({type:P("computer_call"),id:d(),status:P("completed")}),C({type:P("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:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:mt(),annotations:ge(d(),Le()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:P("apply_patch_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed"]),operation:tt("type",[C({type:P("create_file"),path:d(),diff:d()}),C({type:P("delete_file"),path:d()}),C({type:P("update_file"),path:d(),diff:d()})])}),C({type:P("shell_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed","incomplete"]),action:C({commands:q(d())})})])}),C({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),C({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),C({type:P("response.output_text.annotation.added"),annotation:tt("type",[C({type:P("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:P("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:P("file_path"),file_id:d(),index:j()})])}),C({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),C({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),C({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),C({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),C({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),C({type:P("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}))]))),K7=Ie(()=>Ce(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(tt("type",[C({type:P("message"),role:P("assistant"),id:d(),content:q(C({type:P("output_text"),text:d(),logprobs:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish(),annotations:q(tt("type",[C({type:P("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:P("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:P("file_path"),file_id:d(),index:j()})]))}))}),C({type:P("web_search_call"),id:d(),status:d(),action:tt("type",[C({type:P("search"),query:d().nullish(),sources:q(tt("type",[C({type:P("url"),url:d()}),C({type:P("api"),name:d()})])).nullish()}),C({type:P("open_page"),url:d().nullish()}),C({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:P("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ge(d(),oe([d(),j(),me()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(tt("type",[C({type:P("logs"),logs:d()}),C({type:P("image"),url:d()})])).nullable()}),C({type:P("image_generation_call"),id:d(),result:d()}),C({type:P("local_shell_call"),id:d(),call_id:d(),action:C({type:P("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),C({type:P("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:P("computer_call"),id:d(),status:d().optional()}),C({type:P("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(C({type:P("summary_text"),text:d()}))}),C({type:P("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:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:mt(),annotations:ge(d(),Le()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:P("apply_patch_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed"]),operation:tt("type",[C({type:P("create_file"),path:d(),diff:d()}),C({type:P("delete_file"),path:d()}),C({type:P("update_file"),path:d(),diff:d()})])}),C({type:P("shell_call"),id:d(),call_id:d(),status:Ee(["in_progress","completed","incomplete"]),action:C({commands:q(d())})})])).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()}))),g_=20,y_=Ie(()=>Ce(C({conversation:d().nullish(),include:q(Ee(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([me(),j().min(1).max(g_)]).optional(),maxToolCalls:j().nullish(),metadata:mt().nullish(),parallelToolCalls:me().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:Ee(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:Ee(["auto","flex","priority","default"]).nullish(),store:me().nullish(),strictJsonSchema:me().nullish(),textVerbosity:Ee(["low","medium","high"]).nullish(),truncation:Ee(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:Ee(["system","developer","remove"]).optional(),forceReasoning:me().optional()})));async function Y7({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 qt({value:s.args,schema:k7});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":{n.push({type:"shell"});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await qt({value:s.args,schema:L7});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await qt({value:s.args,schema:M7});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 qt({value:s.args,schema:_7});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 qt({value:s.args,schema:S7});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 qt({value:s.args,schema:z7}),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 xr({functionality:`tool choice type: ${s}`})}}}function v_(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 Q7=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:f,responseFormat:p}){var h,y,w,g,b,v;const m=[],T=Yv(this.modelId);o!=null&&m.push({type:"unsupported",feature:"topK"}),i!=null&&m.push({type:"unsupported",feature:"seed"}),s!=null&&m.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&m.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&m.push({type:"unsupported",feature:"stopSequences"});const k=this.config.provider.includes("azure")?"azure":"openai";let _=await Jr({provider:k,providerOptions:c,schema:y_});_==null&&k!=="openai"&&(_=await Jr({provider:"openai",providerOptions:c,schema:y_}));const S=(h=_?.forceReasoning)!=null?h:T.isReasoningModel;_?.conversation&&_?.previousResponseId&&m.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const $=Q6({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:x,warnings:U}=await J7({prompt:l,toolNameMapping:$,systemMessageMode:(y=_?.systemMessageMode)!=null?y:S?"developer":T.systemMessageMode,providerOptionsName:k,fileIdPrefixes:this.config.fileIdPrefixes,store:(w=_?.store)!=null?w:!0,hasConversation:_?.conversation!=null,hasLocalShellTool:L("openai.local_shell"),hasShellTool:L("openai.shell"),hasApplyPatchTool:L("openai.apply_patch")});m.push(...U);const M=(g=_?.strictJsonSchema)!=null?g:!0;let O=_?.include;function A(H){O==null?O=[H]:O.includes(H)||(O=[...O,H])}function L(H){return u?.find(z=>z.type==="provider"&&z.id===H)!=null}const Y=typeof _?.logprobs=="number"?_?.logprobs:_?.logprobs===!0?g_:void 0;Y&&A("message.output_text.logprobs");const J=(b=u?.find(H=>H.type==="provider"&&(H.id==="openai.web_search"||H.id==="openai.web_search_preview")))==null?void 0:b.name;J&&A("web_search_call.action.sources"),L("openai.code_interpreter")&&A("code_interpreter_call.outputs");const de=_?.store;de===!1&&S&&A("reasoning.encrypted_content");const K={model:this.modelId,input:x,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||_?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:M,name:(v=p.name)!=null?v:"response",description:p.description,schema:p.schema}:{type:"json_object"}},..._?.textVerbosity&&{verbosity:_.textVerbosity}}},conversation:_?.conversation,max_tool_calls:_?.maxToolCalls,metadata:_?.metadata,parallel_tool_calls:_?.parallelToolCalls,previous_response_id:_?.previousResponseId,store:de,user:_?.user,instructions:_?.instructions,service_tier:_?.serviceTier,include:O,prompt_cache_key:_?.promptCacheKey,prompt_cache_retention:_?.promptCacheRetention,safety_identifier:_?.safetyIdentifier,top_logprobs:Y,truncation:_?.truncation,...S&&(_?.reasoningEffort!=null||_?.reasoningSummary!=null)&&{reasoning:{..._?.reasoningEffort!=null&&{effort:_.reasoningEffort},..._?.reasoningSummary!=null&&{summary:_.reasoningSummary}}}};S?_?.reasoningEffort==="none"&&T.supportsNonReasoningParameters||(K.temperature!=null&&(K.temperature=void 0,m.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),K.top_p!=null&&(K.top_p=void 0,m.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(_?.reasoningEffort!=null&&m.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),_?.reasoningSummary!=null&&m.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),_?.serviceTier==="flex"&&!T.supportsFlexProcessing&&(m.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete K.service_tier),_?.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(m.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 K.service_tier);const{tools:$e,toolChoice:Z,toolWarnings:N}=await Y7({tools:u,toolChoice:f});return{webSearchToolName:J,args:{...K,tools:$e,tool_choice:Z},warnings:[...m,...N],store:de,toolNameMapping:$,providerOptionsName:k}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,y,w,g,b,v,m,T,k,_,S,$,x;const{args:U,warnings:M,webSearchToolName:O,toolNameMapping:A,providerOptionsName:L}=await this.getArgs(e),Y=this.config.url({path:"/responses",modelId:this.modelId}),J=v_(e.prompt),{responseHeaders:de,value:K,rawValue:$e}=await Zt({url:Y,headers:$t(this.config.headers(),e.headers),body:U,failedResponseHandler:br,successfulResponseHandler:Kt(K7),abortSignal:e.abortSignal,fetch:this.config.fetch});if(K.error)throw new ht({message:K.error.message,url:Y,requestBodyValues:U,statusCode:400,responseHeaders:de,responseBody:$e,isRetryable:!1});const Z=[],N=[];let H=!1;for(const E of K.output)switch(E.type){case"reasoning":{E.summary.length===0&&E.summary.push({type:"summary_text",text:""});for(const V of E.summary)Z.push({type:"reasoning",text:V.text,providerMetadata:{[L]:{itemId:E.id,reasoningEncryptedContent:(t=E.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{Z.push({type:"tool-call",toolCallId:E.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),Z.push({type:"tool-result",toolCallId:E.id,toolName:A.toCustomToolName("image_generation"),result:{result:E.result}});break}case"local_shell_call":{Z.push({type:"tool-call",toolCallId:E.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:E.action}),providerMetadata:{[L]:{itemId:E.id}}});break}case"shell_call":{Z.push({type:"tool-call",toolCallId:E.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:E.action.commands}}),providerMetadata:{[L]:{itemId:E.id}}});break}case"message":{for(const V of E.content){(n=(r=e.providerOptions)==null?void 0:r[L])!=null&&n.logprobs&&V.logprobs&&N.push(V.logprobs);const te={itemId:E.id,...V.annotations.length>0&&{annotations:V.annotations}};Z.push({type:"text",text:V.text,providerMetadata:{[L]:te}});for(const Q of V.annotations)Q.type==="url_citation"?Z.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:At(),url:Q.url,title:Q.title}):Q.type==="file_citation"?Z.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:At(),mediaType:"text/plain",title:Q.filename,filename:Q.filename,providerMetadata:{[L]:{type:Q.type,fileId:Q.file_id,index:Q.index}}}):Q.type==="container_file_citation"?Z.push({type:"source",sourceType:"document",id:(p=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?p:At(),mediaType:"text/plain",title:Q.filename,filename:Q.filename,providerMetadata:{[L]:{type:Q.type,fileId:Q.file_id,containerId:Q.container_id}}}):Q.type==="file_path"&&Z.push({type:"source",sourceType:"document",id:(w=(y=(h=this.config).generateId)==null?void 0:y.call(h))!=null?w:At(),mediaType:"application/octet-stream",title:Q.file_id,filename:Q.file_id,providerMetadata:{[L]:{type:Q.type,fileId:Q.file_id,index:Q.index}}})}break}case"function_call":{H=!0,Z.push({type:"tool-call",toolCallId:E.call_id,toolName:E.name,input:E.arguments,providerMetadata:{[L]:{itemId:E.id}}});break}case"web_search_call":{Z.push({type:"tool-call",toolCallId:E.id,toolName:A.toCustomToolName(O??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),Z.push({type:"tool-result",toolCallId:E.id,toolName:A.toCustomToolName(O??"web_search"),result:w_(E.action)});break}case"mcp_call":{const V=E.approval_request_id!=null&&(g=J[E.approval_request_id])!=null?g:E.id,te=`mcp.${E.name}`;Z.push({type:"tool-call",toolCallId:V,toolName:te,input:E.arguments,providerExecuted:!0,dynamic:!0}),Z.push({type:"tool-result",toolCallId:V,toolName:te,result:{type:"call",serverLabel:E.server_label,name:E.name,arguments:E.arguments,...E.output!=null?{output:E.output}:{},...E.error!=null?{error:E.error}:{}},providerMetadata:{[L]:{itemId:E.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const V=(b=E.approval_request_id)!=null?b:E.id,te=(T=(m=(v=this.config).generateId)==null?void 0:m.call(v))!=null?T:At(),Q=`mcp.${E.name}`;Z.push({type:"tool-call",toolCallId:te,toolName:Q,input:E.arguments,providerExecuted:!0,dynamic:!0}),Z.push({type:"tool-approval-request",approvalId:V,toolCallId:te});break}case"computer_call":{Z.push({type:"tool-call",toolCallId:E.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Z.push({type:"tool-result",toolCallId:E.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:E.status||"completed"}});break}case"file_search_call":{Z.push({type:"tool-call",toolCallId:E.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),Z.push({type:"tool-result",toolCallId:E.id,toolName:A.toCustomToolName("file_search"),result:{queries:E.queries,results:(_=(k=E.results)==null?void 0:k.map(V=>({attributes:V.attributes,fileId:V.file_id,filename:V.filename,score:V.score,text:V.text})))!=null?_:null}});break}case"code_interpreter_call":{Z.push({type:"tool-call",toolCallId:E.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:E.code,containerId:E.container_id}),providerExecuted:!0}),Z.push({type:"tool-result",toolCallId:E.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:E.outputs}});break}case"apply_patch_call":{Z.push({type:"tool-call",toolCallId:E.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:E.call_id,operation:E.operation}),providerMetadata:{[L]:{itemId:E.id}}});break}}const z={[L]:{responseId:K.id,...N.length>0?{logprobs:N}:{},...typeof K.service_tier=="string"?{serviceTier:K.service_tier}:{}}},I=K.usage;return{content:Z,finishReason:{unified:m_({finishReason:(S=K.incomplete_details)==null?void 0:S.reason,hasFunctionCall:H}),raw:(x=($=K.incomplete_details)==null?void 0:$.reason)!=null?x:void 0},usage:f_(I),request:{body:U},response:{id:K.id,timestamp:new Date(K.created_at*1e3),modelId:K.model,headers:de,body:$e},providerMetadata:z,warnings:M}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a}=await this.getArgs(e),{responseHeaders:i,value:l}=await Zt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:br,successfulResponseHandler:Fi(G7),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=this,u=v_(e.prompt),f=new Map;let p={unified:"other",raw:void 0},h;const y=[];let w=null;const g={},b=[];let v=!1;const m={};let T;return{stream:l.pipeThrough(new TransformStream({start(k){k.enqueue({type:"stream-start",warnings:r})},transform(k,_){var S,$,x,U,M,O,A,L,Y,J,de,K,$e,Z,N,H,z,I,E,V,te,Q,_e,xe,D,F,G,ee,pe,ke;if(e.includeRawChunks&&_.enqueue({type:"raw",rawValue:k.rawValue}),!k.success){p={unified:"error",raw:void 0},_.enqueue({type:"error",error:k.error});return}const R=k.value;if(__(R)){if(R.item.type==="function_call")g[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},_.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:R.item.name});else if(R.item.type==="web_search_call")g[R.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:R.item.id},_.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),_.enqueue({type:"tool-input-end",id:R.item.id}),_.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(R.item.type==="computer_call")g[R.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:R.item.id},_.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(R.item.type==="code_interpreter_call")g[R.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:R.item.id,codeInterpreter:{containerId:R.item.container_id}},_.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),_.enqueue({type:"tool-input-delta",id:R.item.id,delta:`{"containerId":"${R.item.container_id}","code":"`});else if(R.item.type==="file_search_call")_.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(R.item.type==="image_generation_call")_.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(R.item.type==="mcp_call"||R.item.type==="mcp_list_tools"||R.item.type==="mcp_approval_request"))if(R.item.type==="apply_patch_call"){const{call_id:re,operation:ve}=R.item;if(g[R.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:re,applyPatch:{hasDiff:ve.type==="delete_file",endEmitted:ve.type==="delete_file"}},_.enqueue({type:"tool-input-start",id:re,toolName:o.toCustomToolName("apply_patch")}),ve.type==="delete_file"){const Te=JSON.stringify({callId:re,operation:ve});_.enqueue({type:"tool-input-delta",id:re,delta:Te}),_.enqueue({type:"tool-input-end",id:re})}else _.enqueue({type:"tool-input-delta",id:re,delta:`{"callId":"${Wn(re)}","operation":{"type":"${Wn(ve.type)}","path":"${Wn(ve.path)}","diff":"`})}else R.item.type==="shell_call"?g[R.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:R.item.call_id}:R.item.type==="message"?(b.splice(0,b.length),_.enqueue({type:"text-start",id:R.item.id,providerMetadata:{[a]:{itemId:R.item.id}}})):__(R)&&R.item.type==="reasoning"&&(m[R.item.id]={encryptedContent:R.item.encrypted_content,summaryParts:{0:"active"}},_.enqueue({type:"reasoning-start",id:`${R.item.id}:0`,providerMetadata:{[a]:{itemId:R.item.id,reasoningEncryptedContent:(S=R.item.encrypted_content)!=null?S:null}}}))}else if(eR(R)){if(R.item.type==="message")_.enqueue({type:"text-end",id:R.item.id,providerMetadata:{[a]:{itemId:R.item.id,...b.length>0&&{annotations:b}}}});else if(R.item.type==="function_call")g[R.output_index]=void 0,v=!0,_.enqueue({type:"tool-input-end",id:R.item.call_id}),_.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:R.item.name,input:R.item.arguments,providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="web_search_call")g[R.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName(n??"web_search"),result:w_(R.item.action)});else if(R.item.type==="computer_call")g[R.output_index]=void 0,_.enqueue({type:"tool-input-end",id:R.item.id}),_.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),_.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:R.item.status||"completed"}});else if(R.item.type==="file_search_call")g[R.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:R.item.queries,results:(x=($=R.item.results)==null?void 0:$.map(re=>({attributes:re.attributes,fileId:re.file_id,filename:re.filename,score:re.score,text:re.text})))!=null?x:null}});else if(R.item.type==="code_interpreter_call")g[R.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:R.item.outputs}});else if(R.item.type==="image_generation_call")_.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:R.item.result}});else if(R.item.type==="mcp_call"){g[R.output_index]=void 0;const re=(U=R.item.approval_request_id)!=null?U:void 0,ve=re!=null&&(O=(M=f.get(re))!=null?M:u[re])!=null?O:R.item.id,Te=`mcp.${R.item.name}`;_.enqueue({type:"tool-call",toolCallId:ve,toolName:Te,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),_.enqueue({type:"tool-result",toolCallId:ve,toolName:Te,result:{type:"call",serverLabel:R.item.server_label,name:R.item.name,arguments:R.item.arguments,...R.item.output!=null?{output:R.item.output}:{},...R.item.error!=null?{error:R.item.error}:{}},providerMetadata:{[a]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_list_tools")g[R.output_index]=void 0;else if(R.item.type==="apply_patch_call"){const re=g[R.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&R.item.operation.type!=="delete_file"&&(re.applyPatch.hasDiff||_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Wn(R.item.operation.diff)}),_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),_.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0),re&&R.item.status==="completed"&&_.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:R.item.call_id,operation:R.item.operation}),providerMetadata:{[a]:{itemId:R.item.id}}}),g[R.output_index]=void 0}else if(R.item.type==="mcp_approval_request"){g[R.output_index]=void 0;const re=(Y=(L=(A=c.config).generateId)==null?void 0:L.call(A))!=null?Y:At(),ve=(J=R.item.approval_request_id)!=null?J:R.item.id;f.set(ve,re);const Te=`mcp.${R.item.name}`;_.enqueue({type:"tool-call",toolCallId:re,toolName:Te,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),_.enqueue({type:"tool-approval-request",approvalId:ve,toolCallId:re})}else if(R.item.type==="local_shell_call")g[R.output_index]=void 0,_.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:R.item.action.command,timeoutMs:R.item.action.timeout_ms,user:R.item.action.user,workingDirectory:R.item.action.working_directory,env:R.item.action.env}}),providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="shell_call")g[R.output_index]=void 0,_.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:R.item.action.commands}}),providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="reasoning"){const re=m[R.item.id],ve=Object.entries(re.summaryParts).filter(([Te,Re])=>Re==="active"||Re==="can-conclude").map(([Te])=>Te);for(const Te of ve)_.enqueue({type:"reasoning-end",id:`${R.item.id}:${Te}`,providerMetadata:{[a]:{itemId:R.item.id,reasoningEncryptedContent:(de=R.item.encrypted_content)!=null?de:null}}});delete m[R.item.id]}}else if(nR(R)){const re=g[R.output_index];re!=null&&_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:R.delta})}else if(iR(R)){const re=g[R.output_index];re?.applyPatch&&(_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Wn(R.delta)}),re.applyPatch.hasDiff=!0)}else if(lR(R)){const re=g[R.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&(re.applyPatch.hasDiff||(_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Wn(R.diff)}),re.applyPatch.hasDiff=!0),_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),_.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0)}else if(oR(R))_.enqueue({type:"tool-result",toolCallId:R.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:R.partial_image_b64},preliminary:!0});else if(sR(R)){const re=g[R.output_index];re!=null&&_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Wn(R.delta)})}else if(aR(R)){const re=g[R.output_index];re!=null&&(_.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}'}),_.enqueue({type:"tool-input-end",id:re.toolCallId}),_.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:R.code,containerId:re.codeInterpreter.containerId}),providerExecuted:!0}))}else if(rR(R))w=R.response.id,_.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model});else if(X7(R))_.enqueue({type:"text-delta",id:R.item_id,delta:R.delta}),($e=(K=e.providerOptions)==null?void 0:K[a])!=null&&$e.logprobs&&R.logprobs&&y.push(R.logprobs);else if(R.type==="response.reasoning_summary_part.added"){if(R.summary_index>0){const re=m[R.item_id];re.summaryParts[R.summary_index]="active";for(const ve of Object.keys(re.summaryParts))re.summaryParts[ve]==="can-conclude"&&(_.enqueue({type:"reasoning-end",id:`${R.item_id}:${ve}`,providerMetadata:{[a]:{itemId:R.item_id}}}),re.summaryParts[ve]="concluded");_.enqueue({type:"reasoning-start",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[a]:{itemId:R.item_id,reasoningEncryptedContent:(N=(Z=m[R.item_id])==null?void 0:Z.encryptedContent)!=null?N:null}}})}}else R.type==="response.reasoning_summary_text.delta"?_.enqueue({type:"reasoning-delta",id:`${R.item_id}:${R.summary_index}`,delta:R.delta,providerMetadata:{[a]:{itemId:R.item_id}}}):R.type==="response.reasoning_summary_part.done"?s?(_.enqueue({type:"reasoning-end",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[a]:{itemId:R.item_id}}}),m[R.item_id].summaryParts[R.summary_index]="concluded"):m[R.item_id].summaryParts[R.summary_index]="can-conclude":tR(R)?(p={unified:m_({finishReason:(H=R.response.incomplete_details)==null?void 0:H.reason,hasFunctionCall:v}),raw:(I=(z=R.response.incomplete_details)==null?void 0:z.reason)!=null?I:void 0},h=R.response.usage,typeof R.response.service_tier=="string"&&(T=R.response.service_tier)):cR(R)?(b.push(R.annotation),R.annotation.type==="url_citation"?_.enqueue({type:"source",sourceType:"url",id:(te=(V=(E=c.config).generateId)==null?void 0:V.call(E))!=null?te:At(),url:R.annotation.url,title:R.annotation.title}):R.annotation.type==="file_citation"?_.enqueue({type:"source",sourceType:"document",id:(xe=(_e=(Q=c.config).generateId)==null?void 0:_e.call(Q))!=null?xe:At(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}}):R.annotation.type==="container_file_citation"?_.enqueue({type:"source",sourceType:"document",id:(G=(F=(D=c.config).generateId)==null?void 0:F.call(D))!=null?G:At(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,containerId:R.annotation.container_id}}}):R.annotation.type==="file_path"&&_.enqueue({type:"source",sourceType:"document",id:(ke=(pe=(ee=c.config).generateId)==null?void 0:pe.call(ee))!=null?ke:At(),mediaType:"application/octet-stream",title:R.annotation.file_id,filename:R.annotation.file_id,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}})):uR(R)&&_.enqueue({type:"error",error:R})},flush(k){const _={[a]:{responseId:w,...y.length>0?{logprobs:y}:{},...T!==void 0?{serviceTier:T}:{}}};k.enqueue({type:"finish",finishReason:p,usage:f_(h),providerMetadata:_})}})),request:{body:t},response:{headers:i}}}};function X7(e){return e.type==="response.output_text.delta"}function eR(e){return e.type==="response.output_item.done"}function tR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function rR(e){return e.type==="response.created"}function nR(e){return e.type==="response.function_call_arguments.delta"}function oR(e){return e.type==="response.image_generation_call.partial_image"}function sR(e){return e.type==="response.code_interpreter_call_code.delta"}function aR(e){return e.type==="response.code_interpreter_call_code.done"}function iR(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function lR(e){return e.type==="response.apply_patch_call_operation_diff.done"}function __(e){return e.type==="response.output_item.added"}function cR(e){return e.type==="response.output_text.annotation.added"}function uR(e){return e.type==="error"}function w_(e){var t;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 Wn(e){return JSON.stringify(e).slice(1,-1)}var dR=Ie(()=>Ce(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 Jr({provider:"openai",providerOptions:a,schema:dR}),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 f in u){const p=u[f];p!==void 0&&(c[f]=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 Zt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),body:s,failedResponseHandler:br,successfulResponseHandler:uI(),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}}}},fR=Ie(()=>Ce(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()}))),hR=Ie(()=>Ce(C({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(Ee(["word","segment"])).default(["segment"]).optional()}))),b_={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"},mR=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 Jr({provider:"openai",providerOptions:r,schema:hR}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Co(e)]);s.append("model",this.modelId);const i=p5(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 f of u)s.append(`${c}[]`,String(f));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:f}=await this.getArgs(e),{value:p,responseHeaders:h,rawValue:y}=await tg({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:$t(this.config.headers(),e.headers),formData:u,failedResponseHandler:br,successfulResponseHandler:Kt(fR),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=p.language!=null&&p.language in b_?b_[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(g=>({text:g.text,startSecond:g.start,endSecond:g.end})))!=null?a:(s=p.words)==null?void 0:s.map(g=>({text:g.word,startSecond:g.start,endSecond:g.end})))!=null?i:[],language:w,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:h,body:y}}}},gR="3.0.28";function k_(e={}){var t,r;const n=(t=og(Os({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>gn({Authorization:`Bearer ${d5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${gR}`),a=w=>new r7(w,{provider:`${o}.chat`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),i=w=>new a7(w,{provider:`${o}.completion`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),l=w=>new c7(w,{provider:`${o}.embedding`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),c=w=>new f7(w,{provider:`${o}.image`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),u=w=>new mR(w,{provider:`${o}.transcription`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),f=w=>new pR(w,{provider:`${o}.speech`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),p=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(w)},h=w=>new Q7(w,{provider:`${o}.responses`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),y=function(w){return p(w)};return y.specificationVersion="v3",y.languageModel=p,y.chat=a,y.completion=i,y.responses=h,y.embedding=l,y.embeddingModel=l,y.textEmbedding=l,y.textEmbeddingModel=l,y.image=c,y.imageModel=c,y.transcription=u,y.transcriptionModel=u,y.speech=f,y.speechModel=f,y.tools=B7,y}k_();var T_="vercel.ai.error",yR=Symbol.for(T_),C_,vR=class I1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[C_]=!0,this.name=t,this.cause=n}static isInstance(t){return I1.hasMarker(t,T_)}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}};C_=yR;var yt=vR,S_="AI_APICallError",I_=`vercel.ai.error.${S_}`,_R=Symbol.for(I_),E_,Kr=class extends yt{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:S_,message:e,cause:a}),this[E_]=!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 yt.hasMarker(e,I_)}};E_=_R;var x_="AI_EmptyResponseBodyError",$_=`vercel.ai.error.${x_}`,wR=Symbol.for($_),R_,bR=class extends yt{constructor({message:e="Empty response body"}={}){super({name:x_,message:e}),this[R_]=!0}static isInstance(e){return yt.hasMarker(e,$_)}};R_=wR;function P_(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var M_="AI_InvalidArgumentError",O_=`vercel.ai.error.${M_}`,kR=Symbol.for(O_),A_,N_=class extends yt{constructor({message:e,cause:t,argument:r}){super({name:M_,message:e,cause:t}),this[A_]=!0,this.argument=r}static isInstance(e){return yt.hasMarker(e,O_)}};A_=kR;var q_="AI_InvalidResponseDataError",L_=`vercel.ai.error.${q_}`,TR=Symbol.for(L_),j_,D_=class extends yt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:q_,message:t}),this[j_]=!0,this.data=e}static isInstance(e){return yt.hasMarker(e,L_)}};j_=TR;var U_="AI_JSONParseError",z_=`vercel.ai.error.${U_}`,CR=Symbol.for(z_),Z_,al=class extends yt{constructor({text:e,cause:t}){super({name:U_,message:`JSON parsing failed: Text: ${e}.
596
- Error message: ${P_(t)}`,cause:t}),this[Z_]=!0,this.text=e}static isInstance(e){return yt.hasMarker(e,z_)}};Z_=CR;var F_="AI_LoadAPIKeyError",V_=`vercel.ai.error.${F_}`,SR=Symbol.for(V_),H_,il=class extends yt{constructor({message:e}){super({name:F_,message:e}),this[H_]=!0}static isInstance(e){return yt.hasMarker(e,V_)}};H_=SR;var B_="AI_NoSuchModelError",J_=`vercel.ai.error.${B_}`,IR=Symbol.for(J_),W_,G_=class extends yt{constructor({errorName:e=B_,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[W_]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return yt.hasMarker(e,J_)}};W_=IR;var K_="AI_TypeValidationError",Y_=`vercel.ai.error.${K_}`,ER=Symbol.for(Y_),Q_,xR=class Yd extends yt{constructor({value:t,cause:r}){super({name:K_,message:`Type validation failed: Value: ${JSON.stringify(t)}.
597
- Error message: ${P_(r)}`,cause:r}),this[Q_]=!0,this.value=t}static isInstance(t){return yt.hasMarker(t,Y_)}static wrap({value:t,cause:r}){return Yd.isInstance(r)&&r.value===t?r:new Yd({value:t,cause:r})}};Q_=ER;var Gs=xR,X_="AI_UnsupportedFunctionalityError",e1=`vercel.ai.error.${X_}`,$R=Symbol.for(e1),t1,r1=class extends yt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:X_,message:t}),this[t1]=!0,this.functionality=e}static isInstance(e){return yt.hasMarker(e,e1)}};t1=$R;function n1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function ll(e){return Object.fromEntries([...e.headers])}var RR=({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 N_({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},cl=RR();function Md(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var PR=["fetch failed","failed to fetch"];function MR({error:e,url:t,requestBodyValues:r}){if(Md(e))return e;if(e instanceof TypeError&&PR.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Kr({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function OR(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 AR(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 o1(e,...t){const r=new Headers(AR(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var NR="3.0.18";function qR({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new il({message:`${n} API key must be a string.`});if(typeof process>"u")throw new il({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 il({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new il({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var LR=/"__proto__"\s*:/,jR=/"constructor"\s*:/;function s1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||LR.test(e)===!1&&jR.test(e)===!1?t:DR(t)}function DR(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 Od(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return s1(e)}try{return s1(e)}finally{Error.stackTraceLimit=t}}var Ad=Symbol.for("vercel.ai.validator");function UR(e){return{[Ad]:!0,validate:e}}function zR(e){return typeof e=="object"&&e!==null&&Ad in e&&e[Ad]===!0&&"validate"in e}function ZR(e){return zR(e)?e:typeof e=="function"?e():FR(e)}function FR(e){return UR(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Gs({value:t,cause:r.issues})}})}async function VR({value:e,schema:t}){const r=await Ks({value:e,schema:t});if(!r.success)throw Gs.wrap({value:e,cause:r.error});return r.value}async function Ks({value:e,schema:t}){const r=ZR(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:Gs.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Gs.wrap({value:e,cause:n}),rawValue:e}}}async function HR({text:e,schema:t}){try{const r=Od(e);return t==null?r:VR({value:r,schema:t})}catch(r){throw al.isInstance(r)||Gs.isInstance(r)?r:new al({text:e,cause:r})}}async function a1({text:e,schema:t}){try{const r=Od(e);return t==null?{success:!0,value:r,rawValue:r}:await Ks({value:r,schema:t})}catch(r){return{success:!1,error:al.isInstance(r)?r:new al({text:e,cause:r}),rawValue:void 0}}}function i1(e){try{return Od(e),!0}catch{return!1}}function BR({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await a1({text:r,schema:t}))}}))}async function l1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ks({value:t[e],schema:r});if(!n.success)throw new N_({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var JR=()=>globalThis.fetch,c1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>WR({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),WR=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=JR()})=>{try{const i=await a(e,{method:"POST",headers:o1(t,`ai-sdk/provider-utils/${NR}`,OR()),body:r.content,signal:s}),l=ll(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Md(u)||Kr.isInstance(u)?u:new Kr({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&&(Md(c)||Kr.isInstance(c))?c:new Kr({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw MR({error:i,url:e,requestBodyValues:r.values})}},GR=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=ll(n);if(a.trim()==="")return{responseHeaders:i,value:new Kr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await HR({text:a,schema:e});return{responseHeaders:i,value:new Kr({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 Kr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},KR=e=>async({response:t})=>{const r=ll(t);if(t.body==null)throw new bR({});return{responseHeaders:r,value:BR({stream:t.body,schema:e})}},YR=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await a1({text:o,schema:e}),a=ll(t);if(!s.success)throw new Kr({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:QR}=globalThis;function XR(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return QR(t)}function eP(e){return e instanceof Uint8Array?XR(e):e}function tP(e){return e?.replace(/\/$/,"")}function Ys(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function rP(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Ys({...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,...Ys(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Ys(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,${eP(a.data)}`},...i}}else throw new r1({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Ys(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=Ys(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 u1({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 d1(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 Nd=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),nP=C({error:C({message:d(),type:d().nullish(),param:mt().nullish(),code:oe([d(),j()]).nullish()})}),oP={errorSchema:nP,errorToMessage:e=>e.error.message};function sP({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 r1({functionality:`tool choice type: ${s}`})}}}var aP=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:oP;this.chunkSchema=lP(o.errorSchema),this.failedResponseHandler=GR(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:f,tools:p}){var h,y,w,g;const b=[],v=Object.assign((h=await l1({provider:"openai-compatible",providerOptions:i,schema:Nd}))!=null?h:{},(y=await l1({provider:this.providerOptionsName,providerOptions:i,schema:Nd}))!=null?y:{});o!=null&&b.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&b.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:m,toolChoice:T,toolWarnings:k}=sP({tools:p,toolChoice:f});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:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((g=i?.[this.providerOptionsName])!=null?g:{}).filter(([_])=>!Object.keys(Nd.shape).includes(_))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:rP(e),tools:m,tool_choice:T},warnings:[...b,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,y,w,g,b;const{args:v,warnings:m}=await this.getArgs({...e}),T=JSON.stringify(v),{responseHeaders:k,value:_,rawValue:S}=await c1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:n1(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:YR(iP),abortSignal:e.abortSignal,fetch:this.config.fetch}),$=_.choices[0],x=[],U=$.message.content;U!=null&&U.length>0&&x.push({type:"text",text:U});const M=(t=$.message.reasoning_content)!=null?t:$.message.reasoning;if(M!=null&&M.length>0&&x.push({type:"reasoning",text:M}),$.message.tool_calls!=null)for(const L of $.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=L.id)!=null?r:cl(),toolName:L.function.name,input:L.function.arguments});const O={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=_.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(O[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(O[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:x,finishReason:d1($.finish_reason),usage:{inputTokens:(i=(a=_.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=_.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=_.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(y=(h=(p=_.usage)==null?void 0:p.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(b=(g=(w=_.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?b:void 0},providerMetadata:O,request:{body:T},response:{...u1(_),headers:k,body:S},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 c1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:n1(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:KR(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 f=!0;const p=this.providerOptionsName;let h=!1,y=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,g){var b,v,m,T,k,_,S,$,x,U,M,O,A;if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",g.enqueue({type:"error",error:w.error});return}const L=w.value;if(s?.processChunk(w.rawValue),"error"in L){c="error",g.enqueue({type:"error",error:L.error.message});return}if(f&&(f=!1,g.enqueue({type:"response-metadata",...u1(L)})),L.usage!=null){const{prompt_tokens:K,completion_tokens:$e,total_tokens:Z,prompt_tokens_details:N,completion_tokens_details:H}=L.usage;u.promptTokens=K??void 0,u.completionTokens=$e??void 0,u.totalTokens=Z??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),N?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=N?.cached_tokens)}const Y=L.choices[0];if(Y?.finish_reason!=null&&(c=d1(Y.finish_reason)),Y?.delta==null)return;const J=Y.delta,de=(b=J.reasoning_content)!=null?b:J.reasoning;if(de&&(h||(g.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),g.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),J.content&&(y||(g.enqueue({type:"text-start",id:"txt-0"}),y=!0),g.enqueue({type:"text-delta",id:"txt-0",delta:J.content})),J.tool_calls!=null)for(const K of J.tool_calls){const $e=K.index;if(l[$e]==null){if(K.id==null)throw new D_({data:K,message:"Expected 'id' to be a string."});if(((v=K.function)==null?void 0:v.name)==null)throw new D_({data:K,message:"Expected 'function.name' to be a string."});g.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),l[$e]={id:K.id,type:"function",function:{name:K.function.name,arguments:(m=K.function.arguments)!=null?m:""},hasFinished:!1};const N=l[$e];((T=N.function)==null?void 0:T.name)!=null&&((k=N.function)==null?void 0:k.arguments)!=null&&(N.function.arguments.length>0&&g.enqueue({type:"tool-input-delta",id:N.id,delta:N.function.arguments}),i1(N.function.arguments)&&(g.enqueue({type:"tool-input-end",id:N.id}),g.enqueue({type:"tool-call",toolCallId:(_=N.id)!=null?_:cl(),toolName:N.function.name,input:N.function.arguments}),N.hasFinished=!0));continue}const Z=l[$e];Z.hasFinished||(((S=K.function)==null?void 0:S.arguments)!=null&&(Z.function.arguments+=(x=($=K.function)==null?void 0:$.arguments)!=null?x:""),g.enqueue({type:"tool-input-delta",id:Z.id,delta:(U=K.function.arguments)!=null?U:""}),((M=Z.function)==null?void 0:M.name)!=null&&((O=Z.function)==null?void 0:O.arguments)!=null&&i1(Z.function.arguments)&&(g.enqueue({type:"tool-input-end",id:Z.id}),g.enqueue({type:"tool-call",toolCallId:(A=Z.id)!=null?A:cl(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}},flush(w){var g,b,v,m,T,k;h&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),y&&w.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter($=>!$.hasFinished))w.enqueue({type:"tool-input-end",id:S.id}),w.enqueue({type:"tool-call",toolCallId:(g=S.id)!=null?g:cl(),toolName:S.function.name,input:S.function.arguments});const _={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(_[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(_[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(b=u.promptTokens)!=null?b:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(m=u.totalTokens)!=null?m:void 0,reasoningTokens:(T=u.completionTokensDetails.reasoningTokens)!=null?T:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:_})}})),request:{body:o},response:{headers:a}}}},p1=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:P("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:p1}),lP=e=>oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:Ee(["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:p1}),e]);C({echo:me().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var cP=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:cP.nullish()}),C({dimensions:j().optional(),user:d().optional()}),C({data:q(C({embedding:q(j())})),usage:C({prompt_tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),mt())).optional()}),C({data:q(C({b64_json:d()}))});var f1=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}}},uP={extractMetadata:async({parsedBody:e})=>{const t=await Ks({value:e,schema:dP});return!t.success||t.value.usage==null?void 0:f1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ks({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:()=>f1(e)}}},h1=C({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),dP=C({usage:h1.nullish()}),pP=C({choices:q(C({finish_reason:d().nullish()})).nullish(),usage:h1.nullish()}),fP="1.0.30";function m1(e={}){var t;const r=tP((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>o1({Authorization:`Bearer ${qR({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${fP}`);class o extends aP{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:uP}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new G_({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new G_({modelId:i,modelType:"imageModel"})},a}m1();const g1=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]=ng({description:o,inputSchema:Eo({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function hP(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
595
+ ${t}:`]}}function w_({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 b_(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 w7=Ce(()=>Te(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ye(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),b7=Ce(()=>Te(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:j(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ye(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Jd]))),k_=Ce(()=>Te(T({echo:he().optional(),logitBias:ye(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([he(),j()]).optional()}))),k7=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 nn({provider:"openai",providerOptions:p,schema:k_}),...await nn({provider:this.providerOptionsName,providerOptions:p,schema:k_})};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}=_7({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 Wt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:r,failedResponseHandler:Rr,successfulResponseHandler:dr(w7),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:__(s.usage),finishReason:{unified:b_(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...w_(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 Wt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:rl(b7),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",...w_(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:b_(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:__(l)})}})),request:{body:n},response:{headers:o}}}},T7=Ce(()=>Te(T({dimensions:j().optional(),user:d().optional()}))),C7=Ce(()=>Te(T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish()}))),S7=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 h5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await nn({provider:"openai",providerOptions:n,schema:T7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Wt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:At(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Rr,successfulResponseHandler:dr(C7),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}}}},T_=Ce(()=>Te(T({created:j().nullish(),data:q(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:T({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),I7={"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},x7=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function E7(e){return x7.some(t=>e.startsWith(t))}var $7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=I7[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,C;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 b=(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 _g({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:At(this.config.headers(),l),formData:b5({model:this.modelId,prompt:e,image:await Promise.all(t.map($=>$.type==="file"?new Blob([$.data instanceof Uint8Array?new Blob([$.data],{type:$.mediaType}):new Blob([Mo($.data)],{type:$.mediaType})],{type:$.mediaType}):ag($.url))),mask:r!=null?await R7(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:Rr,successfulResponseHandler:dr(T_),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map($=>$.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:b,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:I.data.map(($,N)=>{var A,U,V,Q,_e,te;return{...$.revised_prompt?{revisedPrompt:$.revised_prompt}:{},created:(A=I.created)!=null?A:void 0,size:(U=I.size)!=null?U:void 0,quality:(V=I.quality)!=null?V:void 0,background:(Q=I.background)!=null?Q:void 0,outputFormat:(_e=I.output_format)!=null?_e:void 0,...C_((te=I.usage)==null?void 0:te.input_tokens_details,N,I.data.length)}})}}}}const{value:S,responseHeaders:x}=await Wt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:At(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:Rr,successfulResponseHandler:dr(T_),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(I=>I.b64_json),warnings:k,usage:S.usage!=null?{inputTokens:(v=S.usage.input_tokens)!=null?v:void 0,outputTokens:(m=S.usage.output_tokens)!=null?m:void 0,totalTokens:(C=S.usage.total_tokens)!=null?C:void 0}:void 0,response:{timestamp:b,modelId:this.modelId,headers:x},providerMetadata:{openai:{images:S.data.map((I,L)=>{var $,N,A,U,V,Q;return{...I.revised_prompt?{revisedPrompt:I.revised_prompt}:{},created:($=S.created)!=null?$:void 0,size:(N=S.size)!=null?N:void 0,quality:(A=S.quality)!=null?A:void 0,background:(U=S.background)!=null?U:void 0,outputFormat:(V=S.output_format)!=null?V:void 0,...C_((Q=S.usage)==null?void 0:Q.input_tokens_details,L,S.data.length)}})}}}}};function C_(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 R7(e){if(!e)return;if(e.type==="url")return ag(e.url);const t=e.data instanceof Uint8Array?e.data:Mo(e.data);return new Blob([t],{type:e.mediaType})}var S_=Ce(()=>Te(T({callId:d(),operation:ze("type",[T({type:R("create_file"),path:d(),diff:d()}),T({type:R("delete_file"),path:d()}),T({type:R("update_file"),path:d(),diff:d()})])}))),I_=Ce(()=>Te(T({status:me(["completed","failed"]),output:d().optional()}))),P7=xr({id:"openai.apply_patch",inputSchema:S_,outputSchema:I_}),M7=P7,O7=Ce(()=>Te(T({code:d().nullish(),containerId:d()}))),N7=Ce(()=>Te(T({outputs:q(ze("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullish()}))),A7=Ce(()=>Te(T({container:oe([d(),T({fileIds:q(d()).optional()})]).optional()}))),q7=xr({id:"openai.code_interpreter",inputSchema:O7,outputSchema:N7}),L7=(e={})=>q7(e),x_=T({key:d(),type:me(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),he(),q(d())])}),E_=T({type:me(["and","or"]),filters:q(oe([x_,pc(()=>E_)]))}),j7=Ce(()=>Te(T({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:T({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([x_,E_]).optional()}))),D7=Ce(()=>Te(T({queries:q(d()),results:q(T({attributes:ye(d(),Me()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),U7=xr({id:"openai.file_search",inputSchema:T({}),outputSchema:D7}),z7=Ce(()=>Te(T({background:me(["auto","opaque","transparent"]).optional(),inputFidelity:me(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:me(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:me(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:me(["auto","low","medium","high"]).optional(),size:me(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Z7=Ce(()=>Te(T({}))),F7=Ce(()=>Te(T({result:d()}))),V7=xr({id:"openai.image_generation",inputSchema:Z7,outputSchema:F7}),H7=(e={})=>V7(e),$_=Ce(()=>Te(T({action:T({type:R("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:ye(d(),d()).optional()})}))),R_=Ce(()=>Te(T({output:d()}))),B7=xr({id:"openai.local_shell",inputSchema:$_,outputSchema:R_}),P_=Ce(()=>Te(T({action:T({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),Gd=Ce(()=>Te(T({output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exitCode:j()})])}))}))),J7=q(ze("type",[T({type:R("skillReference"),skillId:d(),version:d().optional()}),T({type:R("inline"),name:d(),description:d(),source:T({type:R("base64"),mediaType:R("application/zip"),data:d()})})])).optional(),W7=Ce(()=>Te(T({environment:oe([T({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:me(["1g","4g","16g","64g"]).optional(),networkPolicy:ze("type",[T({type:R("disabled")}),T({type:R("allowlist"),allowedDomains:q(d()),domainSecrets:q(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:J7}),T({type:R("containerReference"),containerId:d()}),T({type:R("local").optional(),skills:q(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),G7=xr({id:"openai.shell",inputSchema:P_,outputSchema:Gd}),K7=Ce(()=>Te(T({externalWebAccess:he().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:me(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Y7=Ce(()=>Te(T({}))),Q7=Ce(()=>Te(T({action:ze("type",[T({type:R("search"),query:d().optional()}),T({type:R("openPage"),url:d().nullish()}),T({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(ze("type",[T({type:R("url"),url:d()}),T({type:R("api"),name:d()})])).optional()}))),X7=xr({id:"openai.web_search",inputSchema:Y7,outputSchema:Q7}),eR=(e={})=>X7(e),tR=Ce(()=>Te(T({searchContextSize:me(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),rR=Ce(()=>Te(T({}))),nR=Ce(()=>Te(T({action:ze("type",[T({type:R("search"),query:d().optional()}),T({type:R("openPage"),url:d().nullish()}),T({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),oR=xr({id:"openai.web_search_preview",inputSchema:rR,outputSchema:nR}),Kd=pc(()=>oe([d(),j(),he(),Ti(),q(Kd),ye(d(),Kd)])),sR=Ce(()=>Te(T({serverLabel:d(),allowedTools:oe([q(d()),T({readOnly:he().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ye(d(),d()).optional(),requireApproval:oe([me(["always","never"]),T({never:T({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."))),aR=Ce(()=>Te(T({}))),iR=Ce(()=>Te(T({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),Kd]).optional()}))),lR=xr({id:"openai.mcp",inputSchema:aR,outputSchema:iR}),cR=e=>lR(e),uR={applyPatch:M7,codeInterpreter:L7,fileSearch:U7,imageGeneration:H7,localShell:B7,shell:G7,webSearchPreview:oR,webSearch:eR,mcp:cR};function M_(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 O_(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function dR({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,C,k;const b=[],S=[],x=new Set;for(const{role:I,content:L}of e)switch(I){case"system":{switch(r){case"system":{b.push({role:"system",content:L});break}case"developer":{b.push({role:"developer",content:L});break}case"remove":{S.push({type:"other",message:"system messages are removed for this model"});break}default:{const $=r;throw new Error(`Unsupported system message mode: ${$}`)}}break}case"user":{b.push({role:"user",content:L.map(($,N)=>{var A,U,V;switch($.type){case"text":return{type:"input_text",text:$.text};case"file":if($.mediaType.startsWith("image/")){const Q=$.mediaType==="image/*"?"image/jpeg":$.mediaType;return{type:"input_image",...$.data instanceof URL?{image_url:$.data.toString()}:typeof $.data=="string"&&O_($.data,o)?{file_id:$.data}:{image_url:`data:${Q};base64,${No($.data)}`},detail:(U=(A=$.providerOptions)==null?void 0:A[n])==null?void 0:U.imageDetail}}else{if($.mediaType==="application/pdf")return $.data instanceof URL?{type:"input_file",file_url:$.data.toString()}:{type:"input_file",...typeof $.data=="string"&&O_($.data,o)?{file_id:$.data}:{filename:(V=$.filename)!=null?V:`part-${N}.pdf`,file_data:`data:application/pdf;base64,${No($.data)}`}};throw new jr({functionality:`file part media type ${$.mediaType}`})}}})});break}case"assistant":{const $={};for(const N of L)switch(N.type){case"text":{const A=(u=N.providerOptions)==null?void 0:u[n],U=A?.itemId,V=A?.phase;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,...V!=null&&{phase:V}});break}case"tool-call":{const A=(_=(p=(h=N.providerOptions)==null?void 0:h[n])==null?void 0:p.itemId)!=null?_:(g=(f=N.providerMetadata)==null?void 0:f[n])==null?void 0:g.itemId;if(a&&A!=null)break;if(N.providerExecuted){s&&A!=null&&b.push({type:"item_reference",id:A});break}if(s&&A!=null){b.push({type:"item_reference",id:A});break}const U=t.toProviderToolName(N.toolName);if(i&&U==="local_shell"){const V=await Mt({value:N.input,schema:$_});b.push({type:"local_shell_call",call_id:N.toolCallId,id:A,action:{type:"exec",command:V.action.command,timeout_ms:V.action.timeoutMs,user:V.action.user,working_directory:V.action.workingDirectory,env:V.action.env}});break}if(l&&U==="shell"){const V=await Mt({value:N.input,schema:P_});b.push({type:"shell_call",call_id:N.toolCallId,id:A,status:"completed",action:{commands:V.action.commands,timeout_ms:V.action.timeoutMs,max_output_length:V.action.maxOutputLength}});break}if(c&&U==="apply_patch"){const V=await Mt({value:N.input,schema:S_});b.push({type:"apply_patch_call",call_id:V.callId,id:A,status:"completed",operation:V.operation});break}b.push({type:"function_call",call_id:N.toolCallId,name:U,arguments:JSON.stringify(N.input),id:A});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 A=t.toProviderToolName(N.toolName);if(l&&A==="shell"){if(N.output.type==="json"){const U=await Mt({value:N.output.value,schema:Gd});b.push({type:"shell_call_output",call_id:N.toolCallId,output:U.output.map(V=>({stdout:V.stdout,stderr:V.stderr,outcome:V.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:V.outcome.exitCode}}))})}break}if(s){const U=(v=(w=(y=N.providerOptions)==null?void 0:y[n])==null?void 0:w.itemId)!=null?v:N.toolCallId;b.push({type:"item_reference",id:U})}else S.push({type:"other",message:`Results for OpenAI tool ${N.toolName} are not sent to the API when store is false`});break}case"reasoning":{const A=await nn({provider:n,providerOptions:N.providerOptions,schema:pR}),U=A?.itemId;if(a&&U!=null)break;if(U!=null){const V=$[U];if(s)V===void 0&&(b.push({type:"item_reference",id:U}),$[U]={type:"reasoning",id:U,summary:[]});else{const Q=[];N.text.length>0?Q.push({type:"summary_text",text:N.text}):V!==void 0&&S.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(N)}.`}),V===void 0?($[U]={type:"reasoning",id:U,encrypted_content:A?.reasoningEncryptedContent,summary:Q},b.push($[U])):(V.summary.push(...Q),A?.reasoningEncryptedContent!=null&&(V.encrypted_content=A.reasoningEncryptedContent))}}else{const V=A?.reasoningEncryptedContent;if(V!=null){const Q=[];N.text.length>0&&Q.push({type:"summary_text",text:N.text}),b.push({type:"reasoning",encrypted_content:V,summary:Q})}else S.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(N)}.`})}break}}break}case"tool":{for(const $ of L){if($.type==="tool-approval-response"){const V=$;if(x.has(V.approvalId))continue;x.add(V.approvalId),s&&b.push({type:"item_reference",id:V.approvalId}),b.push({type:"mcp_approval_response",approval_request_id:V.approvalId,approve:V.approved});continue}const N=$.output;if(N.type==="execution-denied"&&((C=(m=N.providerOptions)==null?void 0:m.openai)==null?void 0:C.approvalId))continue;const A=t.toProviderToolName($.toolName);if(i&&A==="local_shell"&&N.type==="json"){const V=await Mt({value:N.value,schema:R_});b.push({type:"local_shell_call_output",call_id:$.toolCallId,output:V.output});continue}if(l&&A==="shell"&&N.type==="json"){const V=await Mt({value:N.value,schema:Gd});b.push({type:"shell_call_output",call_id:$.toolCallId,output:V.output.map(Q=>({stdout:Q.stdout,stderr:Q.stderr,outcome:Q.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Q.outcome.exitCode}}))});continue}if(c&&$.toolName==="apply_patch"&&N.type==="json"){const V=await Mt({value:N.value,schema:I_});b.push({type:"apply_patch_call_output",call_id:$.toolCallId,status:V.status,output:V.output});continue}let U;switch(N.type){case"text":case"error-text":U=N.value;break;case"execution-denied":U=(k=N.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(N.value);break;case"content":U=N.value.map(V=>{var Q;switch(V.type){case"text":return{type:"input_text",text:V.text};case"image-data":return{type:"input_image",image_url:`data:${V.mediaType};base64,${V.data}`};case"image-url":return{type:"input_image",image_url:V.url};case"file-data":return{type:"input_file",filename:(Q=V.filename)!=null?Q:"data",file_data:`data:${V.mediaType};base64,${V.data}`};default:{S.push({type:"other",message:`unsupported tool content part type: ${V.type}`});return}}}).filter(E5);break}b.push({type:"function_call_output",call_id:$.toolCallId,output:U})}break}default:{const $=I;throw new Error(`Unsupported role: ${$}`)}}return{input:b,warnings:S}}var pR=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function N_({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 fR=Ce(()=>Te(oe([T({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}),T({type:me(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:R("response.created"),response:T({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),T({type:R("response.output_item.added"),output_index:j(),item:ze("type",[T({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),T({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),T({type:R("web_search_call"),id:d(),status:d()}),T({type:R("computer_call"),id:d(),status:d()}),T({type:R("file_search_call"),id:d()}),T({type:R("image_generation_call"),id:d()}),T({type:R("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(ze("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullable(),status:d()}),T({type:R("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:R("mcp_list_tools"),id:d()}),T({type:R("mcp_approval_request"),id:d()}),T({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:ze("type",[T({type:R("create_file"),path:d(),diff:d()}),T({type:R("delete_file"),path:d()}),T({type:R("update_file"),path:d(),diff:d()})])}),T({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:j()})])}))})])}),T({type:R("response.output_item.done"),output_index:j(),item:ze("type",[T({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),T({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:R("completed")}),T({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(ze("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullable()}),T({type:R("image_generation_call"),id:d(),result:d()}),T({type:R("web_search_call"),id:d(),status:d(),action:ze("type",[T({type:R("search"),query:d().nullish(),sources:q(ze("type",[T({type:R("url"),url:d()}),T({type:R("api"),name:d()})])).nullish()}),T({type:R("open_page"),url:d().nullish()}),T({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:R("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:ye(d(),oe([d(),j(),he()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:R("local_shell_call"),id:d(),call_id:d(),action:T({type:R("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),T({type:R("computer_call"),id:d(),status:R("completed")}),T({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:kt(),annotations:ye(d(),Me()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:ze("type",[T({type:R("create_file"),path:d(),diff:d()}),T({type:R("delete_file"),path:d()}),T({type:R("update_file"),path:d(),diff:d()})])}),T({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:j()})])}))})])}),T({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),T({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),T({type:R("response.output_text.annotation.added"),annotation:ze("type",[T({type:R("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:R("file_path"),file_id:d(),index:j()})])}),T({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),T({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),T({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),T({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),T({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),T({type:R("error"),sequence_number:j(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),hR=Ce(()=>Te(T({id:d().optional(),created_at:j().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(ze("type",[T({type:R("message"),role:R("assistant"),id:d(),phase:me(["commentary","final_answer"]).nullish(),content:q(T({type:R("output_text"),text:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish(),annotations:q(ze("type",[T({type:R("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:R("file_path"),file_id:d(),index:j()})]))}))}),T({type:R("web_search_call"),id:d(),status:d(),action:ze("type",[T({type:R("search"),query:d().nullish(),sources:q(ze("type",[T({type:R("url"),url:d()}),T({type:R("api"),name:d()})])).nullish()}),T({type:R("open_page"),url:d().nullish()}),T({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:R("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:ye(d(),oe([d(),j(),he()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(ze("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullable()}),T({type:R("image_generation_call"),id:d(),result:d()}),T({type:R("local_shell_call"),id:d(),call_id:d(),action:T({type:R("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),T({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:R("computer_call"),id:d(),status:d().optional()}),T({type:R("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(T({type:R("summary_text"),text:d()}))}),T({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:kt(),annotations:ye(d(),Me()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:ze("type",[T({type:R("create_file"),path:d(),diff:d()}),T({type:R("delete_file"),path:d()}),T({type:R("update_file"),path:d(),diff:d()})])}),T({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:j()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),A_=20,q_=Ce(()=>Te(T({conversation:d().nullish(),include:q(me(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([he(),j().min(1).max(A_)]).optional(),maxToolCalls:j().nullish(),metadata:kt().nullish(),parallelToolCalls:he().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:me(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:me(["auto","flex","priority","default"]).nullish(),store:he().nullish(),strictJsonSchema:he().nullish(),textVerbosity:me(["low","medium","high"]).nullish(),truncation:me(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));async function mR({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 Mt({value:s.args,schema:j7});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 Mt({value:s.args,schema:W7});n.push({type:"shell",...a.environment&&{environment:gR(a.environment)}});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await Mt({value:s.args,schema:tR});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await Mt({value:s.args,schema:K7});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 Mt({value:s.args,schema:A7});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 Mt({value:s.args,schema:z7});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 Mt({value:s.args,schema:sR}),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 jr({functionality:`tool choice type: ${s}`})}}}function gR(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:yR(r.skills)}}return{type:"local",skills:e.skills}}function yR(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 L_(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 vR=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,C,k;const b=[],S=g_(this.modelId);o!=null&&b.push({type:"unsupported",feature:"topK"}),i!=null&&b.push({type:"unsupported",feature:"seed"}),s!=null&&b.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&b.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&b.push({type:"unsupported",feature:"stopSequences"});const x=this.config.provider.includes("azure")?"azure":"openai";let I=await nn({provider:x,providerOptions:c,schema:q_});I==null&&x!=="openai"&&(I=await nn({provider:"openai",providerOptions:c,schema:q_}));const L=(f=I?.forceReasoning)!=null?f:S.isReasoningModel;I?.conversation&&I?.previousResponseId&&b.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const $=y5({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:N,warnings:A}=await dR({prompt:l,toolNameMapping:$,systemMessageMode:(g=I?.systemMessageMode)!=null?g:L?"developer":S.systemMessageMode,providerOptionsName:x,fileIdPrefixes:this.config.fileIdPrefixes,store:(_=I?.store)!=null?_:!0,hasConversation:I?.conversation!=null,hasLocalShellTool:_e("openai.local_shell"),hasShellTool:_e("openai.shell"),hasApplyPatchTool:_e("openai.apply_patch")});b.push(...A);const U=(y=I?.strictJsonSchema)!=null?y:!0;let V=I?.include;function Q(G){V==null?V=[G]:V.includes(G)||(V=[...V,G])}function _e(G){return u?.find(re=>re.type==="provider"&&re.id===G)!=null}const te=typeof I?.logprobs=="number"?I?.logprobs:I?.logprobs===!0?A_:void 0;te&&Q("message.output_text.logprobs");const ge=(w=u?.find(G=>G.type==="provider"&&(G.id==="openai.web_search"||G.id==="openai.web_search_preview")))==null?void 0:w.name;ge&&Q("web_search_call.action.sources"),_e("openai.code_interpreter")&&Q("code_interpreter_call.outputs");const H=I?.store;H===!1&&L&&Q("reasoning.encrypted_content");const M={model:this.modelId,input:N,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:H,user:I?.user,instructions:I?.instructions,service_tier:I?.serviceTier,include:V,prompt_cache_key:I?.promptCacheKey,prompt_cache_retention:I?.promptCacheRetention,safety_identifier:I?.safetyIdentifier,top_logprobs:te,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"&&S.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(I?.reasoningEffort!=null&&b.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),I?.reasoningSummary!=null&&b.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),I?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),I?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(b.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 M.service_tier);const{tools:B,toolChoice:Z,toolWarnings:E}=await mR({tools:u,toolChoice:h}),O=(k=(C=(m=u?.find(G=>G.type==="provider"&&G.id==="openai.shell"))==null?void 0:m.args)==null?void 0:C.environment)==null?void 0:k.type,D=O==="containerAuto"||O==="containerReference";return{webSearchToolName:ge,args:{...M,tools:B,tool_choice:Z},warnings:[...b,...E],store:H,toolNameMapping:$,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,C,k,b,S,x,I;const{args:L,warnings:$,webSearchToolName:N,toolNameMapping:A,providerOptionsName:U,isShellProviderExecuted:V}=await this.getArgs(e),Q=this.config.url({path:"/responses",modelId:this.modelId}),_e=L_(e.prompt),{responseHeaders:te,value:ge,rawValue:H}=await Wt({url:Q,headers:At(this.config.headers(),e.headers),body:L,failedResponseHandler:Rr,successfulResponseHandler:dr(hR),abortSignal:e.abortSignal,fetch:this.config.fetch});if(ge.error)throw new ut({message:ge.error.message,url:Q,requestBodyValues:L,statusCode:400,responseHeaders:te,responseBody:H,isRetryable:!1});const M=[],B=[];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 G of D.summary)M.push({type:"reasoning",text:G.text,providerMetadata:{[U]:{itemId:D.id,reasoningEncryptedContent:(t=D.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{M.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("image_generation"),result:{result:D.result}});break}case"local_shell_call":{M.push({type:"tool-call",toolCallId:D.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:D.action}),providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call":{M.push({type:"tool-call",toolCallId:D.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:D.action.commands}}),...V&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call_output":{M.push({type:"tool-result",toolCallId:D.call_id,toolName:A.toCustomToolName("shell"),result:{output:D.output.map(G=>({stdout:G.stdout,stderr:G.stderr,outcome:G.outcome.type==="exit"?{type:"exit",exitCode:G.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const G of D.content){(n=(r=e.providerOptions)==null?void 0:r[U])!=null&&n.logprobs&&G.logprobs&&B.push(G.logprobs);const re={itemId:D.id,...D.phase!=null&&{phase:D.phase},...G.annotations.length>0&&{annotations:G.annotations}};M.push({type:"text",text:G.text,providerMetadata:{[U]:re}});for(const ie of G.annotations)ie.type==="url_citation"?M.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:zt(),url:ie.url,title:ie.title}):ie.type==="file_citation"?M.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:zt(),mediaType:"text/plain",title:ie.filename,filename:ie.filename,providerMetadata:{[U]:{type:ie.type,fileId:ie.file_id,index:ie.index}}}):ie.type==="container_file_citation"?M.push({type:"source",sourceType:"document",id:(p=(h=(u=this.config).generateId)==null?void 0:h.call(u))!=null?p:zt(),mediaType:"text/plain",title:ie.filename,filename:ie.filename,providerMetadata:{[U]:{type:ie.type,fileId:ie.file_id,containerId:ie.container_id}}}):ie.type==="file_path"&&M.push({type:"source",sourceType:"document",id:(_=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?_:zt(),mediaType:"application/octet-stream",title:ie.file_id,filename:ie.file_id,providerMetadata:{[U]:{type:ie.type,fileId:ie.file_id,index:ie.index}}})}break}case"function_call":{Z=!0,M.push({type:"tool-call",toolCallId:D.call_id,toolName:D.name,input:D.arguments,providerMetadata:{[U]:{itemId:D.id}}});break}case"web_search_call":{M.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName(N??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),M.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName(N??"web_search"),result:D_(D.action)});break}case"mcp_call":{const G=D.approval_request_id!=null&&(y=_e[D.approval_request_id])!=null?y:D.id,re=`mcp.${D.name}`;M.push({type:"tool-call",toolCallId:G,toolName:re,input:D.arguments,providerExecuted:!0,dynamic:!0}),M.push({type:"tool-result",toolCallId:G,toolName:re,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 G=(w=D.approval_request_id)!=null?w:D.id,re=(C=(m=(v=this.config).generateId)==null?void 0:m.call(v))!=null?C:zt(),ie=`mcp.${D.name}`;M.push({type:"tool-call",toolCallId:re,toolName:ie,input:D.arguments,providerExecuted:!0,dynamic:!0}),M.push({type:"tool-approval-request",approvalId:G,toolCallId:re});break}case"computer_call":{M.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:D.status||"completed"}});break}case"file_search_call":{M.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("file_search"),result:{queries:D.queries,results:(b=(k=D.results)==null?void 0:k.map(G=>({attributes:G.attributes,fileId:G.file_id,filename:G.filename,score:G.score,text:G.text})))!=null?b:null}});break}case"code_interpreter_call":{M.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:D.code,containerId:D.container_id}),providerExecuted:!0}),M.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:D.outputs}});break}case"apply_patch_call":{M.push({type:"tool-call",toolCallId:D.call_id,toolName:A.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,...B.length>0?{logprobs:B}:{},...typeof ge.service_tier=="string"?{serviceTier:ge.service_tier}:{}}},O=ge.usage;return{content:M,finishReason:{unified:N_({finishReason:(S=ge.incomplete_details)==null?void 0:S.reason,hasFunctionCall:Z}),raw:(I=(x=ge.incomplete_details)==null?void 0:x.reason)!=null?I:void 0},usage:M_(O),request:{body:L},response:{id:ge.id,timestamp:new Date(ge.created_at*1e3),modelId:ge.model,headers:te,body:H},providerMetadata:E,warnings:$}}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 Wt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Rr,successfulResponseHandler:rl(fR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,h=L_(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const _=[];let y=null;const w={},v=[];let m,C=!1;const k={};let b;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,x){var I,L,$,N,A,U,V,Q,_e,te,ge,H,M,B,Z,E,O,D,G,re,ie,Ie,z,F,K,ee,le,we,et,pt,mt,st;if(e.includeRawChunks&&x.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},x.enqueue({type:"error",error:S.error});return}const P=S.value;if(j_(P)){if(P.item.type==="function_call")w[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},x.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},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),x.enqueue({type:"tool-input-end",id:P.item.id}),x.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},x.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}},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),x.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")x.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:ne,operation:Oe}=P.item;if(w[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Oe.type==="delete_file",endEmitted:Oe.type==="delete_file"}},x.enqueue({type:"tool-input-start",id:ne,toolName:o.toCustomToolName("apply_patch")}),Oe.type==="delete_file"){const qe=JSON.stringify({callId:ne,operation:Oe});x.enqueue({type:"tool-input-delta",id:ne,delta:qe}),x.enqueue({type:"tool-input-end",id:ne})}else x.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${oo(ne)}","operation":{"type":"${oo(Oe.type)}","path":"${oo(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),m=(I=P.item.phase)!=null?I:void 0,x.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,...P.item.phase!=null&&{phase:P.item.phase}}}})):j_(P)&&P.item.type==="reasoning"&&(k[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},x.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(L=P.item.encrypted_content)!=null?L:null}}})))}else if(wR(P)){if(P.item.type==="message"){const ne=($=P.item.phase)!=null?$:m;m=void 0,x.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,...ne!=null&&{phase:ne},...v.length>0&&{annotations:v}}}})}else if(P.item.type==="function_call")w[P.output_index]=void 0,C=!0,x.enqueue({type:"tool-input-end",id:P.item.call_id}),x.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,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:D_(P.item.action)});else if(P.item.type==="computer_call")w[P.output_index]=void 0,x.enqueue({type:"tool-input-end",id:P.item.id}),x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.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,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(A=(N=P.item.results)==null?void 0:N.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?A:null}});else if(P.item.type==="code_interpreter_call")w[P.output_index]=void 0,x.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")x.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 ne=(U=P.item.approval_request_id)!=null?U:void 0,Oe=ne!=null&&(Q=(V=p.get(ne))!=null?V:h[ne])!=null?Q:P.item.id,qe=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:Oe,toolName:qe,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-result",toolCallId:Oe,toolName:qe,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 ne=w[P.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:oo(P.item.operation.diff)}),x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&P.item.status==="completed"&&x.enqueue({type:"tool-call",toolCallId:ne.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 ne=(ge=(te=(_e=u.config).generateId)==null?void 0:te.call(_e))!=null?ge:zt(),Oe=(H=P.item.approval_request_id)!=null?H:P.item.id;p.set(Oe,ne);const qe=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:ne,toolName:qe,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-approval-request",approvalId:Oe,toolCallId:ne})}else if(P.item.type==="local_shell_call")w[P.output_index]=void 0,x.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,x.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")x.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(ne=>({stdout:ne.stdout,stderr:ne.stderr,outcome:ne.outcome.type==="exit"?{type:"exit",exitCode:ne.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const ne=k[P.item.id],Oe=Object.entries(ne.summaryParts).filter(([qe,pr])=>pr==="active"||pr==="can-conclude").map(([qe])=>qe);for(const qe of Oe)x.enqueue({type:"reasoning-end",id:`${P.item.id}:${qe}`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(M=P.item.encrypted_content)!=null?M:null}}});delete k[P.item.id]}}else if(TR(P)){const ne=w[P.output_index];ne!=null&&x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:P.delta})}else if(xR(P)){const ne=w[P.output_index];ne?.applyPatch&&(x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:oo(P.delta)}),ne.applyPatch.hasDiff=!0)}else if(ER(P)){const ne=w[P.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:oo(P.diff)}),ne.applyPatch.hasDiff=!0),x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(CR(P))x.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(SR(P)){const ne=w[P.output_index];ne!=null&&x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:oo(P.delta)})}else if(IR(P)){const ne=w[P.output_index];ne!=null&&(x.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),x.enqueue({type:"tool-input-end",id:ne.toolCallId}),x.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(kR(P))y=P.response.id,x.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(_R(P))x.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(Z=(B=e.providerOptions)==null?void 0:B[a])!=null&&Z.logprobs&&P.logprobs&&_.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const ne=k[P.item_id];ne.summaryParts[P.summary_index]="active";for(const Oe of Object.keys(ne.summaryParts))ne.summaryParts[Oe]==="can-conclude"&&(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${Oe}`,providerMetadata:{[a]:{itemId:P.item_id}}}),ne.summaryParts[Oe]="concluded");x.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id,reasoningEncryptedContent:(O=(E=k[P.item_id])==null?void 0:E.encryptedContent)!=null?O:null}}})}}else P.type==="response.reasoning_summary_text.delta"?x.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?(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id}}}),k[P.item_id].summaryParts[P.summary_index]="concluded"):k[P.item_id].summaryParts[P.summary_index]="can-conclude":bR(P)?(f={unified:N_({finishReason:(D=P.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:C}),raw:(re=(G=P.response.incomplete_details)==null?void 0:G.reason)!=null?re:void 0},g=P.response.usage,typeof P.response.service_tier=="string"&&(b=P.response.service_tier)):$R(P)?(v.push(P.annotation),P.annotation.type==="url_citation"?x.enqueue({type:"source",sourceType:"url",id:(z=(Ie=(ie=u.config).generateId)==null?void 0:Ie.call(ie))!=null?z:zt(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?x.enqueue({type:"source",sourceType:"document",id:(ee=(K=(F=u.config).generateId)==null?void 0:K.call(F))!=null?ee:zt(),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"?x.enqueue({type:"source",sourceType:"document",id:(et=(we=(le=u.config).generateId)==null?void 0:we.call(le))!=null?et:zt(),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"&&x.enqueue({type:"source",sourceType:"document",id:(st=(mt=(pt=u.config).generateId)==null?void 0:mt.call(pt))!=null?st:zt(),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}}})):RR(P)&&x.enqueue({type:"error",error:P})},flush(S){const x={[a]:{responseId:y,..._.length>0?{logprobs:_}:{},...b!==void 0?{serviceTier:b}:{}}};S.enqueue({type:"finish",finishReason:f,usage:M_(g),providerMetadata:x})}})),request:{body:t},response:{headers:l}}}};function _R(e){return e.type==="response.output_text.delta"}function wR(e){return e.type==="response.output_item.done"}function bR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function kR(e){return e.type==="response.created"}function TR(e){return e.type==="response.function_call_arguments.delta"}function CR(e){return e.type==="response.image_generation_call.partial_image"}function SR(e){return e.type==="response.code_interpreter_call_code.delta"}function IR(e){return e.type==="response.code_interpreter_call_code.done"}function xR(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 j_(e){return e.type==="response.output_item.added"}function $R(e){return e.type==="response.output_text.annotation.added"}function RR(e){return e.type==="error"}function D_(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 oo(e){return JSON.stringify(e).slice(1,-1)}var PR=Ce(()=>Te(T({instructions:d().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),MR=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 nn({provider:"openai",providerOptions:a,schema:PR}),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 Wt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:s,failedResponseHandler:Rr,successfulResponseHandler:EI(),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}}}},OR=Ce(()=>Te(T({text:d(),language:d().nullish(),duration:j().nullish(),words:q(T({word:d(),start:j(),end:j()})).nullish(),segments:q(T({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()}))),NR=Ce(()=>Te(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(me(["word","segment"])).default(["segment"]).optional()}))),U_={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"},AR=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 nn({provider:"openai",providerOptions:r,schema:NR}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Mo(e)]);s.append("model",this.modelId);const i=P5(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 _g({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),formData:u,failedResponseHandler:Rr,successfulResponseHandler:dr(OR),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=p.language!=null&&p.language in U_?U_[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}}}},qR="3.0.36";function z_(e={}){var t,r;const n=(t=kg(Ao({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>xn({Authorization:`Bearer ${R5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${qR}`),a=_=>new v7(_,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=_=>new k7(_,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=_=>new S7(_,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=_=>new $7(_,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=_=>new AR(_,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),h=_=>new MR(_,{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 vR(_,{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=uR,g}z_();var Z_="vercel.ai.error",LR=Symbol.for(Z_),F_,jR=class H1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[F_]=!0,this.name=t,this.cause=n}static isInstance(t){return H1.hasMarker(t,Z_)}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}};F_=LR;var Ct=jR,V_="AI_APICallError",H_=`vercel.ai.error.${V_}`,DR=Symbol.for(H_),B_,an=class extends Ct{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:V_,message:e,cause:a}),this[B_]=!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 Ct.hasMarker(e,H_)}};B_=DR;var J_="AI_EmptyResponseBodyError",W_=`vercel.ai.error.${J_}`,UR=Symbol.for(W_),G_,zR=class extends Ct{constructor({message:e="Empty response body"}={}){super({name:J_,message:e}),this[G_]=!0}static isInstance(e){return Ct.hasMarker(e,W_)}};G_=UR;function K_(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Y_="AI_InvalidArgumentError",Q_=`vercel.ai.error.${Y_}`,ZR=Symbol.for(Q_),X_,e1=class extends Ct{constructor({message:e,cause:t,argument:r}){super({name:Y_,message:e,cause:t}),this[X_]=!0,this.argument=r}static isInstance(e){return Ct.hasMarker(e,Q_)}};X_=ZR;var t1="AI_InvalidResponseDataError",r1=`vercel.ai.error.${t1}`,FR=Symbol.for(r1),n1,o1=class extends Ct{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:t1,message:t}),this[n1]=!0,this.data=e}static isInstance(e){return Ct.hasMarker(e,r1)}};n1=FR;var s1="AI_JSONParseError",a1=`vercel.ai.error.${s1}`,VR=Symbol.for(a1),i1,wl=class extends Ct{constructor({text:e,cause:t}){super({name:s1,message:`JSON parsing failed: Text: ${e}.
596
+ Error message: ${K_(t)}`,cause:t}),this[i1]=!0,this.text=e}static isInstance(e){return Ct.hasMarker(e,a1)}};i1=VR;var l1="AI_LoadAPIKeyError",c1=`vercel.ai.error.${l1}`,HR=Symbol.for(c1),u1,bl=class extends Ct{constructor({message:e}){super({name:l1,message:e}),this[u1]=!0}static isInstance(e){return Ct.hasMarker(e,c1)}};u1=HR;var d1="AI_NoSuchModelError",p1=`vercel.ai.error.${d1}`,BR=Symbol.for(p1),f1,h1=class extends Ct{constructor({errorName:e=d1,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[f1]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Ct.hasMarker(e,p1)}};f1=BR;var m1="AI_TypeValidationError",g1=`vercel.ai.error.${m1}`,JR=Symbol.for(g1),y1,WR=class hp extends Ct{constructor({value:t,cause:r}){super({name:m1,message:`Type validation failed: Value: ${JSON.stringify(t)}.
597
+ Error message: ${K_(r)}`,cause:r}),this[y1]=!0,this.value=t}static isInstance(t){return Ct.hasMarker(t,g1)}static wrap({value:t,cause:r}){return hp.isInstance(r)&&r.value===t?r:new hp({value:t,cause:r})}};y1=JR;var na=WR,v1="AI_UnsupportedFunctionalityError",_1=`vercel.ai.error.${v1}`,GR=Symbol.for(_1),w1,b1=class extends Ct{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:v1,message:t}),this[w1]=!0,this.functionality=e}static isInstance(e){return Ct.hasMarker(e,_1)}};w1=GR;function k1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function kl(e){return Object.fromEntries([...e.headers])}var KR=({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 e1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Tl=KR();function Yd(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var YR=["fetch failed","failed to fetch"];function QR({error:e,url:t,requestBodyValues:r}){if(Yd(e))return e;if(e instanceof TypeError&&YR.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new an({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function XR(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 eP(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 T1(e,...t){const r=new Headers(eP(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var tP="3.0.18";function rP({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new bl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new bl({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 bl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new bl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var nP=/"__proto__"\s*:/,oP=/"constructor"\s*:/;function C1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||nP.test(e)===!1&&oP.test(e)===!1?t:sP(t)}function sP(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 Qd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return C1(e)}try{return C1(e)}finally{Error.stackTraceLimit=t}}var Xd=Symbol.for("vercel.ai.validator");function aP(e){return{[Xd]:!0,validate:e}}function iP(e){return typeof e=="object"&&e!==null&&Xd in e&&e[Xd]===!0&&"validate"in e}function lP(e){return iP(e)?e:typeof e=="function"?e():cP(e)}function cP(e){return aP(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new na({value:t,cause:r.issues})}})}async function uP({value:e,schema:t}){const r=await oa({value:e,schema:t});if(!r.success)throw na.wrap({value:e,cause:r.error});return r.value}async function oa({value:e,schema:t}){const r=lP(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:na.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:na.wrap({value:e,cause:n}),rawValue:e}}}async function dP({text:e,schema:t}){try{const r=Qd(e);return t==null?r:uP({value:r,schema:t})}catch(r){throw wl.isInstance(r)||na.isInstance(r)?r:new wl({text:e,cause:r})}}async function S1({text:e,schema:t}){try{const r=Qd(e);return t==null?{success:!0,value:r,rawValue:r}:await oa({value:r,schema:t})}catch(r){return{success:!1,error:wl.isInstance(r)?r:new wl({text:e,cause:r}),rawValue:void 0}}}function I1(e){try{return Qd(e),!0}catch{return!1}}function pP({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new xo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await S1({text:r,schema:t}))}}))}async function x1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await oa({value:t[e],schema:r});if(!n.success)throw new e1({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var fP=()=>globalThis.fetch,E1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>hP({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),hP=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=fP()})=>{try{const i=await a(e,{method:"POST",headers:T1(t,`ai-sdk/provider-utils/${tP}`,XR()),body:r.content,signal:s}),l=kl(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Yd(u)||an.isInstance(u)?u:new an({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&&(Yd(c)||an.isInstance(c))?c:new an({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw QR({error:i,url:e,requestBodyValues:r.values})}},mP=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=kl(n);if(a.trim()==="")return{responseHeaders:i,value:new an({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await dP({text:a,schema:e});return{responseHeaders:i,value:new an({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 an({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},gP=e=>async({response:t})=>{const r=kl(t);if(t.body==null)throw new zR({});return{responseHeaders:r,value:pP({stream:t.body,schema:e})}},yP=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await S1({text:o,schema:e}),a=kl(t);if(!s.success)throw new an({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:vP}=globalThis;function _P(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return vP(t)}function wP(e){return e instanceof Uint8Array?_P(e):e}function bP(e){return e?.replace(/\/$/,"")}function sa(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function kP(e){const t=[];for(const{role:r,content:n,...o}of e){const s=sa({...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,...sa(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=sa(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,${wP(a.data)}`},...i}}else throw new b1({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=sa(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=sa(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 $1({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 R1(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 ep=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),TP=T({error:T({message:d(),type:d().nullish(),param:kt().nullish(),code:oe([d(),j()]).nullish()})}),CP={errorSchema:TP,errorToMessage:e=>e.error.message};function SP({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 b1({functionality:`tool choice type: ${s}`})}}}var IP=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:CP;this.chunkSchema=EP(o.errorSchema),this.failedResponseHandler=mP(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 x1({provider:"openai-compatible",providerOptions:i,schema:ep}))!=null?f:{},(g=await x1({provider:this.providerOptionsName,providerOptions:i,schema:ep}))!=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:C,toolWarnings:k}=SP({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(([b])=>!Object.keys(ep.shape).includes(b))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:kP(e),tools:m,tool_choice:C},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}),C=JSON.stringify(v),{responseHeaders:k,value:b,rawValue:S}=await E1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:k1(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:yP(xP),abortSignal:e.abortSignal,fetch:this.config.fetch}),x=b.choices[0],I=[],L=x.message.content;L!=null&&L.length>0&&I.push({type:"text",text:L});const $=(t=x.message.reasoning_content)!=null?t:x.message.reasoning;if($!=null&&$.length>0&&I.push({type:"reasoning",text:$}),x.message.tool_calls!=null)for(const U of x.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:Tl(),toolName:U.function.name,input:U.function.arguments});const N={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=b.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(N[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(N[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:I,finishReason:R1(x.finish_reason),usage:{inputTokens:(i=(a=b.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=b.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=b.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(g=(f=(p=b.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(_=b.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:N,request:{body:C},response:{...$1(b),headers:k,body:S},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 E1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:k1(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:gP(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,C,k,b,S,x,I,L,$,N,A;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",...$1(U)})),U.usage!=null){const{prompt_tokens:te,completion_tokens:ge,total_tokens:H,prompt_tokens_details:M,completion_tokens_details:B}=U.usage;u.promptTokens=te??void 0,u.completionTokens=ge??void 0,u.totalTokens=H??void 0,B?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=B?.rejected_prediction_tokens),M?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=M?.cached_tokens)}const V=U.choices[0];if(V?.finish_reason!=null&&(c=R1(V.finish_reason)),V?.delta==null)return;const Q=V.delta,_e=(w=Q.reasoning_content)!=null?w:Q.reasoning;if(_e&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:_e})),Q.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const te of Q.tool_calls){const ge=te.index;if(l[ge]==null){if(te.id==null)throw new o1({data:te,message:"Expected 'id' to be a string."});if(((v=te.function)==null?void 0:v.name)==null)throw new o1({data:te,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),l[ge]={id:te.id,type:"function",function:{name:te.function.name,arguments:(m=te.function.arguments)!=null?m:""},hasFinished:!1};const M=l[ge];((C=M.function)==null?void 0:C.name)!=null&&((k=M.function)==null?void 0:k.arguments)!=null&&(M.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),I1(M.function.arguments)&&(y.enqueue({type:"tool-input-end",id:M.id}),y.enqueue({type:"tool-call",toolCallId:(b=M.id)!=null?b:Tl(),toolName:M.function.name,input:M.function.arguments}),M.hasFinished=!0));continue}const H=l[ge];H.hasFinished||(((S=te.function)==null?void 0:S.arguments)!=null&&(H.function.arguments+=(I=(x=te.function)==null?void 0:x.arguments)!=null?I:""),y.enqueue({type:"tool-input-delta",id:H.id,delta:(L=te.function.arguments)!=null?L:""}),(($=H.function)==null?void 0:$.name)!=null&&((N=H.function)==null?void 0:N.arguments)!=null&&I1(H.function.arguments)&&(y.enqueue({type:"tool-input-end",id:H.id}),y.enqueue({type:"tool-call",toolCallId:(A=H.id)!=null?A:Tl(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(_){var y,w,v,m,C,k;f&&_.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&_.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(x=>!x.hasFinished))_.enqueue({type:"tool-input-end",id:S.id}),_.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:Tl(),toolName:S.function.name,input:S.function.arguments});const b={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(b[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(b[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:(C=u.completionTokensDetails.reasoningTokens)!=null?C:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:b})}})),request:{body:o},response:{headers:a}}}},P1=T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),xP=T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:R("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:P1}),EP=e=>oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:me(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:P1}),e]);T({echo:he().optional(),logitBias:ye(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var $P=T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:$P.nullish()}),T({dimensions:j().optional(),user:d().optional()}),T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish(),providerMetadata:ye(d(),ye(d(),kt())).optional()}),T({data:q(T({b64_json:d()}))});var M1=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}}},RP={extractMetadata:async({parsedBody:e})=>{const t=await oa({value:e,schema:PP});return!t.success||t.value.usage==null?void 0:M1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await oa({value:t,schema:MP});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:()=>M1(e)}}},O1=T({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),PP=T({usage:O1.nullish()}),MP=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:O1.nullish()}),OP="1.0.30";function N1(e={}){var t;const r=bP((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>T1({Authorization:`Bearer ${rP({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${OP}`);class o extends IP{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:RP}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new h1({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new h1({modelId:i,modelType:"imageModel"})},a}N1();const A1=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]=bg({description:o,inputSchema:qo({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function NP(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
598
598
 
599
599
  # 工具调用
600
600
 
@@ -628,15 +628,15 @@ Error message: ${P_(r)}`,cause:r}),this[Q_]=!0,this.value=t}static isInstance(t)
628
628
  `,r+=`- 必须严格按照 XML 格式调用工具
629
629
  `,r+=`- arguments 必须是有效的 JSON 格式
630
630
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
631
- `,r}function y1(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 mP={openai:k_,deepseek:m1};class gP{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=mP[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 Ts(new URL(t.url)):"type"in t&&t.type==="extension"?r=new c0(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await G$({transport:r});return o.__transport__=r,o}else{const o=new a0({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 xs||r&&r instanceof Cs)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 g1(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=hP(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)},f=i[0]?.role==="system"?i:[u,...i];return t===Cd?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,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:h,...y}=s,g=(await bv({model:this.llm(n),messages:p,...y})).text,b={role:"assistant",content:g};l.push(b),a.push(b);const v=y1(g,r);if(!v)return this.responseMessages=a,{text:g,response:{messages:a}};const m=await this._executeReActToolCall(v.toolName,v.arguments,r),_={role:"user",content:`<tool_response>
631
+ `,r}function q1(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 AP={openai:z_,deepseek:N1};class qP{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=AP[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 Os(new URL(t.url)):"type"in t&&t.type==="extension"?r=new I0(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await d7({transport:r});return o.__transport__=r,o}else{const o=new T0({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 js||r&&r instanceof Ns)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 A1(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=NP(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 Dv({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const v=q1(y,r);if(!v)return this.responseMessages=a,{text:y,response:{messages:a}};const m=await this._executeReActToolCall(v.toolName,v.arguments,r),b={role:"user",content:`<tool_response>
633
633
  ${m.success?JSON.stringify(m.result):`工具执行失败 - ${m.error}`}
634
- </tool_response>`};l.push(_),a.push(_)}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,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const y=t[0]?.role==="system"?t[0]:null,w=y?t.slice(1):[...t];let g=0,b="";const v=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;g<o;){g++;const m=a._buildMessagesForModel(y,w,v),{tools:T,...k}=s;delete k.system,delete k.onFinish;const _=await Cd({...k,model:i,messages:m});let S="";for await(const J of _.fullStream)J.type==="text-delta"?(S+=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);b+=S;const $={role:"assistant",content:b};w.push($),h.push($);const x=y1(b,r);if(!x){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}if(x.toolName==="computer"&&x.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}const U=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:U,toolName:x.toolName});const M=JSON.stringify(x.arguments,null,2);p.enqueue({type:"tool-input-delta",id:U,delta:M}),p.enqueue({type:"tool-input-end",id:U}),p.enqueue({type:"tool-call",toolCallId:U,toolName:x.toolName,input:x.arguments});const O=await a._executeReActToolCall(x.toolName,x.arguments,r);let A,L=O.result;if(O.success&&O.result&&typeof O.result=="object"&&O.result.screenshot){A=O.result.screenshot;const{screenshot:J,...de}=O.result;L=de}let Y="";if(O.success){L&&Array.isArray(L.content)&&L.content.length>0&&L.content[0].text?Y=L.content[0].text:Y=JSON.stringify(L);let J=`<tool_response>
635
- ${Y}
636
- </tool_response>`;A&&(J+=`
637
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:U,result:J});const de=A?{role:"user",content:[{type:"text",text:J},{type:"image",image:A}]}:{role:"user",content:J};w.push(de),h.push(de),b=""}else Y=`工具执行失败 - ${O.error}`,p.enqueue({type:"tool-error",toolCallId:U,input:x.arguments,error:{message:Y}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h})}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:bd(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(bv,t)}async chatStream(t){return this._chat(Cd,t)}}const yP=/^\.\/[^/]+\/SKILL\.md$/,vP=/^---\s*\n([\s\S]+?)\s*\n---/;function v1(e){const t=e.match(vP);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 qd(e){return Object.keys(e).filter(t=>yP.test(t))}function _P(e){const t=qd(e),r=[];for(const n of t){const o=e[n];if(!o)continue;const s=v1(o);s&&r.push({name:s.name,description:s.description,path:n})}return r}function wP(e){return e.length===0?"":`## 可用技能
634
+ </tool_response>`};l.push(b),a.push(b)}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:C,...k}=s;delete k.system,delete k.onFinish;const b=await Zd({...k,model:i,messages:m});let S="";for await(const Q of b.fullStream)Q.type==="text-delta"?(S+=Q.text||"",p.enqueue({type:"text-delta",text:Q.text})):Q.type==="text-start"?p.enqueue({type:"text-start"}):Q.type==="text-end"||Q.type==="finish-step"||Q.type==="finish"||Q.type==="start"||Q.type==="start-step"||p.enqueue(Q);w+=S;const x={role:"assistant",content:w};_.push(x),f.push(x);const I=q1(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 $=JSON.stringify(I.arguments,null,2);p.enqueue({type:"tool-input-delta",id:L,delta:$}),p.enqueue({type:"tool-input-end",id:L}),p.enqueue({type:"tool-call",toolCallId:L,toolName:I.toolName,input:I.arguments});const N=await a._executeReActToolCall(I.toolName,I.arguments,r);let A,U=N.result;if(N.success&&N.result&&typeof N.result=="object"&&N.result.screenshot){A=N.result.screenshot;const{screenshot:Q,..._e}=N.result;U=_e}let V="";if(N.success){U&&Array.isArray(U.content)&&U.content.length>0&&U.content[0].text?V=U.content[0].text:V=JSON.stringify(U);let Q=`<tool_response>
635
+ ${V}
636
+ </tool_response>`;A&&(Q+=`
637
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:L,result:Q});const _e=A?{role:"user",content:[{type:"text",text:Q},{type:"image",image:A}]}:{role:"user",content:Q};_.push(_e),f.push(_e),w=""}else V=`工具执行失败 - ${N.error}`,p.enqueue({type:"tool-error",toolCallId:L,input:I.arguments,error:{message:V}})}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:Dd(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(Dv,t)}async chatStream(t){return this._chat(Zd,t)}}const LP=/^\.\/[^/]+\/SKILL\.md$/,jP=/^---\s*\n([\s\S]+?)\s*\n---/;function L1(e){const t=e.match(jP);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 tp(e){return Object.keys(e).filter(t=>LP.test(t))}function DP(e){const t=tp(e),r=[];for(const n of t){const o=e[n];if(!o)continue;const s=L1(o);s&&r.push({name:s.name,description:s.description,path:n})}return r}function UP(e){return e.length===0?"":`## 可用技能
638
638
 
639
639
  ${e.map(r=>`- **${r.name}**: ${r.description}`).join(`
640
640
  `)}
641
641
 
642
- 当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function bP(e){return Object.keys(e)}function Ld(e,t){return e[t]}function jd(e,t){return qd(e).find(r=>r.startsWith(`./${t}/SKILL.md`))}function kP(e){return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整 Markdown 文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md",inputSchema:jt({skillName:Ve().optional().describe("技能名称,与目录名一致,如 calculator"),path:Ve().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.md")}),execute:r=>{const{skillName:n,path:o}=r;let s;if(o)s=Ld(e,o);else if(n){const a=jd(e,n);s=a?Ld(e,a):void 0}return s===void 0?{error:"未找到对应技能文档",skillName:n??o}:{content:s,path:o??jd(e,n)}}}}}Oe.AgentModelProvider=gP,Oe.Ajv=wf,Oe.AuthClientProvider=PS,Oe.ContentScriptServerTransport=o6,Oe.ExtensionClientTransport=c0,Oe.ExtensionPageServerTransport=n6,Oe.InMemoryTransport=xs,Oe.QrCode=V0,Oe.ResourceTemplate=zS,Oe.UriTemplate=Br,Oe.WebMcpClient=a0,Oe.WebMcpServer=BS,Oe.completable=AS,Oe.createMessageChannelClientTransport=XS,Oe.createMessageChannelPairTransport=WS,Oe.createMessageChannelServerTransport=JS,Oe.createRemoter=j6,Oe.createSSEClientTransport=YS,Oe.createSkillTools=kP,Oe.createStreamableHTTPClientTransport=QS,Oe.formatSkillsForSystemPrompt=wP,Oe.getAISDKTools=g1,Oe.getDisplayName=HS,Oe.getMainSkillPathByName=jd,Oe.getMainSkillPaths=qd,Oe.getSkillMdContent=Ld,Oe.getSkillMdPaths=bP,Oe.getSkillOverviews=_P,Oe.isMcpClient=r6,Oe.isMcpServer=KS,Oe.isMessageChannelClientTransport=t6,Oe.isMessageChannelServerTransport=GS,Oe.isSSEClientTransport=e6,Oe.isStreamableHTTPClientTransport=i0,Oe.parseSkillFrontMatter=v1,Oe.z=_b,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"})}));
642
+ 当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function zP(e){return Object.keys(e)}function rp(e,t){return e[t]}function np(e,t){return tp(e).find(r=>r.startsWith(`./${t}/SKILL.md`))}function ZP(e){return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)。支持 .md、.json、.xml 等各类文本格式文件。",inputSchema:Vt({skillName:Fe().optional().describe("技能名称,与目录名一致,如 calculator"),path:Fe().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json")}),execute:r=>{const{skillName:n,path:o}=r;let s;if(o)s=rp(e,o);else if(n){const a=np(e,n);s=a?rp(e,a):void 0}return s===void 0?{error:"未找到对应技能文档",skillName:n??o}:{content:s,path:o??np(e,n)}}}}}Re.AgentModelProvider=qP,Re.Ajv=Lf,Re.AuthClientProvider=KS,Re.ContentScriptServerTransport=T6,Re.ExtensionClientTransport=I0,Re.ExtensionPageServerTransport=k6,Re.InMemoryTransport=js,Re.QrCode=i2,Re.ResourceTemplate=a6,Re.UriTemplate=rn,Re.WebMcpClient=T0,Re.WebMcpServer=d6,Re.completable=XS,Re.createMessageChannelClientTransport=v6,Re.createMessageChannelPairTransport=f6,Re.createMessageChannelServerTransport=p6,Re.createRemoter=n5,Re.createSSEClientTransport=g6,Re.createSkillTools=ZP,Re.createStreamableHTTPClientTransport=y6,Re.formatSkillsForSystemPrompt=UP,Re.getAISDKTools=A1,Re.getDisplayName=u6,Re.getMainSkillPathByName=np,Re.getMainSkillPaths=tp,Re.getSkillMdContent=rp,Re.getSkillMdPaths=zP,Re.getSkillOverviews=DP,Re.isMcpClient=b6,Re.isMcpServer=m6,Re.isMessageChannelClientTransport=w6,Re.isMessageChannelServerTransport=h6,Re.isSSEClientTransport=_6,Re.isStreamableHTTPClientTransport=C0,Re.parseSkillFrontMatter=L1,Re.z=jb,Object.defineProperty(Re,Symbol.toStringTag,{value:"Module"})}));