@opentiny/next-sdk 0.2.7 → 0.2.9
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/agent/AgentModelProvider.ts +22 -10
- package/dist/agent/AgentModelProvider.d.ts +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.es.dev.js +476 -23
- package/dist/index.es.js +6622 -6273
- package/dist/index.js +2120 -1771
- package/dist/index.umd.dev.js +476 -23
- package/dist/index.umd.js +217 -49
- package/dist/{page-tool-bridge.d.ts → page-tools/bridge.d.ts} +34 -42
- package/dist/page-tools/effects.d.ts +36 -0
- package/dist/remoter/createRemoter.d.ts +2 -0
- package/dist/skills/index.d.ts +2 -1
- package/dist/webagent.dev.js +31 -7
- package/dist/webagent.es.dev.js +31 -7
- package/dist/webagent.es.js +33 -17
- package/dist/webagent.js +3 -3
- package/index.ts +1 -1
- package/package.json +1 -1
- package/{page-tool-bridge.ts → page-tools/bridge.ts} +170 -95
- package/page-tools/effects.ts +343 -0
- package/remoter/createRemoter.ts +25 -11
- package/skills/index.ts +109 -12
package/dist/index.umd.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
|
-
(function(Ce,Nn){typeof exports=="object"&&typeof module<"u"?Nn(exports):typeof define=="function"&&define.amd?define(["exports"],Nn):(Ce=typeof globalThis<"u"?globalThis:Ce||self,Nn(Ce.WebMCP={}))})(this,(function(Ce){"use strict";function Nn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ba={exports:{}},Ll={},Jr={},An={},jl={},Dl={},Ul={},Cp;function ka(){return Cp||(Cp=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(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((m,C)=>`${m}${C}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_: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,..._){const m=[w[0]];let C=0;for(;C<_.length;)i(m,_[C]),m.push(w[++C]);return new n(m)}e._=o;const s=new n("+");function a(w,..._){const m=[f(w[0])];let C=0;for(;C<_.length;)m.push(s),i(m,_[C]),m.push(s,f(w[++C]));return l(m),new n(m)}e.str=a;function i(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(h(_))}e.addCodeArg=i;function l(w){let _=1;for(;_<w.length-1;){if(w[_]===s){const m=c(w[_-1],w[_+1]);if(m!==void 0){w.splice(_-1,3,m);continue}w[_++]="+"}_++}}function c(w,_){if(_==='""')return w;if(w==='""')return _;if(typeof w=="string")return _ instanceof r||w[w.length-1]!=='"'?void 0:typeof _!="string"?`${w.slice(0,-1)}${_}"`:_[0]==='"'?w.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(w instanceof r))return`"${w}${_.slice(1)}`}function u(w,_){return _.emptyStr()?w:w.emptyStr()?_:a`${w}${_}`}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 v(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=v;function y(w){return new n(w.toString())}e.regexpCode=y})(Ul)),Ul}var zl={},Sp;function Ip(){return Sp||(Sp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ka();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 v=this._values[f];if(v){const _=v.get(g);if(_)return _}else v=this._values[f]=new Map;v.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 v=c[g];if(!v)continue;const y=h[g]=h[g]||new Map;v.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let _=u(w);if(_){const m=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${m} ${w} = ${_};${this.opts._n}`}else if(_=p?.(w))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(zl)),zl}var Ep;function Oe(){return Ep||(Ep=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=ka(),r=Ip();var n=ka();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=Ip();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(x,M){return this}}class a extends s{constructor(x,M,L){super(),this.varKind=x,this.name=M,this.rhs=L}render({es5:x,_n:M}){const L=x?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${L} ${this.name}${W};`+M}optimizeNames(x,M){if(x[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,x,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(x,M,L){super(),this.lhs=x,this.rhs=M,this.sideEffects=L}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,M){if(!(this.lhs instanceof t.Name&&!x[this.lhs.str]&&!this.sideEffects))return this.rhs=N(this.rhs,x,M),this}get names(){const x=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(x,this.rhs)}}class l extends i{constructor(x,M,L,W){super(x,L,W),this.op=M}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}}class c extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}}class u extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}}class h extends s{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}}class p extends s{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,M){return this.code=N(this.code,x,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((M,L)=>M+L.render(x),"")}optimizeNodes(){const{nodes:x}=this;let M=x.length;for(;M--;){const L=x[M].optimizeNodes();Array.isArray(L)?x.splice(M,1,...L):L?x[M]=L:x.splice(M,1)}return x.length>0?this:void 0}optimizeNames(x,M){const{nodes:L}=this;let W=L.length;for(;W--;){const te=L[W];te.optimizeNames(x,M)||(G(x,te.names),L.splice(W,1))}return L.length>0?this:void 0}get names(){return this.nodes.reduce((x,M)=>U(x,M.names),{})}}class g extends f{render(x){return"{"+x._n+super.render(x)+"}"+x._n}}class v extends f{}class y extends g{}y.kind="else";class w extends g{constructor(x,M){super(M),this.condition=x}render(x){let M=`if(${this.condition})`+super.render(x);return this.else&&(M+="else "+this.else.render(x)),M}optimizeNodes(){super.optimizeNodes();const x=this.condition;if(x===!0)return this.nodes;let M=this.else;if(M){const L=M.optimizeNodes();M=this.else=Array.isArray(L)?new y(L):L}if(M)return x===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(X(x),M instanceof w?[M]:M.nodes);if(!(x===!1||!this.nodes.length))return this}optimizeNames(x,M){var L;if(this.else=(L=this.else)===null||L===void 0?void 0:L.optimizeNames(x,M),!!(super.optimizeNames(x,M)||this.else))return this.condition=N(this.condition,x,M),this}get names(){const x=super.names;return A(x,this.condition),this.else&&U(x,this.else.names),x}}w.kind="if";class _ extends g{}_.kind="for";class m extends _{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iteration=N(this.iteration,x,M),this}get names(){return U(super.names,this.iteration.names)}}class C extends _{constructor(x,M,L,W){super(),this.varKind=x,this.name=M,this.from=L,this.to=W}render(x){const M=x.es5?r.varKinds.var:this.varKind,{name:L,from:W,to:te}=this;return`for(${M} ${L}=${W}; ${L}<${te}; ${L}++)`+super.render(x)}get names(){const x=A(super.names,this.from);return A(x,this.to)}}class b extends _{constructor(x,M,L,W){super(),this.loop=x,this.varKind=M,this.name=L,this.iterable=W}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iterable=N(this.iterable,x,M),this}get names(){return U(super.names,this.iterable.names)}}class k extends g{constructor(x,M,L){super(),this.name=x,this.args=M,this.async=L}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}}k.kind="func";class S extends f{render(x){return"return "+super.render(x)}}S.kind="return";class I extends g{render(x){let M="try"+super.render(x);return this.catch&&(M+=this.catch.render(x)),this.finally&&(M+=this.finally.render(x)),M}optimizeNodes(){var x,M;return super.optimizeNodes(),(x=this.catch)===null||x===void 0||x.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(x,M){var L,W;return super.optimizeNames(x,M),(L=this.catch)===null||L===void 0||L.optimizeNames(x,M),(W=this.finally)===null||W===void 0||W.optimizeNames(x,M),this}get names(){const x=super.names;return this.catch&&U(x,this.catch.names),this.finally&&U(x,this.finally.names),x}}class E extends g{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}}E.kind="catch";class j extends g{render(x){return"finally"+super.render(x)}}j.kind="finally";class O{constructor(x,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
|
|
2
|
-
`:""},this._extScope=x,this._scope=new r.Scope({parent:x}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,M){const L=this._extScope.value(x,M);return(this._values[L.prefix]||(this._values[L.prefix]=new Set)).add(L),L}getScopeValue(x,M){return this._extScope.getValue(x,M)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,M,L,W){const te=this._scope.toName(M);return L!==void 0&&W&&(this._constants[te.str]=L),this._leafNode(new a(x,te,L)),te}const(x,M,L){return this._def(r.varKinds.const,x,M,L)}let(x,M,L){return this._def(r.varKinds.let,x,M,L)}var(x,M,L){return this._def(r.varKinds.var,x,M,L)}assign(x,M,L){return this._leafNode(new i(x,M,L))}add(x,M){return this._leafNode(new l(x,e.operators.ADD,M))}code(x){return typeof x=="function"?x():x!==t.nil&&this._leafNode(new p(x)),this}object(...x){const M=["{"];for(const[L,W]of x)M.length>1&&M.push(","),M.push(L),(L!==W||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,W));return M.push("}"),new t._Code(M)}if(x,M,L){if(this._blockNode(new w(x)),M&&L)this.code(M).else().code(L).endIf();else if(M)this.code(M).endIf();else if(L)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new w(x))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(x,M){return this._blockNode(x),M&&this.code(M).endFor(),this}for(x,M){return this._for(new m(x),M)}forRange(x,M,L,W,te=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(x);return this._for(new C(te,se,M,L),()=>W(se))}forOf(x,M,L,W=r.varKinds.const){const te=this._scope.toName(x);if(this.opts.es5){const se=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${se}.length`,Se=>{this.var(te,(0,t._)`${se}[${Se}]`),L(te)})}return this._for(new b("of",W,te,M),()=>L(te))}forIn(x,M,L,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,t._)`Object.keys(${M})`,L);const te=this._scope.toName(x);return this._for(new b("in",W,te,M),()=>L(te))}endFor(){return this._endBlockNode(_)}label(x){return this._leafNode(new c(x))}break(x){return this._leafNode(new u(x))}return(x){const M=new S;if(this._blockNode(M),this.code(x),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(x,M,L){if(!M&&!L)throw new Error('CodeGen: "try" without "catch" and "finally"');const W=new I;if(this._blockNode(W),this.code(x),M){const te=this.name("e");this._currNode=W.catch=new E(te),M(te)}return L&&(this._currNode=W.finally=new j,this.code(L)),this._endBlockNode(E,j)}throw(x){return this._leafNode(new h(x))}block(x,M){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(M),this}endBlock(x){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const L=this._nodes.length-M;if(L<0||x!==void 0&&L!==x)throw new Error(`CodeGen: wrong number of nodes: ${L} vs ${x} expected`);return this._nodes.length=M,this}func(x,M=t.nil,L,W){return this._blockNode(new k(x,M,L)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,M){const L=this._currNode;if(L instanceof x||M&&L instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${x.kind}/${M.kind}`:x.kind}"`)}_elseNode(x){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=x,this}get _root(){return this._nodes[0]}get _currNode(){const x=this._nodes;return x[x.length-1]}set _currNode(x){const M=this._nodes;M[M.length-1]=x}}e.CodeGen=O;function U(Z,x){for(const M in x)Z[M]=(Z[M]||0)+(x[M]||0);return Z}function A(Z,x){return x instanceof t._CodeOrName?U(Z,x.names):Z}function N(Z,x,M){if(Z instanceof t.Name)return L(Z);if(!W(Z))return Z;return new t._Code(Z._items.reduce((te,se)=>(se instanceof t.Name&&(se=L(se)),se instanceof t._Code?te.push(...se._items):te.push(se),te),[]));function L(te){const se=M[te.str];return se===void 0||x[te.str]!==1?te:(delete x[te.str],se)}function W(te){return te instanceof t._Code&&te._items.some(se=>se instanceof t.Name&&x[se.str]===1&&M[se.str]!==void 0)}}function G(Z,x){for(const M in x)Z[M]=(Z[M]||0)-(x[M]||0)}function X(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${H(Z)}`}e.not=X;const Q=P(e.operators.AND);function K(...Z){return Z.reduce(Q)}e.and=K;const he=P(e.operators.OR);function V(...Z){return Z.reduce(he)}e.or=V;function P(Z){return(x,M)=>x===t.nil?M:M===t.nil?x:(0,t._)`${H(x)} ${Z} ${H(M)}`}function H(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(Dl)),Dl}var Ne={},xp;function De(){if(xp)return Ne;xp=1,Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.checkStrictMode=Ne.getErrorPath=Ne.Type=Ne.useFunc=Ne.setEvaluated=Ne.evaluatedPropsToName=Ne.mergeEvaluated=Ne.eachItem=Ne.unescapeJsonPointer=Ne.escapeJsonPointer=Ne.escapeFragment=Ne.unescapeFragment=Ne.schemaRefOrVal=Ne.schemaHasRulesButRef=Ne.schemaHasRules=Ne.checkUnknownRules=Ne.alwaysValidSchema=Ne.toHash=void 0;const e=Oe(),t=ka();function r(b){const k={};for(const S of b)k[S]=!0;return k}Ne.toHash=r;function n(b,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(b,k),!s(k,b.self.RULES.all))}Ne.alwaysValidSchema=n;function o(b,k=b.schema){const{opts:S,self:I}=b;if(!S.strictSchema||typeof k=="boolean")return;const E=I.RULES.keywords;for(const j in k)E[j]||C(b,`unknown keyword: "${j}"`)}Ne.checkUnknownRules=o;function s(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(k[S])return!0;return!1}Ne.schemaHasRules=s;function a(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(S!=="$ref"&&k.all[S])return!0;return!1}Ne.schemaHasRulesButRef=a;function i({topSchemaRef:b,schemaPath:k},S,I,E){if(!E){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${b}${k}${(0,e.getProperty)(I)}`}Ne.schemaRefOrVal=i;function l(b){return h(decodeURIComponent(b))}Ne.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Ne.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Ne.escapeJsonPointer=u;function h(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Ne.unescapeJsonPointer=h;function p(b,k){if(Array.isArray(b))for(const S of b)k(S);else k(b)}Ne.eachItem=p;function f({mergeNames:b,mergeToName:k,mergeValues:S,resultToName:I}){return(E,j,O,U)=>{const A=O===void 0?j:O instanceof e.Name?(j instanceof e.Name?b(E,j,O):k(E,j,O),O):j instanceof e.Name?(k(E,O,j),j):S(j,O);return U===e.Name&&!(A instanceof e.Name)?I(E,A):A}}Ne.mergeEvaluated={props:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>{b.if((0,e._)`${k} === true`,()=>b.assign(S,!0),()=>b.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${k})`))}),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>{k===!0?b.assign(S,!0):(b.assign(S,(0,e._)`${S} || {}`),v(b,S,k))}),mergeValues:(b,k)=>b===!0?!0:{...b,...k},resultToName:g}),items:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>b.assign(S,(0,e._)`${k} === true ? true : ${S} > ${k} ? ${S} : ${k}`)),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>b.assign(S,k===!0?!0:(0,e._)`${S} > ${k} ? ${S} : ${k}`)),mergeValues:(b,k)=>b===!0?!0:Math.max(b,k),resultToName:(b,k)=>b.var("items",k)})};function g(b,k){if(k===!0)return b.var("props",!0);const S=b.var("props",(0,e._)`{}`);return k!==void 0&&v(b,S,k),S}Ne.evaluatedPropsToName=g;function v(b,k,S){Object.keys(S).forEach(I=>b.assign((0,e._)`${k}${(0,e.getProperty)(I)}`,!0))}Ne.setEvaluated=v;const y={};function w(b,k){return b.scopeValue("func",{ref:k,code:y[k.code]||(y[k.code]=new t._Code(k.code))})}Ne.useFunc=w;var _;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(_||(Ne.Type=_={}));function m(b,k,S){if(b instanceof e.Name){const I=k===_.Num;return S?I?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:I?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(b).toString():"/"+u(b)}Ne.getErrorPath=m;function C(b,k,S=b.opts.strictSchema){if(S){if(k=`strict mode: ${k}`,S===!0)throw new Error(k);b.self.logger.warn(k)}}return Ne.checkStrictMode=C,Ne}var Ta={},$p;function hn(){if($p)return Ta;$p=1,Object.defineProperty(Ta,"__esModule",{value:!0});const e=Oe(),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 Ta.default=t,Ta}var Rp;function Ca(){return Rp||(Rp=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=Oe(),r=De(),n=hn();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,_,m){const{it:C}=y,{gen:b,compositeRule:k,allErrors:S}=C,I=h(y,w,_);m??(k||S)?l(b,I):c(C,(0,t._)`[${I}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:m}=y,{gen:C,compositeRule:b,allErrors:k}=m,S=h(y,w,_);l(C,S),b||k||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:_,data:m,errsCount:C,it:b}){if(C===void 0)throw new Error("ajv implementation error");const k=y.name("err");y.forRange("i",C,n.default.errors,S=>{y.const(k,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${k}.instancePath === undefined`,()=>y.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),y.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(y.assign((0,t._)`${k}.schema`,_),y.assign((0,t._)`${k}.data`,m))})}e.extendErrors=i;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:m,schemaEnv:C}=y;C.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${m}.errors`,w),_.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,_){const{createErrors:m}=y.it;return m===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:m,it:C}=y,b=[f(C,_),g(y,_)];return v(y,w,b),m.object(...b)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:m}){let C=m?w:(0,t.str)`${w}/${y}`;return _&&(C=(0,t.str)`${C}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,C]}function v(y,{params:w,message:_},m){const{keyword:C,data:b,schemaValue:k,it:S}=y,{opts:I,propertyName:E,topSchemaRef:j,schemaPath:O}=S;m.push([u.keyword,C],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),I.messages&&m.push([u.message,typeof _=="function"?_(y):_]),I.verbose&&m.push([u.schema,k],[u.parentSchema,(0,t._)`${j}${O}`],[n.default.data,b]),E&&m.push([u.propertyName,E])}})(jl)),jl}var Pp;function pw(){if(Pp)return An;Pp=1,Object.defineProperty(An,"__esModule",{value:!0}),An.boolOrEmptySchema=An.topBoolOrEmptySchema=void 0;const e=Ca(),t=Oe(),r=hn(),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))}An.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}An.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 An}var $t={},qn={},Mp;function Op(){if(Mp)return qn;Mp=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.getRules=qn.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)}qn.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 qn.getRules=n,qn}var Gr={},Np;function Ap(){if(Np)return Gr;Np=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.shouldUseRule=Gr.shouldUseGroup=Gr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Gr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Gr.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 Gr.shouldUseRule=r,Gr}var qp;function Sa(){if(qp)return $t;qp=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=Op(),t=Ap(),r=Ca(),n=Oe(),o=De();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||($t.DataType=s={}));function a(_){const m=i(_.type);if(m.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!m.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&m.push("null")}return m}$t.getSchemaTypes=a;function i(_){const m=Array.isArray(_)?_:_?[_]:[];if(m.every(e.isJSONType))return m;throw new Error("type must be JSONType or JSONType[]: "+m.join(","))}$t.getJSONTypes=i;function l(_,m){const{gen:C,data:b,opts:k}=_,S=u(m,k.coerceTypes),I=m.length>0&&!(S.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(_,m[0]));if(I){const E=g(m,b,k.strictNumbers,s.Wrong);C.if(E,()=>{S.length?h(_,m,S):y(_)})}return I}$t.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,m){return m?_.filter(C=>c.has(C)||m==="array"&&C==="array"):[]}function h(_,m,C){const{gen:b,data:k,opts:S}=_,I=b.let("dataType",(0,n._)`typeof ${k}`),E=b.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&b.if((0,n._)`${I} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>b.assign(k,(0,n._)`${k}[0]`).assign(I,(0,n._)`typeof ${k}`).if(g(m,k,S.strictNumbers),()=>b.assign(E,k))),b.if((0,n._)`${E} !== undefined`);for(const O of C)(c.has(O)||O==="array"&&S.coerceTypes==="array")&&j(O);b.else(),y(_),b.endIf(),b.if((0,n._)`${E} !== undefined`,()=>{b.assign(k,E),p(_,E)});function j(O){switch(O){case"string":b.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(E,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(E,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${I} == "boolean" || ${k} === null
|
|
3
|
-
|| (${I} == "string" && ${k} && ${k} == +${k})`).assign(
|
|
4
|
-
|| (${I} === "string" && ${k} && ${k} == +${k} && !(${k} % 1))`).assign(
|
|
5
|
-
|| ${I} === "boolean" || ${k} === null`).assign(E,(0,n._)`[${k}]`)}}}function p({gen:_,parentData:m,parentDataProperty:C},b){_.if((0,n._)`${m} !== undefined`,()=>_.assign((0,n._)`${m}[${C}]`,b))}function f(_,m,C,b=s.Correct){const k=b===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${m} ${k} 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=I((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":S=I();break;default:return(0,n._)`typeof ${m} ${k} ${_}`}return b===s.Correct?S:(0,n.not)(S);function I(E=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,E,C?(0,n._)`isFinite(${m})`:n.nil)}}$t.checkDataType=f;function g(_,m,C,b){if(_.length===1)return f(_[0],m,C,b);let k;const S=(0,o.toHash)(_);if(S.array&&S.object){const I=(0,n._)`typeof ${m} != "object"`;k=S.null?I:(0,n._)`!${m} || ${I}`,delete S.null,delete S.array,delete S.object}else k=n.nil;S.number&&delete S.integer;for(const I in S)k=(0,n.and)(k,f(I,m,C,b));return k}$t.checkDataTypes=g;const v={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:m})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${m}}`};function y(_){const m=w(_);(0,r.reportError)(m,v)}$t.reportTypeError=y;function w(_){const{gen:m,data:C,schema:b}=_,k=(0,o.schemaRefOrVal)(_,b,"type");return{gen:m,keyword:"type",data:C,schema:b.type,schemaCode:k,schemaValue:k,parentSchema:b,params:{},it:_}}return $t}var Jo={},Lp;function fw(){if(Lp)return Jo;Lp=1,Object.defineProperty(Jo,"__esModule",{value:!0}),Jo.assignDefaults=void 0;const e=Oe(),t=De();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))}Jo.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 Jo}var gr={},Be={},jp;function yr(){if(jp)return Be;jp=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=Oe(),t=De(),r=hn(),n=De();function o(_,m){const{gen:C,data:b,it:k}=_;C.if(u(C,b,m,k.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${m}`},!0),_.error()})}Be.checkReportMissingProp=o;function s({gen:_,data:m,it:{opts:C}},b,k){return(0,e.or)(...b.map(S=>(0,e.and)(u(_,m,S,C.ownProperties),(0,e._)`${k} = ${S}`)))}Be.checkMissingProp=s;function a(_,m){_.setParams({missingProperty:m},!0),_.error()}Be.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Be.hasPropFunc=i;function l(_,m,C){return(0,e._)`${i(_)}.call(${m}, ${C})`}Be.isOwnProperty=l;function c(_,m,C,b){const k=(0,e._)`${m}${(0,e.getProperty)(C)} !== undefined`;return b?(0,e._)`${k} && ${l(_,m,C)}`:k}Be.propertyInData=c;function u(_,m,C,b){const k=(0,e._)`${m}${(0,e.getProperty)(C)} === undefined`;return b?(0,e.or)(k,(0,e.not)(l(_,m,C))):k}Be.noPropertyInData=u;function h(_){return _?Object.keys(_).filter(m=>m!=="__proto__"):[]}Be.allSchemaProperties=h;function p(_,m){return h(m).filter(C=>!(0,t.alwaysValidSchema)(_,m[C]))}Be.schemaProperties=p;function f({schemaCode:_,data:m,it:{gen:C,topSchemaRef:b,schemaPath:k,errorPath:S},it:I},E,j,O){const U=O?(0,e._)`${_}, ${m}, ${b}${k}`:m,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const N=(0,e._)`${U}, ${C.object(...A)}`;return j!==e.nil?(0,e._)`${E}.call(${j}, ${N})`:(0,e._)`${E}(${N})`}Be.callValidateCode=f;const g=(0,e._)`new RegExp`;function v({gen:_,it:{opts:m}},C){const b=m.unicodeRegExp?"u":"",{regExp:k}=m.code,S=k(C,b);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${k.code==="new RegExp"?g:(0,n.useFunc)(_,k)}(${C}, ${b})`})}Be.usePattern=v;function y(_){const{gen:m,data:C,keyword:b,it:k}=_,S=m.name("valid");if(k.allErrors){const E=m.let("valid",!0);return I(()=>m.assign(E,!1)),E}return m.var(S,!0),I(()=>m.break()),S;function I(E){const j=m.const("len",(0,e._)`${C}.length`);m.forRange("i",0,j,O=>{_.subschema({keyword:b,dataProp:O,dataPropType:t.Type.Num},S),m.if((0,e.not)(S),E)})}}Be.validateArray=y;function w(_){const{gen:m,schema:C,keyword:b,it:k}=_;if(!Array.isArray(C))throw new Error("ajv implementation error");if(C.some(j=>(0,t.alwaysValidSchema)(k,j))&&!k.opts.unevaluated)return;const I=m.let("valid",!1),E=m.name("_valid");m.block(()=>C.forEach((j,O)=>{const U=_.subschema({keyword:b,schemaProp:O,compositeRule:!0},E);m.assign(I,(0,e._)`${I} || ${E}`),_.mergeValidEvaluated(U,E)||m.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Be.validateUnion=w,Be}var Dp;function hw(){if(Dp)return gr;Dp=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.validateKeywordUsage=gr.validSchemaType=gr.funcKeywordCode=gr.macroKeywordCode=void 0;const e=Oe(),t=hn(),r=yr(),n=Ca();function o(p,f){const{gen:g,keyword:v,schema:y,parentSchema:w,it:_}=p,m=f.macro.call(_.self,y,w,_),C=c(g,v,m);_.opts.validateSchema!==!1&&_.self.validateSchema(m,!0);const b=g.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:C,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}gr.macroKeywordCode=o;function s(p,f){var g;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:m,it:C}=p;l(C,f);const b=!m&&f.compile?f.compile.call(C.self,w,_,C):f.validate,k=c(v,y,b),S=v.let("valid");p.block$data(S,I),p.ok((g=f.valid)!==null&&g!==void 0?g:S);function I(){if(f.errors===!1)O(),f.modifying&&a(p),U(()=>p.error());else{const A=f.async?E():j();f.modifying&&a(p),U(()=>i(p,A))}}function E(){const A=v.let("ruleErrs",null);return v.try(()=>O((0,e._)`await `),N=>v.assign(S,!1).if((0,e._)`${N} instanceof ${C.ValidationError}`,()=>v.assign(A,(0,e._)`${N}.errors`),()=>v.throw(N))),A}function j(){const A=(0,e._)`${k}.errors`;return v.assign(A,null),O(e.nil),A}function O(A=f.async?(0,e._)`await `:e.nil){const N=C.opts.passContext?t.default.this:t.default.self,G=!("compile"in f&&!m||f.schema===!1);v.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,k,N,G)}`,f.modifying)}function U(A){var N;v.if((0,e.not)((N=f.valid)!==null&&N!==void 0?N:S),A)}}gr.funcKeywordCode=s;function a(p){const{gen:f,data:g,it:v}=p;f.if(v.parentData,()=>f.assign(g,(0,e._)`${v.parentData}[${v.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(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||g&&typeof p>"u")}gr.validSchemaType=u;function h({schema:p,opts:f,self:g,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(m=>!Object.prototype.hasOwnProperty.call(p,m)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const C=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(C);else throw new Error(C)}}return gr.validateKeywordUsage=h,gr}var Wr={},Up;function mw(){if(Up)return Wr;Up=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.getSubschema=void 0;const e=Oe(),t=De();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')}Wr.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:v,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=[...v,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]}}Wr.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 Wr.extendSubschemaMode=o,Wr}var Dt={},Zl,zp;function Zp(){return zp||(zp=1,Zl=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}),Zl}var Fl={exports:{}},Fp;function gw(){if(Fp)return Fl.exports;Fp=1;var e=Fl.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 v=0;v<g.length;v++)t(n,o,s,g[v],i+"/"+f+"/"+v,l,i,f,a,v)}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 Fl.exports}var Vp;function Ia(){if(Vp)return Dt;Vp=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;const e=De(),t=Zp(),r=gw(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,y=!0){return typeof v=="boolean"?!0:y===!0?!a(v):y?i(v)<=y:!1}Dt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let y=0;for(const w in v){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],_=>y+=i(_)),y===1/0))return 1/0}return y}function l(v,y="",w){w!==!1&&(y=h(y));const _=v.parse(y);return c(v,_)}Dt.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}Dt._getFullPath=c;const u=/#\/?$/;function h(v){return v?v.replace(u,""):""}Dt.normalizeId=h;function p(v,y,w){return w=h(w),v.resolve(y,w)}Dt.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,m=h(v[w]||y),C={"":m},b=l(_,m,!1),k={},S=new Set;return r(v,{allKeys:!0},(j,O,U,A)=>{if(A===void 0)return;const N=b+O;let G=C[A];typeof j[w]=="string"&&(G=X.call(this,j[w])),Q.call(this,j.$anchor),Q.call(this,j.$dynamicAnchor),C[O]=G;function X(K){const he=this.opts.uriResolver.resolve;if(K=h(G?he(G,K):K),S.has(K))throw E(K);S.add(K);let V=this.refs[K];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(j,V.schema,K):K!==h(N)&&(K[0]==="#"?(I(j,k[K],K),k[K]=j):this.refs[K]=N),K}function Q(K){if(typeof K=="string"){if(!f.test(K))throw new Error(`invalid anchor "${K}"`);X.call(this,`#${K}`)}}}),k;function I(j,O,U){if(O!==void 0&&!t(j,O))throw E(U)}function E(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Dt.getSchemaRefs=g,Dt}var Hp;function Ea(){if(Hp)return Jr;Hp=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=pw(),t=Sa(),r=Ap(),n=Sa(),o=fw(),s=hw(),a=mw(),i=Oe(),l=hn(),c=Ia(),u=De(),h=Ca();function p(z){if(b(z)&&(S(z),C(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Jr.validateFunctionCode=p;function f({gen:z,validateName:F,schema:Y,schemaEnv:ee,opts:ue},Ee){ue.code.es5?z.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,ee.$async,()=>{z.code((0,i._)`"use strict"; ${_(Y,ue)}`),v(z,ue),z.code(Ee)}):z.func(F,(0,i._)`${l.default.data}, ${g(ue)}`,ee.$async,()=>z.code(_(Y,ue)).code(Ee))}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 v(z,F){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,i._)`""`),z.var(l.default.parentData,(0,i._)`undefined`),z.var(l.default.parentDataProperty,(0,i._)`undefined`),z.var(l.default.rootData,l.default.data),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(z){const{schema:F,opts:Y,gen:ee}=z;f(z,()=>{Y.$comment&&F.$comment&&A(z),j(z),ee.let(l.default.vErrors,null),ee.let(l.default.errors,0),Y.unevaluated&&w(z),I(z),N(z)})}function w(z){const{gen:F,validateName:Y}=z;z.evaluated=F.const("evaluated",(0,i._)`${Y}.evaluated`),F.if((0,i._)`${z.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${z.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${z.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${z.evaluated}.items`,(0,i._)`undefined`))}function _(z,F){const Y=typeof z=="object"&&z[F.schemaId];return Y&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${Y} */`:i.nil}function m(z,F){if(b(z)&&(S(z),C(z))){k(z,F);return}(0,e.boolOrEmptySchema)(z,F)}function C({schema:z,self:F}){if(typeof z=="boolean")return!z;for(const Y in z)if(F.RULES.all[Y])return!0;return!1}function b(z){return typeof z.schema!="boolean"}function k(z,F){const{schema:Y,gen:ee,opts:ue}=z;ue.$comment&&Y.$comment&&A(z),O(z),U(z);const Ee=ee.const("_errs",l.default.errors);I(z,Ee),ee.var(F,(0,i._)`${Ee} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),E(z)}function I(z,F){if(z.opts.jtd)return X(z,[],!1,F);const Y=(0,t.getSchemaTypes)(z.schema),ee=(0,t.coerceAndCheckDataType)(z,Y);X(z,Y,!ee,F)}function E(z){const{schema:F,errSchemaPath:Y,opts:ee,self:ue}=z;F.$ref&&ee.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,ue.RULES)&&ue.logger.warn(`$ref: keywords ignored in schema at path "${Y}"`)}function j(z){const{schema:F,opts:Y}=z;F.default!==void 0&&Y.useDefaults&&Y.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function O(z){const F=z.schema[z.opts.schemaId];F&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,F))}function U(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:F,schema:Y,errSchemaPath:ee,opts:ue}){const Ee=Y.$comment;if(ue.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${Ee})`);else if(typeof ue.$comment=="function"){const He=(0,i.str)`${ee}/$comment`,ot=z.scopeValue("root",{ref:F.root});z.code((0,i._)`${l.default.self}.opts.$comment(${Ee}, ${He}, ${ot}.schema)`)}}function N(z){const{gen:F,schemaEnv:Y,validateName:ee,ValidationError:ue,opts:Ee}=z;Y.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${ue}(${l.default.vErrors})`)):(F.assign((0,i._)`${ee}.errors`,l.default.vErrors),Ee.unevaluated&&G(z),F.return((0,i._)`${l.default.errors} === 0`))}function G({gen:z,evaluated:F,props:Y,items:ee}){Y instanceof i.Name&&z.assign((0,i._)`${F}.props`,Y),ee instanceof i.Name&&z.assign((0,i._)`${F}.items`,ee)}function X(z,F,Y,ee){const{gen:ue,schema:Ee,data:He,allErrors:ot,opts:ft,self:et}=z,{RULES:$}=et;if(Ee.$ref&&(ft.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Ee,$))){ue.block(()=>W(z,"$ref",$.all.$ref.definition));return}ft.jtd||K(z,F),ue.block(()=>{for(const Le of $.rules)ne(Le);ne($.post)});function ne(Le){(0,r.shouldUseGroup)(Ee,Le)&&(Le.type?(ue.if((0,n.checkDataType)(Le.type,He,ft.strictNumbers)),Q(z,Le),F.length===1&&F[0]===Le.type&&Y&&(ue.else(),(0,n.reportTypeError)(z)),ue.endIf()):Q(z,Le),ot||ue.if((0,i._)`${l.default.errors} === ${ee||0}`))}}function Q(z,F){const{gen:Y,schema:ee,opts:{useDefaults:ue}}=z;ue&&(0,o.assignDefaults)(z,F.type),Y.block(()=>{for(const Ee of F.rules)(0,r.shouldUseRule)(ee,Ee)&&W(z,Ee.keyword,Ee.definition,F.type)})}function K(z,F){z.schemaEnv.meta||!z.opts.strictTypes||(he(z,F),z.opts.allowUnionTypes||V(z,F),P(z,z.dataTypes))}function he(z,F){if(F.length){if(!z.dataTypes.length){z.dataTypes=F;return}F.forEach(Y=>{Z(z.dataTypes,Y)||M(z,`type "${Y}" not allowed by context "${z.dataTypes.join(",")}"`)}),x(z,F)}}function V(z,F){F.length>1&&!(F.length===2&&F.includes("null"))&&M(z,"use allowUnionTypes to allow union type keyword")}function P(z,F){const Y=z.self.RULES.all;for(const ee in Y){const ue=Y[ee];if(typeof ue=="object"&&(0,r.shouldUseRule)(z.schema,ue)){const{type:Ee}=ue.definition;Ee.length&&!Ee.some(He=>H(F,He))&&M(z,`missing type "${Ee.join(",")}" for keyword "${ee}"`)}}}function H(z,F){return z.includes(F)||F==="number"&&z.includes("integer")}function Z(z,F){return z.includes(F)||F==="integer"&&z.includes("number")}function x(z,F){const Y=[];for(const ee of z.dataTypes)Z(F,ee)?Y.push(ee):F.includes("integer")&&ee==="number"&&Y.push("integer");z.dataTypes=Y}function M(z,F){const Y=z.schemaEnv.baseId+z.errSchemaPath;F+=` at "${Y}" (strictTypes)`,(0,u.checkStrictMode)(z,F,z.opts.strictTypes)}class L{constructor(F,Y,ee){if((0,s.validateKeywordUsage)(F,Y,ee),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=ee,this.data=F.data,this.schema=F.schema[ee],this.$data=Y.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,ee,this.$data),this.schemaType=Y.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=Y,this.$data)this.schemaCode=F.gen.const("vSchema",Se(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,Y.schemaType,Y.allowUndefined))throw new Error(`${ee} value must be ${JSON.stringify(Y.schemaType)}`);("code"in Y?Y.trackErrors:Y.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,Y,ee){this.failResult((0,i.not)(F),Y,ee)}failResult(F,Y,ee){this.gen.if(F),ee?ee():this.error(),Y?(this.gen.else(),Y(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,Y){this.failResult((0,i.not)(F),void 0,Y)}fail(F){if(F===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(F),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(F){if(!this.$data)return this.fail(F);const{schemaCode:Y}=this;this.fail((0,i._)`${Y} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,Y,ee){if(Y){this.setParams(Y),this._error(F,ee),this.setParams({});return}this._error(F,ee)}_error(F,Y){(F?h.reportExtraError:h.reportError)(this,this.def.error,Y)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,Y){Y?Object.assign(this.params,F):this.params=F}block$data(F,Y,ee=i.nil){this.gen.block(()=>{this.check$data(F,ee),Y()})}check$data(F=i.nil,Y=i.nil){if(!this.$data)return;const{gen:ee,schemaCode:ue,schemaType:Ee,def:He}=this;ee.if((0,i.or)((0,i._)`${ue} === undefined`,Y)),F!==i.nil&&ee.assign(F,!0),(Ee.length||He.validateSchema)&&(ee.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&ee.assign(F,!1)),ee.else()}invalid$data(){const{gen:F,schemaCode:Y,schemaType:ee,def:ue,it:Ee}=this;return(0,i.or)(He(),ot());function He(){if(ee.length){if(!(Y instanceof i.Name))throw new Error("ajv implementation error");const ft=Array.isArray(ee)?ee:[ee];return(0,i._)`${(0,n.checkDataTypes)(ft,Y,Ee.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function ot(){if(ue.validateSchema){const ft=F.scopeValue("validate$data",{ref:ue.validateSchema});return(0,i._)`!${ft}(${Y})`}return i.nil}}subschema(F,Y){const ee=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(ee,this.it,F),(0,a.extendSubschemaMode)(ee,F);const ue={...this.it,...ee,items:void 0,props:void 0};return m(ue,Y),ue}mergeEvaluated(F,Y){const{it:ee,gen:ue}=this;ee.opts.unevaluated&&(ee.props!==!0&&F.props!==void 0&&(ee.props=u.mergeEvaluated.props(ue,F.props,ee.props,Y)),ee.items!==!0&&F.items!==void 0&&(ee.items=u.mergeEvaluated.items(ue,F.items,ee.items,Y)))}mergeValidEvaluated(F,Y){const{it:ee,gen:ue}=this;if(ee.opts.unevaluated&&(ee.props!==!0||ee.items!==!0))return ue.if(Y,()=>this.mergeEvaluated(F,i.Name)),!0}}Jr.KeywordCxt=L;function W(z,F,Y,ee){const ue=new L(z,Y,F);"code"in Y?Y.code(ue,ee):ue.$data&&Y.validate?(0,s.funcKeywordCode)(ue,Y):"macro"in Y?(0,s.macroKeywordCode)(ue,Y):(Y.compile||Y.validate)&&(0,s.funcKeywordCode)(ue,Y)}const te=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Se(z,{dataLevel:F,dataNames:Y,dataPathArr:ee}){let ue,Ee;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!te.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);ue=z,Ee=l.default.rootData}else{const et=se.exec(z);if(!et)throw new Error(`Invalid JSON-pointer: ${z}`);const $=+et[1];if(ue=et[2],ue==="#"){if($>=F)throw new Error(ft("property/index",$));return ee[F-$]}if($>F)throw new Error(ft("data",$));if(Ee=Y[F-$],!ue)return Ee}let He=Ee;const ot=ue.split("/");for(const et of ot)et&&(Ee=(0,i._)`${Ee}${(0,i.getProperty)((0,u.unescapeJsonPointer)(et))}`,He=(0,i._)`${He} && ${Ee}`);return He;function ft(et,$){return`Cannot access ${et} ${$} levels up, current level is ${F}`}}return Jr.getData=Se,Jr}var xa={},Bp;function Vl(){if(Bp)return xa;Bp=1,Object.defineProperty(xa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return xa.default=e,xa}var $a={},Jp;function Ra(){if(Jp)return $a;Jp=1,Object.defineProperty($a,"__esModule",{value:!0});const e=Ia();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 $a.default=t,$a}var er={},Gp;function Hl(){if(Gp)return er;Gp=1,Object.defineProperty(er,"__esModule",{value:!0}),er.resolveSchema=er.getCompilingSchema=er.resolveRef=er.compileSchema=er.SchemaEnv=void 0;const e=Oe(),t=Vl(),r=hn(),n=Ia(),o=De(),s=Ea();class a{constructor(w){var _;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=(_=w.baseId)!==null&&_!==void 0?_:(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={}}}er.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:m,lines:C}=this.opts.code,{ownProperties:b}=this.opts,k=new e.CodeGen(this.scope,{es5:m,lines:C,ownProperties:b});let S;y.$async&&(S=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=k.scopeName("validate");y.validateName=I;const E={gen:k,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:k.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:I,ValidationError:S,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,s.validateFunctionCode)(E),k.optimize(this.opts.code.optimize);const O=k.toString();j=`${k.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(I,{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:I,validateCode:O,scopeValues:k._values}),this.opts.unevaluated){const{props:N,items:G}=E;A.evaluated={props:N instanceof e.Name?void 0:N,items:G instanceof e.Name?void 0:G,dynamicProps:N instanceof e.Name,dynamicItems:G instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch(O){throw delete y.validate,delete y.validateName,j&&this.logger.error("Error compiling schema, function code:",j),O}finally{this._compilations.delete(y)}}er.compileSchema=i;function l(y,w,_){var m;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const C=y.refs[_];if(C)return C;let b=p.call(this,y,_);if(b===void 0){const k=(m=y.localRefs)===null||m===void 0?void 0:m[_],{schemaId:S}=this.opts;k&&(b=new a({schema:k,schemaId:S,root:y,baseId:w}))}if(b!==void 0)return y.refs[_]=c.call(this,b)}er.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}er.getCompilingSchema=u;function h(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),m=(0,n._getFullPath)(this.opts.uriResolver,_);let C=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&m===C)return v.call(this,_,y);const b=(0,n.normalizeId)(m),k=this.refs[b]||this.schemas[b];if(typeof k=="string"){const S=f.call(this,y,k);return typeof S?.schema!="object"?void 0:v.call(this,_,S)}if(typeof k?.schema=="object"){if(k.validate||i.call(this,k),b===(0,n.normalizeId)(w)){const{schema:S}=k,{schemaId:I}=this.opts,E=S[I];return E&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,E)),new a({schema:S,schemaId:I,root:y,baseId:C})}return v.call(this,_,k)}}er.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,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 _=="boolean")return;const I=_[(0,o.unescapeFragment)(S)];if(I===void 0)return;_=I;const E=typeof _=="object"&&_[this.opts.schemaId];!g.has(S)&&E&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,E))}let b;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);b=f.call(this,m,S)}const{schemaId:k}=this.opts;if(b=b||new a({schema:_,schemaId:k,root:m,baseId:w}),b.schema!==b.root.schema)return b}return er}const yw={$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 Pa={},Go={exports:{}},Bl,Wp;function Kp(){if(Wp)return Bl;Wp=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,v=0;for(v=0;v<p.length;v++)if(g=p[v].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v];break}for(v+=1;v<p.length;v++){if(g=p[v].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v]}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 v=r(p);if(v!=="")f.push(v);else return g.error=!0,!1;p.length=0}return!0}function a(p){let f=0;const g={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,m=s;for(let C=0;C<p.length;C++){const b=p[C];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(_=!0),!m(y,v,g))break;if(++f>7){g.error=!0;break}C>0&&p[C-1]===":"&&(w=!0),v.push(":");continue}else if(b==="%"){if(!m(y,v,g))break;m=o}else{y.push(b);continue}}return y.length&&(m===o?g.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),g.address=v.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,v=f.address;return f.zone&&(g+="%"+f.zone,v+="%25"+f.zone),{host:g,isIPV6:!0,escapedHost:v}}}function l(p,f){let g=0;for(let v=0;v<p.length;v++)p[v]===f&&g++;return g}function c(p){let f=p;const g=[];let v=-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((v=f.indexOf("/",1))===-1){g.push(f);break}else g.push(f.slice(0,v)),f=f.slice(v)}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 v=i(g);v.isIPV6===!0?g=`[${v.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 Bl={nonSimpleDomain:n,recomposeAuthority:h,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},Bl}var Jl,Yp;function vw(){if(Yp)return Jl;Yp=1;const{isUUID:e}=Kp(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function a(b){const k=String(b.scheme).toLowerCase()==="https";return(b.port===(k?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function i(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[k,S]=b.resourceName.split("?");b.path=k&&k!=="/"?k:void 0,b.query=S,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,k){if(!b.path)return b.error="URN can not be parsed",b;const S=b.path.match(t);if(S){const I=k.scheme||b.scheme||"urn";b.nid=S[1].toLowerCase(),b.nss=S[2];const E=`${I}:${k.nid||b.nid}`,j=C(E);b.path=void 0,j&&(b=j.parse(b,k))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,k){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=k.scheme||b.scheme||"urn",I=b.nid.toLowerCase(),E=`${S}:${k.nid||I}`,j=C(E);j&&(b=j.serialize(b,k));const O=b,U=b.nss;return O.path=`${I||k.nid}:${U}`,k.skipEscape=!0,O}function h(b,k){const S=b;return S.uuid=S.nss,S.nss=void 0,!k.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(b){const k=b;return k.nss=(b.uuid||"").toLowerCase(),k}const f={scheme:"http",domainHost:!0,parse:s,serialize:a},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},m={http:f,https:g,ws:v,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(b){return b&&(m[b]||m[b.toLowerCase()])||void 0}return Jl={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:C},Jl}var Qp;function _w(){if(Qp)return Go.exports;Qp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Kp(),{SCHEMES:a,getSchemeHandler:i}=vw();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,_){const m=_?Object.assign({scheme:"null"},_):{scheme:"null"},C=u(g(y,m),g(w,m),m,!0);return m.skipEscape=!0,p(C,m)}function u(y,w,_,m){const C={};return m||(y=g(p(y,_),_),w=g(p(w,_),_)),_=_||{},!_.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,_){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={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=[],b=i(m.scheme||_.scheme);b&&b.serialize&&b.serialize(_,m),_.path!==void 0&&(m.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),m.reference!=="suffix"&&_.scheme&&C.push(_.scheme,":");const k=r(_);if(k!==void 0&&(m.reference!=="suffix"&&C.push("//"),C.push(k),_.path&&_.path[0]!=="/"&&C.push("/")),_.path!==void 0){let S=_.path;!m.absolutePath&&(!b||!b.absolutePath)&&(S=t(S)),k===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),C.push(S)}return _.query!==void 0&&C.push("?",_.query),_.fragment!==void 0&&C.push("#",_.fragment),C.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const _=Object.assign({},w),m={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let C=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const b=y.match(f);if(b){if(m.scheme=b[1],m.userinfo=b[3],m.host=b[4],m.port=parseInt(b[5],10),m.path=b[6]||"",m.query=b[7],m.fragment=b[8],isNaN(m.port)&&(m.port=b[5]),m.host)if(o(m.host)===!1){const I=e(m.host);m.host=I.host.toLowerCase(),C=I.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",_.reference&&_.reference!=="suffix"&&_.reference!==m.reference&&(m.error=m.error||"URI is not a "+_.reference+" reference.");const k=i(_.scheme||m.scheme);if(!_.unicodeSupport&&(!k||!k.unicodeSupport)&&m.host&&(_.domainHost||k&&k.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}(!k||k&&!k.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)))),k&&k.parse&&k.parse(m,_)}else m.error=m.error||"URI can not be parsed.";return m}const v={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:h,serialize:p,parse:g};return Go.exports=v,Go.exports.default=v,Go.exports.fastUri=v,Go.exports}var Xp;function ww(){if(Xp)return Pa;Xp=1,Object.defineProperty(Pa,"__esModule",{value:!0});const e=_w();return e.code='require("ajv/dist/runtime/uri").default',Pa.default=e,Pa}var ef;function bw(){return ef||(ef=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=Ea();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Oe();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=Vl(),o=Ra(),s=Op(),a=Hl(),i=Oe(),l=Ia(),c=Sa(),u=De(),h=yw,p=ww(),f=(V,P)=>new RegExp(V,P);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=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.'},_=200;function m(V){var P,H,Z,x,M,L,W,te,se,Se,z,F,Y,ee,ue,Ee,He,ot,ft,et,$,ne,Le,_t,Ht;const We=V.strict,un=(P=V.code)===null||P===void 0?void 0:P.optimize,ht=un===!0||un===void 0?1:un||0,hr=(Z=(H=V.code)===null||H===void 0?void 0:H.regExp)!==null&&Z!==void 0?Z:f,Pn=(x=V.uriResolver)!==null&&x!==void 0?x:p.default;return{strictSchema:(L=(M=V.strictSchema)!==null&&M!==void 0?M:We)!==null&&L!==void 0?L:!0,strictNumbers:(te=(W=V.strictNumbers)!==null&&W!==void 0?W:We)!==null&&te!==void 0?te:!0,strictTypes:(Se=(se=V.strictTypes)!==null&&se!==void 0?se:We)!==null&&Se!==void 0?Se:"log",strictTuples:(F=(z=V.strictTuples)!==null&&z!==void 0?z:We)!==null&&F!==void 0?F:"log",strictRequired:(ee=(Y=V.strictRequired)!==null&&Y!==void 0?Y:We)!==null&&ee!==void 0?ee:!1,code:V.code?{...V.code,optimize:ht,regExp:hr}:{optimize:ht,regExp:hr},loopRequired:(ue=V.loopRequired)!==null&&ue!==void 0?ue:_,loopEnum:(Ee=V.loopEnum)!==null&&Ee!==void 0?Ee:_,meta:(He=V.meta)!==null&&He!==void 0?He:!0,messages:(ot=V.messages)!==null&&ot!==void 0?ot:!0,inlineRefs:(ft=V.inlineRefs)!==null&&ft!==void 0?ft:!0,schemaId:(et=V.schemaId)!==null&&et!==void 0?et:"$id",addUsedSchema:($=V.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(ne=V.validateSchema)!==null&&ne!==void 0?ne:!0,validateFormats:(Le=V.validateFormats)!==null&&Le!==void 0?Le:!0,unicodeRegExp:(_t=V.unicodeRegExp)!==null&&_t!==void 0?_t:!0,int32range:(Ht=V.int32range)!==null&&Ht!==void 0?Ht:!0,uriResolver:Pn}}class C{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,...m(P)};const{es5:H,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:H,lines:Z}),this.logger=U(P.logger);const x=P.validateFormats;P.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,y,P,"NOT SUPPORTED"),b.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&E.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),S.call(this),P.validateFormats=x}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:H,schemaId:Z}=this.opts;let x=h;Z==="id"&&(x={...h},x.id=x.$id,delete x.$id),H&&P&&this.addMetaSchema(x,x[Z],!1)}defaultMeta(){const{meta:P,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[H]||P:void 0}validate(P,H){let Z;if(typeof P=="string"){if(Z=this.getSchema(P),!Z)throw new Error(`no schema with key or ref "${P}"`)}else Z=this.compile(P);const x=Z(H);return"$async"in Z||(this.errors=Z.errors),x}compile(P,H){const Z=this._addSchema(P,H);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(P,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return x.call(this,P,H);async function x(Se,z){await M.call(this,Se.$schema);const F=this._addSchema(Se,z);return F.validate||L.call(this,F)}async function M(Se){Se&&!this.getSchema(Se)&&await x.call(this,{$ref:Se},!0)}async function L(Se){try{return this._compileSchemaEnv(Se)}catch(z){if(!(z instanceof o.default))throw z;return W.call(this,z),await te.call(this,z.missingSchema),L.call(this,Se)}}function W({missingSchema:Se,missingRef:z}){if(this.refs[Se])throw new Error(`AnySchema ${Se} is loaded but ${z} cannot be resolved`)}async function te(Se){const z=await se.call(this,Se);this.refs[Se]||await M.call(this,z.$schema),this.refs[Se]||this.addSchema(z,Se,H)}async function se(Se){const z=this._loading[Se];if(z)return z;try{return await(this._loading[Se]=Z(Se))}finally{delete this._loading[Se]}}}addSchema(P,H,Z,x=this.opts.validateSchema){if(Array.isArray(P)){for(const L of P)this.addSchema(L,void 0,Z,x);return this}let M;if(typeof P=="object"){const{schemaId:L}=this.opts;if(M=P[L],M!==void 0&&typeof M!="string")throw new Error(`schema ${L} must be string`)}return H=(0,l.normalizeId)(H||M),this._checkUnique(H),this.schemas[H]=this._addSchema(P,Z,H,x,!0),this}addMetaSchema(P,H,Z=this.opts.validateSchema){return this.addSchema(P,H,!0,Z),this}validateSchema(P,H){if(typeof P=="boolean")return!0;let Z;if(Z=P.$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 x=this.validate(Z,P);if(!x&&H){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return x}getSchema(P){let H;for(;typeof(H=k.call(this,P))=="string";)P=H;if(H===void 0){const{schemaId:Z}=this.opts,x=new a.SchemaEnv({schema:{},schemaId:Z});if(H=a.resolveSchema.call(this,x,P),!H)return;this.refs[P]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const H=k.call(this,P);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const H=P;this._cache.delete(H);let Z=P[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(P){for(const H of P)this.addKeyword(H);return this}addKeyword(P,H){let Z;if(typeof P=="string")Z=P,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=Z);else if(typeof P=="object"&&H===void 0){if(H=P,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(N.call(this,Z,H),!H)return(0,u.eachItem)(Z,M=>G.call(this,M)),this;Q.call(this,H);const x={...H,type:(0,c.getJSONTypes)(H.type),schemaType:(0,c.getJSONTypes)(H.schemaType)};return(0,u.eachItem)(Z,x.type.length===0?M=>G.call(this,M,x):M=>x.type.forEach(L=>G.call(this,M,x,L))),this}getKeyword(P){const H=this.RULES.all[P];return typeof H=="object"?H.definition:!!H}removeKeyword(P){const{RULES:H}=this;delete H.keywords[P],delete H.all[P];for(const Z of H.rules){const x=Z.rules.findIndex(M=>M.keyword===P);x>=0&&Z.rules.splice(x,1)}return this}addFormat(P,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[P]=H,this}errorsText(P=this.errors,{separator:H=", ",dataVar:Z="data"}={}){return!P||P.length===0?"No errors":P.map(x=>`${Z}${x.instancePath} ${x.message}`).reduce((x,M)=>x+H+M)}$dataMetaSchema(P,H){const Z=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const x of H){const M=x.split("/").slice(1);let L=P;for(const W of M)L=L[W];for(const W in Z){const te=Z[W];if(typeof te!="object")continue;const{$data:se}=te.definition,Se=L[W];se&&Se&&(L[W]=he(Se))}}return P}_removeAllSchemas(P,H){for(const Z in P){const x=P[Z];(!H||H.test(Z))&&(typeof x=="string"?delete P[Z]:x&&!x.meta&&(this._cache.delete(x.schema),delete P[Z]))}}_addSchema(P,H,Z,x=this.opts.validateSchema,M=this.opts.addUsedSchema){let L;const{schemaId:W}=this.opts;if(typeof P=="object")L=P[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(P);if(te!==void 0)return te;Z=(0,l.normalizeId)(L||Z);const se=l.getSchemaRefs.call(this,P,Z);return te=new a.SchemaEnv({schema:P,schemaId:W,meta:H,baseId:Z,localRefs:se}),this._cache.set(te.schema,te),M&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=te),x&&this.validateSchema(P,!0),te}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){const H=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=H}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function b(V,P,H,Z="error"){for(const x in V){const M=x;M in P&&this.logger[Z](`${H}: option ${x}. ${V[M]}`)}}function k(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function S(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const P in V)this.addSchema(V[P],P)}function I(){for(const V in this.opts.formats){const P=this.opts.formats[V];P&&this.addFormat(V,P)}}function E(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in V){const H=V[P];H.keyword||(H.keyword=P),this.addKeyword(H)}}function j(){const V={...this.opts};for(const P of g)delete V[P];return V}const O={log(){},warn(){},error(){}};function U(V){if(V===!1)return O;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const A=/^[a-z_$][a-z0-9_$:-]*$/i;function N(V,P){const{RULES:H}=this;if((0,u.eachItem)(V,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`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function G(V,P,H){var Z;const x=P?.post;if(H&&x)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let L=x?M.post:M.rules.find(({type:te})=>te===H);if(L||(L={type:H,rules:[]},M.rules.push(L)),M.keywords[V]=!0,!P)return;const W={keyword:V,definition:{...P,type:(0,c.getJSONTypes)(P.type),schemaType:(0,c.getJSONTypes)(P.schemaType)}};P.before?X.call(this,L,W,P.before):L.rules.push(W),M.all[V]=W,(Z=P.implements)===null||Z===void 0||Z.forEach(te=>this.addKeyword(te))}function X(V,P,H){const Z=V.rules.findIndex(x=>x.keyword===H);Z>=0?V.rules.splice(Z,0,P):(V.rules.push(P),this.logger.warn(`rule ${H} is not defined`))}function Q(V){let{metaSchema:P}=V;P!==void 0&&(V.$data&&this.opts.$data&&(P=he(P)),V.validateSchema=this.compile(P,!0))}const K={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(V){return{anyOf:[V,K]}}})(Ll)),Ll}var Ma={},Oa={},Na={},tf;function kw(){if(tf)return Na;tf=1,Object.defineProperty(Na,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Na.default=e,Na}var mn={},rf;function Tw(){if(rf)return mn;rf=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.callRef=mn.getValidate=void 0;const e=Ra(),t=yr(),r=Oe(),n=hn(),o=Hl(),s=De(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:h,it:p}=c,{baseId:f,schemaEnv:g,validateName:v,opts:y,self:w}=p,{root:_}=g;if((h==="#"||h==="#/")&&f===_.baseId)return C();const m=o.resolveRef.call(w,_,f,h);if(m===void 0)throw new e.default(p.opts.uriResolver,f,h);if(m instanceof o.SchemaEnv)return b(m);return k(m);function C(){if(g===_)return l(c,v,g,g.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function b(S){const I=i(c,S);l(c,I,S,S.$async)}function k(S){const I=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),E=u.name("valid"),j=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:h},E);c.mergeEvaluated(j),c.ok(E)}}};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`}mn.getValidate=i;function l(c,u,h,p){const{gen:f,it:g}=c,{allErrors:v,schemaEnv:y,opts:w}=g,_=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,_)}`),k(u),v||f.assign(S,!0)},I=>{f.if((0,r._)`!(${I} instanceof ${g.ValidationError})`,()=>f.throw(I)),b(I),v||f.assign(S,!1)}),c.ok(S)}function C(){c.result((0,t.callValidateCode)(c,u,_),()=>k(u),()=>b(u))}function b(S){const I=(0,r._)`${S}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(S){var I;if(!g.opts.unevaluated)return;const E=(I=h?.validate)===null||I===void 0?void 0:I.evaluated;if(g.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(g.props=s.mergeEvaluated.props(f,E.props,g.props));else{const j=f.var("props",(0,r._)`${S}.evaluated.props`);g.props=s.mergeEvaluated.props(f,j,g.props,r.Name)}if(g.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(g.items=s.mergeEvaluated.items(f,E.items,g.items));else{const j=f.var("items",(0,r._)`${S}.evaluated.items`);g.items=s.mergeEvaluated.items(f,j,g.items,r.Name)}}}return mn.callRef=l,mn.default=a,mn}var nf;function Cw(){if(nf)return Oa;nf=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=kw(),t=Tw(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Oa.default=r,Oa}var Aa={},qa={},of;function Sw(){if(of)return qa;of=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=Oe(),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 qa.default=o,qa}var La={},sf;function Iw(){if(sf)return La;sf=1,Object.defineProperty(La,"__esModule",{value:!0});const e=Oe(),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 La.default=r,La}var ja={},Da={},af;function Ew(){if(af)return Da;af=1,Object.defineProperty(Da,"__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 Da.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Da}var lf;function xw(){if(lf)return ja;lf=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=Oe(),t=De(),r=Ew(),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 ja.default=o,ja}var Ua={},cf;function $w(){if(cf)return Ua;cf=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=yr(),t=De(),r=Oe(),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),v=a.let("valid");a.try(()=>a.assign(v,(0,r._)`${g}(${u}, ${p}).test(${i})`),()=>a.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${i})`)}}};return Ua.default=o,Ua}var za={},uf;function Rw(){if(uf)return za;uf=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Oe(),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 za.default=r,za}var Za={},df;function Pw(){if(df)return Za;df=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=yr(),t=Oe(),r=De(),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():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:m}=s.it;for(const C of i)if(_?.[C]===void 0&&!m.has(C)){const b=h.schemaEnv.baseId+h.errSchemaPath,k=`required property "${C}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(h,k,h.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function v(){const _=a.let("missing");if(f||u){const m=a.let("valid",!0);s.block$data(m,()=>w(_,m)),s.ok(m)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function y(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,p.ownProperties),()=>s.error())})}function w(_,m){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(m,(0,e.propertyInData)(a,c,_,p.ownProperties)),a.if((0,t.not)(m),()=>{s.error(),a.break()})},t.nil)}}};return Za.default=o,Za}var Fa={},pf;function Mw(){if(pf)return Fa;pf=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Oe(),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 Fa.default=r,Fa}var Va={},Ha={},ff;function Gl(){if(ff)return Ha;ff=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=Zp();return e.code='require("ajv/dist/runtime/equal").default',Ha.default=e,Ha}var hf;function Ow(){if(hf)return Va;hf=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Sa(),t=Oe(),r=De(),n=Gl(),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"),v=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`),b=i.let("j");a.setParams({i:C,j:b}),i.assign(g,!0),i.if((0,t._)`${C} > 1`,()=>(w()?_:m)(C,b))}function w(){return v.length>0&&!v.some(C=>C==="object"||C==="array")}function _(C,b){const k=i.name("item"),S=(0,e.checkDataTypes)(v,k,f.opts.strictNumbers,e.DataType.Wrong),I=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${C}--;`,()=>{i.let(k,(0,t._)`${l}[${C}]`),i.if(S,(0,t._)`continue`),v.length>1&&i.if((0,t._)`typeof ${k} == "string"`,(0,t._)`${k} += "_"`),i.if((0,t._)`typeof ${I}[${k}] == "number"`,()=>{i.assign(b,(0,t._)`${I}[${k}]`),a.error(),i.assign(g,!1).break()}).code((0,t._)`${I}[${k}] = ${C}`)})}function m(C,b){const k=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${C}--;`,()=>i.for((0,t._)`${b} = ${C}; ${b}--;`,()=>i.if((0,t._)`${k}(${l}[${C}], ${l}[${b}])`,()=>{a.error(),i.assign(g,!1).break(S)})))}}};return Va.default=s,Va}var Ba={},mf;function Nw(){if(mf)return Ba;mf=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Oe(),t=De(),r=Gl(),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 Ba.default=o,Ba}var Ja={},gf;function Aw(){if(gf)return Ja;gf=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Oe(),t=De(),r=Gl(),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 v;if(p||l)v=a.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);v=(0,e.or)(...c.map((m,C)=>w(_,C)))}s.pass(v);function y(){a.assign(v,!1),a.forOf("v",u,_=>a.if((0,e._)`${g()}(${i}, ${_})`,()=>a.assign(v,!0).break()))}function w(_,m){const C=c[m];return typeof C=="object"&&C!==null?(0,e._)`${g()}(${i}, ${_}[${m}])`:(0,e._)`${i} === ${C}`}}};return Ja.default=o,Ja}var yf;function qw(){if(yf)return Aa;yf=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Sw(),t=Iw(),r=xw(),n=$w(),o=Rw(),s=Pw(),a=Mw(),i=Ow(),l=Nw(),c=Aw(),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 Aa.default=u,Aa}var Ga={},lo={},vf;function _f(){if(vf)return lo;vf=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.validateAdditionalItems=void 0;const e=Oe(),t=De(),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,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),h.allErrors||i.if((0,e.not)(g),()=>i.break())})}}return lo.validateAdditionalItems=o,lo.default=n,lo}var Wa={},co={},wf;function bf(){if(wf)return co;wf=1,Object.defineProperty(co,"__esModule",{value:!0}),co.validateTuple=void 0;const e=Oe(),t=De(),r=yr(),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;v(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 v(y){const{opts:w,errSchemaPath:_}=p,m=i.length,C=m===y.minItems&&(m===y.maxItems||y[a]===!1);if(w.strictTuples&&!C){const b=`"${h}" is ${m}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return co.validateTuple=o,co.default=n,co}var kf;function Lw(){if(kf)return Wa;kf=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=bf(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Wa.default=t,Wa}var Ka={},Tf;function jw(){if(Tf)return Ka;Tf=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Oe(),t=De(),r=yr(),n=_f(),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 Ka.default=s,Ka}var Ya={},Cf;function Dw(){if(Cf)return Ya;Cf=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Oe(),t=De(),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 v=s.name("valid");h===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),h!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const m=s.name("_valid"),C=s.let("count",0);w(m,()=>s.if(m,()=>_(C)))}function w(m,C){s.forRange("i",0,g,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},m),C()})}function _(m){s.code((0,e._)`${m}++`),h===void 0?s.if((0,e._)`${m} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${m} > ${h}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${m} >= ${u}`,()=>s.assign(v,!0)))}}};return Ya.default=n,Ya}var Wl={},Sf;function Uw(){return Sf||(Sf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Oe(),r=De(),n=yr();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},
|
|
1
|
+
(function(Te,An){typeof exports=="object"&&typeof module<"u"?An(exports):typeof define=="function"&&define.amd?define(["exports"],An):(Te=typeof globalThis<"u"?globalThis:Te||self,An(Te.WebMCP={}))})(this,(function(Te){"use strict";function An(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ca={exports:{}},Vl={},Jr={},qn={},Hl={},Bl={},Jl={},Rp;function Sa(){return Rp||(Rp=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(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((g,C)=>`${g}${C}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((g,C)=>(C instanceof r&&(g[C.str]=(g[C.str]||0)+1),g),{})}}e._Code=n,e.nil=new n("");function o(w,..._){const g=[w[0]];let C=0;for(;C<_.length;)i(g,_[C]),g.push(w[++C]);return new n(g)}e._=o;const s=new n("+");function a(w,..._){const g=[f(w[0])];let C=0;for(;C<_.length;)g.push(s),i(g,_[C]),g.push(s,f(w[++C]));return l(g),new n(g)}e.str=a;function i(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(h(_))}e.addCodeArg=i;function l(w){let _=1;for(;_<w.length-1;){if(w[_]===s){const g=c(w[_-1],w[_+1]);if(g!==void 0){w.splice(_-1,3,g);continue}w[_++]="+"}_++}}function c(w,_){if(_==='""')return w;if(w==='""')return _;if(typeof w=="string")return _ instanceof r||w[w.length-1]!=='"'?void 0:typeof _!="string"?`${w.slice(0,-1)}${_}"`:_[0]==='"'?w.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(w instanceof r))return`"${w}${_.slice(1)}`}function u(w,_){return _.emptyStr()?w:w.emptyStr()?_:a`${w}${_}`}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 m(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=m;function v(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=v;function y(w){return new n(w.toString())}e.regexpCode=y})(Jl)),Jl}var Gl={},Pp;function Mp(){return Pp||(Pp=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,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,m=(h=u.key)!==null&&h!==void 0?h:u.ref;let v=this._values[f];if(v){const _=v.get(m);if(_)return _}else v=this._values[f]=new Map;v.set(m,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 m in c){const v=c[m];if(!v)continue;const y=h[m]=h[m]||new Map;v.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let _=u(w);if(_){const g=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${g} ${w} = ${_};${this.opts._n}`}else if(_=p?.(w))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(Gl)),Gl}var Op;function Oe(){return Op||(Op=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=Mp();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=Mp();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,M){return this}}class a extends s{constructor(E,M,L){super(),this.varKind=E,this.name=M,this.rhs=L}render({es5:E,_n:M}){const L=E?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${L} ${this.name}${W};`+M}optimizeNames(E,M){if(E[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,E,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,M,L){super(),this.lhs=E,this.rhs=M,this.sideEffects=L}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,M){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=N(this.rhs,E,M),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(E,this.rhs)}}class l extends i{constructor(E,M,L,W){super(E,L,W),this.op=M}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class h extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class p extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,M){return this.code=N(this.code,E,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((M,L)=>M+L.render(E),"")}optimizeNodes(){const{nodes:E}=this;let M=E.length;for(;M--;){const L=E[M].optimizeNodes();Array.isArray(L)?E.splice(M,1,...L):L?E[M]=L:E.splice(M,1)}return E.length>0?this:void 0}optimizeNames(E,M){const{nodes:L}=this;let W=L.length;for(;W--;){const te=L[W];te.optimizeNames(E,M)||(G(E,te.names),L.splice(W,1))}return L.length>0?this:void 0}get names(){return this.nodes.reduce((E,M)=>U(E,M.names),{})}}class m extends f{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends f{}class y extends m{}y.kind="else";class w extends m{constructor(E,M){super(M),this.condition=E}render(E){let M=`if(${this.condition})`+super.render(E);return this.else&&(M+="else "+this.else.render(E)),M}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let M=this.else;if(M){const L=M.optimizeNodes();M=this.else=Array.isArray(L)?new y(L):L}if(M)return E===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(X(E),M instanceof w?[M]:M.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,M){var L;if(this.else=(L=this.else)===null||L===void 0?void 0:L.optimizeNames(E,M),!!(super.optimizeNames(E,M)||this.else))return this.condition=N(this.condition,E,M),this}get names(){const E=super.names;return A(E,this.condition),this.else&&U(E,this.else.names),E}}w.kind="if";class _ extends m{}_.kind="for";class g extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iteration=N(this.iteration,E,M),this}get names(){return U(super.names,this.iteration.names)}}class C extends _{constructor(E,M,L,W){super(),this.varKind=E,this.name=M,this.from=L,this.to=W}render(E){const M=E.es5?r.varKinds.var:this.varKind,{name:L,from:W,to:te}=this;return`for(${M} ${L}=${W}; ${L}<${te}; ${L}++)`+super.render(E)}get names(){const E=A(super.names,this.from);return A(E,this.to)}}class b extends _{constructor(E,M,L,W){super(),this.loop=E,this.varKind=M,this.name=L,this.iterable=W}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iterable=N(this.iterable,E,M),this}get names(){return U(super.names,this.iterable.names)}}class k extends m{constructor(E,M,L){super(),this.name=E,this.args=M,this.async=L}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}k.kind="func";class S extends f{render(E){return"return "+super.render(E)}}S.kind="return";class I extends m{render(E){let M="try"+super.render(E);return this.catch&&(M+=this.catch.render(E)),this.finally&&(M+=this.finally.render(E)),M}optimizeNodes(){var E,M;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(E,M){var L,W;return super.optimizeNames(E,M),(L=this.catch)===null||L===void 0||L.optimizeNames(E,M),(W=this.finally)===null||W===void 0||W.optimizeNames(E,M),this}get names(){const E=super.names;return this.catch&&U(E,this.catch.names),this.finally&&U(E,this.finally.names),E}}class x extends m{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}x.kind="catch";class j extends m{render(E){return"finally"+super.render(E)}}j.kind="finally";class O{constructor(E,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
|
|
2
|
+
`:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,M){const L=this._extScope.value(E,M);return(this._values[L.prefix]||(this._values[L.prefix]=new Set)).add(L),L}getScopeValue(E,M){return this._extScope.getValue(E,M)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,M,L,W){const te=this._scope.toName(M);return L!==void 0&&W&&(this._constants[te.str]=L),this._leafNode(new a(E,te,L)),te}const(E,M,L){return this._def(r.varKinds.const,E,M,L)}let(E,M,L){return this._def(r.varKinds.let,E,M,L)}var(E,M,L){return this._def(r.varKinds.var,E,M,L)}assign(E,M,L){return this._leafNode(new i(E,M,L))}add(E,M){return this._leafNode(new l(E,e.operators.ADD,M))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const M=["{"];for(const[L,W]of E)M.length>1&&M.push(","),M.push(L),(L!==W||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,W));return M.push("}"),new t._Code(M)}if(E,M,L){if(this._blockNode(new w(E)),M&&L)this.code(M).else().code(L).endIf();else if(M)this.code(M).endIf();else if(L)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,M){return this._blockNode(E),M&&this.code(M).endFor(),this}for(E,M){return this._for(new g(E),M)}forRange(E,M,L,W,te=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(E);return this._for(new C(te,se,M,L),()=>W(se))}forOf(E,M,L,W=r.varKinds.const){const te=this._scope.toName(E);if(this.opts.es5){const se=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${se}.length`,Se=>{this.var(te,(0,t._)`${se}[${Se}]`),L(te)})}return this._for(new b("of",W,te,M),()=>L(te))}forIn(E,M,L,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${M})`,L);const te=this._scope.toName(E);return this._for(new b("in",W,te,M),()=>L(te))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const M=new S;if(this._blockNode(M),this.code(E),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(E,M,L){if(!M&&!L)throw new Error('CodeGen: "try" without "catch" and "finally"');const W=new I;if(this._blockNode(W),this.code(E),M){const te=this.name("e");this._currNode=W.catch=new x(te),M(te)}return L&&(this._currNode=W.finally=new j,this.code(L)),this._endBlockNode(x,j)}throw(E){return this._leafNode(new h(E))}block(E,M){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(M),this}endBlock(E){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const L=this._nodes.length-M;if(L<0||E!==void 0&&L!==E)throw new Error(`CodeGen: wrong number of nodes: ${L} vs ${E} expected`);return this._nodes.length=M,this}func(E,M=t.nil,L,W){return this._blockNode(new k(E,M,L)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,M){const L=this._currNode;if(L instanceof E||M&&L instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${E.kind}/${M.kind}`:E.kind}"`)}_elseNode(E){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const M=this._nodes;M[M.length-1]=E}}e.CodeGen=O;function U(Z,E){for(const M in E)Z[M]=(Z[M]||0)+(E[M]||0);return Z}function A(Z,E){return E instanceof t._CodeOrName?U(Z,E.names):Z}function N(Z,E,M){if(Z instanceof t.Name)return L(Z);if(!W(Z))return Z;return new t._Code(Z._items.reduce((te,se)=>(se instanceof t.Name&&(se=L(se)),se instanceof t._Code?te.push(...se._items):te.push(se),te),[]));function L(te){const se=M[te.str];return se===void 0||E[te.str]!==1?te:(delete E[te.str],se)}function W(te){return te instanceof t._Code&&te._items.some(se=>se instanceof t.Name&&E[se.str]===1&&M[se.str]!==void 0)}}function G(Z,E){for(const M in E)Z[M]=(Z[M]||0)-(E[M]||0)}function X(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${H(Z)}`}e.not=X;const Q=P(e.operators.AND);function K(...Z){return Z.reduce(Q)}e.and=K;const he=P(e.operators.OR);function V(...Z){return Z.reduce(he)}e.or=V;function P(Z){return(E,M)=>E===t.nil?M:M===t.nil?E:(0,t._)`${H(E)} ${Z} ${H(M)}`}function H(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(Bl)),Bl}var Ne={},Np;function De(){if(Np)return Ne;Np=1,Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.checkStrictMode=Ne.getErrorPath=Ne.Type=Ne.useFunc=Ne.setEvaluated=Ne.evaluatedPropsToName=Ne.mergeEvaluated=Ne.eachItem=Ne.unescapeJsonPointer=Ne.escapeJsonPointer=Ne.escapeFragment=Ne.unescapeFragment=Ne.schemaRefOrVal=Ne.schemaHasRulesButRef=Ne.schemaHasRules=Ne.checkUnknownRules=Ne.alwaysValidSchema=Ne.toHash=void 0;const e=Oe(),t=Sa();function r(b){const k={};for(const S of b)k[S]=!0;return k}Ne.toHash=r;function n(b,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(b,k),!s(k,b.self.RULES.all))}Ne.alwaysValidSchema=n;function o(b,k=b.schema){const{opts:S,self:I}=b;if(!S.strictSchema||typeof k=="boolean")return;const x=I.RULES.keywords;for(const j in k)x[j]||C(b,`unknown keyword: "${j}"`)}Ne.checkUnknownRules=o;function s(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(k[S])return!0;return!1}Ne.schemaHasRules=s;function a(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(S!=="$ref"&&k.all[S])return!0;return!1}Ne.schemaHasRulesButRef=a;function i({topSchemaRef:b,schemaPath:k},S,I,x){if(!x){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${b}${k}${(0,e.getProperty)(I)}`}Ne.schemaRefOrVal=i;function l(b){return h(decodeURIComponent(b))}Ne.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Ne.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Ne.escapeJsonPointer=u;function h(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Ne.unescapeJsonPointer=h;function p(b,k){if(Array.isArray(b))for(const S of b)k(S);else k(b)}Ne.eachItem=p;function f({mergeNames:b,mergeToName:k,mergeValues:S,resultToName:I}){return(x,j,O,U)=>{const A=O===void 0?j:O instanceof e.Name?(j instanceof e.Name?b(x,j,O):k(x,j,O),O):j instanceof e.Name?(k(x,O,j),j):S(j,O);return U===e.Name&&!(A instanceof e.Name)?I(x,A):A}}Ne.mergeEvaluated={props:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>{b.if((0,e._)`${k} === true`,()=>b.assign(S,!0),()=>b.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${k})`))}),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>{k===!0?b.assign(S,!0):(b.assign(S,(0,e._)`${S} || {}`),v(b,S,k))}),mergeValues:(b,k)=>b===!0?!0:{...b,...k},resultToName:m}),items:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>b.assign(S,(0,e._)`${k} === true ? true : ${S} > ${k} ? ${S} : ${k}`)),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>b.assign(S,k===!0?!0:(0,e._)`${S} > ${k} ? ${S} : ${k}`)),mergeValues:(b,k)=>b===!0?!0:Math.max(b,k),resultToName:(b,k)=>b.var("items",k)})};function m(b,k){if(k===!0)return b.var("props",!0);const S=b.var("props",(0,e._)`{}`);return k!==void 0&&v(b,S,k),S}Ne.evaluatedPropsToName=m;function v(b,k,S){Object.keys(S).forEach(I=>b.assign((0,e._)`${k}${(0,e.getProperty)(I)}`,!0))}Ne.setEvaluated=v;const y={};function w(b,k){return b.scopeValue("func",{ref:k,code:y[k.code]||(y[k.code]=new t._Code(k.code))})}Ne.useFunc=w;var _;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(_||(Ne.Type=_={}));function g(b,k,S){if(b instanceof e.Name){const I=k===_.Num;return S?I?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:I?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(b).toString():"/"+u(b)}Ne.getErrorPath=g;function C(b,k,S=b.opts.strictSchema){if(S){if(k=`strict mode: ${k}`,S===!0)throw new Error(k);b.self.logger.warn(k)}}return Ne.checkStrictMode=C,Ne}var Ia={},Ap;function mn(){if(Ap)return Ia;Ap=1,Object.defineProperty(Ia,"__esModule",{value:!0});const e=Oe(),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 Ia.default=t,Ia}var qp;function xa(){return qp||(qp=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=Oe(),r=De(),n=mn();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,_,g){const{it:C}=y,{gen:b,compositeRule:k,allErrors:S}=C,I=h(y,w,_);g??(k||S)?l(b,I):c(C,(0,t._)`[${I}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:g}=y,{gen:C,compositeRule:b,allErrors:k}=g,S=h(y,w,_);l(C,S),b||k||c(g,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:_,data:g,errsCount:C,it:b}){if(C===void 0)throw new Error("ajv implementation error");const k=y.name("err");y.forRange("i",C,n.default.errors,S=>{y.const(k,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${k}.instancePath === undefined`,()=>y.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),y.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(y.assign((0,t._)`${k}.schema`,_),y.assign((0,t._)`${k}.data`,g))})}e.extendErrors=i;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:g,schemaEnv:C}=y;C.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${g}.errors`,w),_.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,_){const{createErrors:g}=y.it;return g===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:g,it:C}=y,b=[f(C,_),m(y,_)];return v(y,w,b),g.object(...b)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function m({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:g}){let C=g?w:(0,t.str)`${w}/${y}`;return _&&(C=(0,t.str)`${C}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,C]}function v(y,{params:w,message:_},g){const{keyword:C,data:b,schemaValue:k,it:S}=y,{opts:I,propertyName:x,topSchemaRef:j,schemaPath:O}=S;g.push([u.keyword,C],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),I.messages&&g.push([u.message,typeof _=="function"?_(y):_]),I.verbose&&g.push([u.schema,k],[u.parentSchema,(0,t._)`${j}${O}`],[n.default.data,b]),x&&g.push([u.propertyName,x])}})(Hl)),Hl}var Lp;function vw(){if(Lp)return qn;Lp=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;const e=xa(),t=Oe(),r=mn(),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))}qn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}qn.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 qn}var $t={},Ln={},jp;function Dp(){if(jp)return Ln;jp=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.getRules=Ln.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)}Ln.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 Ln.getRules=n,Ln}var Gr={},Up;function zp(){if(Up)return Gr;Up=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.shouldUseRule=Gr.shouldUseGroup=Gr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Gr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Gr.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 Gr.shouldUseRule=r,Gr}var Zp;function Ea(){if(Zp)return $t;Zp=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=Dp(),t=zp(),r=xa(),n=Oe(),o=De();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||($t.DataType=s={}));function a(_){const g=i(_.type);if(g.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&g.push("null")}return g}$t.getSchemaTypes=a;function i(_){const g=Array.isArray(_)?_:_?[_]:[];if(g.every(e.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}$t.getJSONTypes=i;function l(_,g){const{gen:C,data:b,opts:k}=_,S=u(g,k.coerceTypes),I=g.length>0&&!(S.length===0&&g.length===1&&(0,t.schemaHasRulesForType)(_,g[0]));if(I){const x=m(g,b,k.strictNumbers,s.Wrong);C.if(x,()=>{S.length?h(_,g,S):y(_)})}return I}$t.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,g){return g?_.filter(C=>c.has(C)||g==="array"&&C==="array"):[]}function h(_,g,C){const{gen:b,data:k,opts:S}=_,I=b.let("dataType",(0,n._)`typeof ${k}`),x=b.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&b.if((0,n._)`${I} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>b.assign(k,(0,n._)`${k}[0]`).assign(I,(0,n._)`typeof ${k}`).if(m(g,k,S.strictNumbers),()=>b.assign(x,k))),b.if((0,n._)`${x} !== undefined`);for(const O of C)(c.has(O)||O==="array"&&S.coerceTypes==="array")&&j(O);b.else(),y(_),b.endIf(),b.if((0,n._)`${x} !== undefined`,()=>{b.assign(k,x),p(_,x)});function j(O){switch(O){case"string":b.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(x,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(x,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${I} == "boolean" || ${k} === null
|
|
3
|
+
|| (${I} == "string" && ${k} && ${k} == +${k})`).assign(x,(0,n._)`+${k}`);return;case"integer":b.elseIf((0,n._)`${I} === "boolean" || ${k} === null
|
|
4
|
+
|| (${I} === "string" && ${k} && ${k} == +${k} && !(${k} % 1))`).assign(x,(0,n._)`+${k}`);return;case"boolean":b.elseIf((0,n._)`${k} === "false" || ${k} === 0 || ${k} === null`).assign(x,!1).elseIf((0,n._)`${k} === "true" || ${k} === 1`).assign(x,!0);return;case"null":b.elseIf((0,n._)`${k} === "" || ${k} === 0 || ${k} === false`),b.assign(x,null);return;case"array":b.elseIf((0,n._)`${I} === "string" || ${I} === "number"
|
|
5
|
+
|| ${I} === "boolean" || ${k} === null`).assign(x,(0,n._)`[${k}]`)}}}function p({gen:_,parentData:g,parentDataProperty:C},b){_.if((0,n._)`${g} !== undefined`,()=>_.assign((0,n._)`${g}[${C}]`,b))}function f(_,g,C,b=s.Correct){const k=b===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${g} ${k} null`;case"array":S=(0,n._)`Array.isArray(${g})`;break;case"object":S=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":S=I((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":S=I();break;default:return(0,n._)`typeof ${g} ${k} ${_}`}return b===s.Correct?S:(0,n.not)(S);function I(x=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,x,C?(0,n._)`isFinite(${g})`:n.nil)}}$t.checkDataType=f;function m(_,g,C,b){if(_.length===1)return f(_[0],g,C,b);let k;const S=(0,o.toHash)(_);if(S.array&&S.object){const I=(0,n._)`typeof ${g} != "object"`;k=S.null?I:(0,n._)`!${g} || ${I}`,delete S.null,delete S.array,delete S.object}else k=n.nil;S.number&&delete S.integer;for(const I in S)k=(0,n.and)(k,f(I,g,C,b));return k}$t.checkDataTypes=m;const v={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:g})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${g}}`};function y(_){const g=w(_);(0,r.reportError)(g,v)}$t.reportTypeError=y;function w(_){const{gen:g,data:C,schema:b}=_,k=(0,o.schemaRefOrVal)(_,b,"type");return{gen:g,keyword:"type",data:C,schema:b.type,schemaCode:k,schemaValue:k,parentSchema:b,params:{},it:_}}return $t}var Wo={},Fp;function _w(){if(Fp)return Wo;Fp=1,Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.assignDefaults=void 0;const e=Oe(),t=De();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))}Wo.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 Wo}var gr={},Be={},Vp;function yr(){if(Vp)return Be;Vp=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=Oe(),t=De(),r=mn(),n=De();function o(_,g){const{gen:C,data:b,it:k}=_;C.if(u(C,b,g,k.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${g}`},!0),_.error()})}Be.checkReportMissingProp=o;function s({gen:_,data:g,it:{opts:C}},b,k){return(0,e.or)(...b.map(S=>(0,e.and)(u(_,g,S,C.ownProperties),(0,e._)`${k} = ${S}`)))}Be.checkMissingProp=s;function a(_,g){_.setParams({missingProperty:g},!0),_.error()}Be.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Be.hasPropFunc=i;function l(_,g,C){return(0,e._)`${i(_)}.call(${g}, ${C})`}Be.isOwnProperty=l;function c(_,g,C,b){const k=(0,e._)`${g}${(0,e.getProperty)(C)} !== undefined`;return b?(0,e._)`${k} && ${l(_,g,C)}`:k}Be.propertyInData=c;function u(_,g,C,b){const k=(0,e._)`${g}${(0,e.getProperty)(C)} === undefined`;return b?(0,e.or)(k,(0,e.not)(l(_,g,C))):k}Be.noPropertyInData=u;function h(_){return _?Object.keys(_).filter(g=>g!=="__proto__"):[]}Be.allSchemaProperties=h;function p(_,g){return h(g).filter(C=>!(0,t.alwaysValidSchema)(_,g[C]))}Be.schemaProperties=p;function f({schemaCode:_,data:g,it:{gen:C,topSchemaRef:b,schemaPath:k,errorPath:S},it:I},x,j,O){const U=O?(0,e._)`${_}, ${g}, ${b}${k}`:g,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const N=(0,e._)`${U}, ${C.object(...A)}`;return j!==e.nil?(0,e._)`${x}.call(${j}, ${N})`:(0,e._)`${x}(${N})`}Be.callValidateCode=f;const m=(0,e._)`new RegExp`;function v({gen:_,it:{opts:g}},C){const b=g.unicodeRegExp?"u":"",{regExp:k}=g.code,S=k(C,b);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${k.code==="new RegExp"?m:(0,n.useFunc)(_,k)}(${C}, ${b})`})}Be.usePattern=v;function y(_){const{gen:g,data:C,keyword:b,it:k}=_,S=g.name("valid");if(k.allErrors){const x=g.let("valid",!0);return I(()=>g.assign(x,!1)),x}return g.var(S,!0),I(()=>g.break()),S;function I(x){const j=g.const("len",(0,e._)`${C}.length`);g.forRange("i",0,j,O=>{_.subschema({keyword:b,dataProp:O,dataPropType:t.Type.Num},S),g.if((0,e.not)(S),x)})}}Be.validateArray=y;function w(_){const{gen:g,schema:C,keyword:b,it:k}=_;if(!Array.isArray(C))throw new Error("ajv implementation error");if(C.some(j=>(0,t.alwaysValidSchema)(k,j))&&!k.opts.unevaluated)return;const I=g.let("valid",!1),x=g.name("_valid");g.block(()=>C.forEach((j,O)=>{const U=_.subschema({keyword:b,schemaProp:O,compositeRule:!0},x);g.assign(I,(0,e._)`${I} || ${x}`),_.mergeValidEvaluated(U,x)||g.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Be.validateUnion=w,Be}var Hp;function ww(){if(Hp)return gr;Hp=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.validateKeywordUsage=gr.validSchemaType=gr.funcKeywordCode=gr.macroKeywordCode=void 0;const e=Oe(),t=mn(),r=yr(),n=xa();function o(p,f){const{gen:m,keyword:v,schema:y,parentSchema:w,it:_}=p,g=f.macro.call(_.self,y,w,_),C=c(m,v,g);_.opts.validateSchema!==!1&&_.self.validateSchema(g,!0);const b=m.name("valid");p.subschema({schema:g,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:C,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}gr.macroKeywordCode=o;function s(p,f){var m;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:g,it:C}=p;l(C,f);const b=!g&&f.compile?f.compile.call(C.self,w,_,C):f.validate,k=c(v,y,b),S=v.let("valid");p.block$data(S,I),p.ok((m=f.valid)!==null&&m!==void 0?m:S);function I(){if(f.errors===!1)O(),f.modifying&&a(p),U(()=>p.error());else{const A=f.async?x():j();f.modifying&&a(p),U(()=>i(p,A))}}function x(){const A=v.let("ruleErrs",null);return v.try(()=>O((0,e._)`await `),N=>v.assign(S,!1).if((0,e._)`${N} instanceof ${C.ValidationError}`,()=>v.assign(A,(0,e._)`${N}.errors`),()=>v.throw(N))),A}function j(){const A=(0,e._)`${k}.errors`;return v.assign(A,null),O(e.nil),A}function O(A=f.async?(0,e._)`await `:e.nil){const N=C.opts.passContext?t.default.this:t.default.self,G=!("compile"in f&&!g||f.schema===!1);v.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,k,N,G)}`,f.modifying)}function U(A){var N;v.if((0,e.not)((N=f.valid)!==null&&N!==void 0?N:S),A)}}gr.funcKeywordCode=s;function a(p){const{gen:f,data:m,it:v}=p;f.if(v.parentData,()=>f.assign(m,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function i(p,f){const{gen:m}=p;m.if((0,e._)`Array.isArray(${f})`,()=>{m.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,m){if(m===void 0)throw new Error(`keyword "${f}" failed to compile`);return p.scopeValue("keyword",typeof m=="function"?{ref:m}:{ref:m,code:(0,e.stringify)(m)})}function u(p,f,m=!1){return!f.length||f.some(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||m&&typeof p>"u")}gr.validSchemaType=u;function h({schema:p,opts:f,self:m,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(g=>!Object.prototype.hasOwnProperty.call(p,g)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const C=`keyword "${w}" value is invalid at path "${v}": `+m.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")m.logger.error(C);else throw new Error(C)}}return gr.validateKeywordUsage=h,gr}var Wr={},Bp;function bw(){if(Bp)return Wr;Bp=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.getSubschema=void 0;const e=Oe(),t=De();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')}Wr.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:m,dataPathArr:v,opts:y}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);f(w),s.errorPath=(0,e.str)`${m}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const m=c instanceof e.Name?c:p.let("data",c,!0);f(m),h!==void 0&&(s.propertyName=h)}u&&(s.dataTypes=u);function f(m){s.data=m,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,m]}}Wr.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 Wr.extendSubschemaMode=o,Wr}var Dt={},Wl,Jp;function Gp(){return Jp||(Jp=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 Kl={exports:{}},Wp;function kw(){if(Wp)return Kl.exports;Wp=1;var e=Kl.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 m=a[f];if(Array.isArray(m)){if(f in e.arrayKeywords)for(var v=0;v<m.length;v++)t(n,o,s,m[v],i+"/"+f+"/"+v,l,i,f,a,v)}else if(f in e.propsKeywords){if(m&&typeof m=="object")for(var y in m)t(n,o,s,m[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,m,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 Kl.exports}var Kp;function $a(){if(Kp)return Dt;Kp=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;const e=De(),t=Gp(),r=kw(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,y=!0){return typeof v=="boolean"?!0:y===!0?!a(v):y?i(v)<=y:!1}Dt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let y=0;for(const w in v){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],_=>y+=i(_)),y===1/0))return 1/0}return y}function l(v,y="",w){w!==!1&&(y=h(y));const _=v.parse(y);return c(v,_)}Dt.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}Dt._getFullPath=c;const u=/#\/?$/;function h(v){return v?v.replace(u,""):""}Dt.normalizeId=h;function p(v,y,w){return w=h(w),v.resolve(y,w)}Dt.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function m(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,g=h(v[w]||y),C={"":g},b=l(_,g,!1),k={},S=new Set;return r(v,{allKeys:!0},(j,O,U,A)=>{if(A===void 0)return;const N=b+O;let G=C[A];typeof j[w]=="string"&&(G=X.call(this,j[w])),Q.call(this,j.$anchor),Q.call(this,j.$dynamicAnchor),C[O]=G;function X(K){const he=this.opts.uriResolver.resolve;if(K=h(G?he(G,K):K),S.has(K))throw x(K);S.add(K);let V=this.refs[K];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(j,V.schema,K):K!==h(N)&&(K[0]==="#"?(I(j,k[K],K),k[K]=j):this.refs[K]=N),K}function Q(K){if(typeof K=="string"){if(!f.test(K))throw new Error(`invalid anchor "${K}"`);X.call(this,`#${K}`)}}}),k;function I(j,O,U){if(O!==void 0&&!t(j,O))throw x(U)}function x(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Dt.getSchemaRefs=m,Dt}var Yp;function Ra(){if(Yp)return Jr;Yp=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=vw(),t=Ea(),r=zp(),n=Ea(),o=_w(),s=ww(),a=bw(),i=Oe(),l=mn(),c=$a(),u=De(),h=xa();function p(z){if(b(z)&&(S(z),C(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Jr.validateFunctionCode=p;function f({gen:z,validateName:F,schema:Y,schemaEnv:ee,opts:ue},xe){ue.code.es5?z.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,ee.$async,()=>{z.code((0,i._)`"use strict"; ${_(Y,ue)}`),v(z,ue),z.code(xe)}):z.func(F,(0,i._)`${l.default.data}, ${m(ue)}`,ee.$async,()=>z.code(_(Y,ue)).code(xe))}function m(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 v(z,F){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,i._)`""`),z.var(l.default.parentData,(0,i._)`undefined`),z.var(l.default.parentDataProperty,(0,i._)`undefined`),z.var(l.default.rootData,l.default.data),F.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(z){const{schema:F,opts:Y,gen:ee}=z;f(z,()=>{Y.$comment&&F.$comment&&A(z),j(z),ee.let(l.default.vErrors,null),ee.let(l.default.errors,0),Y.unevaluated&&w(z),I(z),N(z)})}function w(z){const{gen:F,validateName:Y}=z;z.evaluated=F.const("evaluated",(0,i._)`${Y}.evaluated`),F.if((0,i._)`${z.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${z.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${z.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${z.evaluated}.items`,(0,i._)`undefined`))}function _(z,F){const Y=typeof z=="object"&&z[F.schemaId];return Y&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${Y} */`:i.nil}function g(z,F){if(b(z)&&(S(z),C(z))){k(z,F);return}(0,e.boolOrEmptySchema)(z,F)}function C({schema:z,self:F}){if(typeof z=="boolean")return!z;for(const Y in z)if(F.RULES.all[Y])return!0;return!1}function b(z){return typeof z.schema!="boolean"}function k(z,F){const{schema:Y,gen:ee,opts:ue}=z;ue.$comment&&Y.$comment&&A(z),O(z),U(z);const xe=ee.const("_errs",l.default.errors);I(z,xe),ee.var(F,(0,i._)`${xe} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),x(z)}function I(z,F){if(z.opts.jtd)return X(z,[],!1,F);const Y=(0,t.getSchemaTypes)(z.schema),ee=(0,t.coerceAndCheckDataType)(z,Y);X(z,Y,!ee,F)}function x(z){const{schema:F,errSchemaPath:Y,opts:ee,self:ue}=z;F.$ref&&ee.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,ue.RULES)&&ue.logger.warn(`$ref: keywords ignored in schema at path "${Y}"`)}function j(z){const{schema:F,opts:Y}=z;F.default!==void 0&&Y.useDefaults&&Y.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function O(z){const F=z.schema[z.opts.schemaId];F&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,F))}function U(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:F,schema:Y,errSchemaPath:ee,opts:ue}){const xe=Y.$comment;if(ue.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${xe})`);else if(typeof ue.$comment=="function"){const He=(0,i.str)`${ee}/$comment`,ot=z.scopeValue("root",{ref:F.root});z.code((0,i._)`${l.default.self}.opts.$comment(${xe}, ${He}, ${ot}.schema)`)}}function N(z){const{gen:F,schemaEnv:Y,validateName:ee,ValidationError:ue,opts:xe}=z;Y.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${ue}(${l.default.vErrors})`)):(F.assign((0,i._)`${ee}.errors`,l.default.vErrors),xe.unevaluated&&G(z),F.return((0,i._)`${l.default.errors} === 0`))}function G({gen:z,evaluated:F,props:Y,items:ee}){Y instanceof i.Name&&z.assign((0,i._)`${F}.props`,Y),ee instanceof i.Name&&z.assign((0,i._)`${F}.items`,ee)}function X(z,F,Y,ee){const{gen:ue,schema:xe,data:He,allErrors:ot,opts:ft,self:et}=z,{RULES:$}=et;if(xe.$ref&&(ft.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(xe,$))){ue.block(()=>W(z,"$ref",$.all.$ref.definition));return}ft.jtd||K(z,F),ue.block(()=>{for(const Le of $.rules)ne(Le);ne($.post)});function ne(Le){(0,r.shouldUseGroup)(xe,Le)&&(Le.type?(ue.if((0,n.checkDataType)(Le.type,He,ft.strictNumbers)),Q(z,Le),F.length===1&&F[0]===Le.type&&Y&&(ue.else(),(0,n.reportTypeError)(z)),ue.endIf()):Q(z,Le),ot||ue.if((0,i._)`${l.default.errors} === ${ee||0}`))}}function Q(z,F){const{gen:Y,schema:ee,opts:{useDefaults:ue}}=z;ue&&(0,o.assignDefaults)(z,F.type),Y.block(()=>{for(const xe of F.rules)(0,r.shouldUseRule)(ee,xe)&&W(z,xe.keyword,xe.definition,F.type)})}function K(z,F){z.schemaEnv.meta||!z.opts.strictTypes||(he(z,F),z.opts.allowUnionTypes||V(z,F),P(z,z.dataTypes))}function he(z,F){if(F.length){if(!z.dataTypes.length){z.dataTypes=F;return}F.forEach(Y=>{Z(z.dataTypes,Y)||M(z,`type "${Y}" not allowed by context "${z.dataTypes.join(",")}"`)}),E(z,F)}}function V(z,F){F.length>1&&!(F.length===2&&F.includes("null"))&&M(z,"use allowUnionTypes to allow union type keyword")}function P(z,F){const Y=z.self.RULES.all;for(const ee in Y){const ue=Y[ee];if(typeof ue=="object"&&(0,r.shouldUseRule)(z.schema,ue)){const{type:xe}=ue.definition;xe.length&&!xe.some(He=>H(F,He))&&M(z,`missing type "${xe.join(",")}" for keyword "${ee}"`)}}}function H(z,F){return z.includes(F)||F==="number"&&z.includes("integer")}function Z(z,F){return z.includes(F)||F==="integer"&&z.includes("number")}function E(z,F){const Y=[];for(const ee of z.dataTypes)Z(F,ee)?Y.push(ee):F.includes("integer")&&ee==="number"&&Y.push("integer");z.dataTypes=Y}function M(z,F){const Y=z.schemaEnv.baseId+z.errSchemaPath;F+=` at "${Y}" (strictTypes)`,(0,u.checkStrictMode)(z,F,z.opts.strictTypes)}class L{constructor(F,Y,ee){if((0,s.validateKeywordUsage)(F,Y,ee),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=ee,this.data=F.data,this.schema=F.schema[ee],this.$data=Y.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,ee,this.$data),this.schemaType=Y.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=Y,this.$data)this.schemaCode=F.gen.const("vSchema",Se(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,Y.schemaType,Y.allowUndefined))throw new Error(`${ee} value must be ${JSON.stringify(Y.schemaType)}`);("code"in Y?Y.trackErrors:Y.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,Y,ee){this.failResult((0,i.not)(F),Y,ee)}failResult(F,Y,ee){this.gen.if(F),ee?ee():this.error(),Y?(this.gen.else(),Y(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,Y){this.failResult((0,i.not)(F),void 0,Y)}fail(F){if(F===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(F),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(F){if(!this.$data)return this.fail(F);const{schemaCode:Y}=this;this.fail((0,i._)`${Y} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,Y,ee){if(Y){this.setParams(Y),this._error(F,ee),this.setParams({});return}this._error(F,ee)}_error(F,Y){(F?h.reportExtraError:h.reportError)(this,this.def.error,Y)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,Y){Y?Object.assign(this.params,F):this.params=F}block$data(F,Y,ee=i.nil){this.gen.block(()=>{this.check$data(F,ee),Y()})}check$data(F=i.nil,Y=i.nil){if(!this.$data)return;const{gen:ee,schemaCode:ue,schemaType:xe,def:He}=this;ee.if((0,i.or)((0,i._)`${ue} === undefined`,Y)),F!==i.nil&&ee.assign(F,!0),(xe.length||He.validateSchema)&&(ee.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&ee.assign(F,!1)),ee.else()}invalid$data(){const{gen:F,schemaCode:Y,schemaType:ee,def:ue,it:xe}=this;return(0,i.or)(He(),ot());function He(){if(ee.length){if(!(Y instanceof i.Name))throw new Error("ajv implementation error");const ft=Array.isArray(ee)?ee:[ee];return(0,i._)`${(0,n.checkDataTypes)(ft,Y,xe.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function ot(){if(ue.validateSchema){const ft=F.scopeValue("validate$data",{ref:ue.validateSchema});return(0,i._)`!${ft}(${Y})`}return i.nil}}subschema(F,Y){const ee=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(ee,this.it,F),(0,a.extendSubschemaMode)(ee,F);const ue={...this.it,...ee,items:void 0,props:void 0};return g(ue,Y),ue}mergeEvaluated(F,Y){const{it:ee,gen:ue}=this;ee.opts.unevaluated&&(ee.props!==!0&&F.props!==void 0&&(ee.props=u.mergeEvaluated.props(ue,F.props,ee.props,Y)),ee.items!==!0&&F.items!==void 0&&(ee.items=u.mergeEvaluated.items(ue,F.items,ee.items,Y)))}mergeValidEvaluated(F,Y){const{it:ee,gen:ue}=this;if(ee.opts.unevaluated&&(ee.props!==!0||ee.items!==!0))return ue.if(Y,()=>this.mergeEvaluated(F,i.Name)),!0}}Jr.KeywordCxt=L;function W(z,F,Y,ee){const ue=new L(z,Y,F);"code"in Y?Y.code(ue,ee):ue.$data&&Y.validate?(0,s.funcKeywordCode)(ue,Y):"macro"in Y?(0,s.macroKeywordCode)(ue,Y):(Y.compile||Y.validate)&&(0,s.funcKeywordCode)(ue,Y)}const te=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Se(z,{dataLevel:F,dataNames:Y,dataPathArr:ee}){let ue,xe;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!te.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);ue=z,xe=l.default.rootData}else{const et=se.exec(z);if(!et)throw new Error(`Invalid JSON-pointer: ${z}`);const $=+et[1];if(ue=et[2],ue==="#"){if($>=F)throw new Error(ft("property/index",$));return ee[F-$]}if($>F)throw new Error(ft("data",$));if(xe=Y[F-$],!ue)return xe}let He=xe;const ot=ue.split("/");for(const et of ot)et&&(xe=(0,i._)`${xe}${(0,i.getProperty)((0,u.unescapeJsonPointer)(et))}`,He=(0,i._)`${He} && ${xe}`);return He;function ft(et,$){return`Cannot access ${et} ${$} levels up, current level is ${F}`}}return Jr.getData=Se,Jr}var Pa={},Qp;function Yl(){if(Qp)return Pa;Qp=1,Object.defineProperty(Pa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Pa.default=e,Pa}var Ma={},Xp;function Oa(){if(Xp)return Ma;Xp=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=$a();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 Ma.default=t,Ma}var er={},ef;function Ql(){if(ef)return er;ef=1,Object.defineProperty(er,"__esModule",{value:!0}),er.resolveSchema=er.getCompilingSchema=er.resolveRef=er.compileSchema=er.SchemaEnv=void 0;const e=Oe(),t=Yl(),r=mn(),n=$a(),o=De(),s=Ra();class a{constructor(w){var _;this.refs={},this.dynamicAnchors={};let g;typeof w.schema=="object"&&(g=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(_=w.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(g?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=g?.$async,this.refs={}}}er.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:g,lines:C}=this.opts.code,{ownProperties:b}=this.opts,k=new e.CodeGen(this.scope,{es5:g,lines:C,ownProperties:b});let S;y.$async&&(S=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=k.scopeName("validate");y.validateName=I;const x={gen:k,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:k.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:I,ValidationError:S,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,s.validateFunctionCode)(x),k.optimize(this.opts.code.optimize);const O=k.toString();j=`${k.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(I,{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:I,validateCode:O,scopeValues:k._values}),this.opts.unevaluated){const{props:N,items:G}=x;A.evaluated={props:N instanceof e.Name?void 0:N,items:G instanceof e.Name?void 0:G,dynamicProps:N instanceof e.Name,dynamicItems:G instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch(O){throw delete y.validate,delete y.validateName,j&&this.logger.error("Error compiling schema, function code:",j),O}finally{this._compilations.delete(y)}}er.compileSchema=i;function l(y,w,_){var g;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const C=y.refs[_];if(C)return C;let b=p.call(this,y,_);if(b===void 0){const k=(g=y.localRefs)===null||g===void 0?void 0:g[_],{schemaId:S}=this.opts;k&&(b=new a({schema:k,schemaId:S,root:y,baseId:w}))}if(b!==void 0)return y.refs[_]=c.call(this,b)}er.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}er.getCompilingSchema=u;function h(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),g=(0,n._getFullPath)(this.opts.uriResolver,_);let C=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&g===C)return v.call(this,_,y);const b=(0,n.normalizeId)(g),k=this.refs[b]||this.schemas[b];if(typeof k=="string"){const S=f.call(this,y,k);return typeof S?.schema!="object"?void 0:v.call(this,_,S)}if(typeof k?.schema=="object"){if(k.validate||i.call(this,k),b===(0,n.normalizeId)(w)){const{schema:S}=k,{schemaId:I}=this.opts,x=S[I];return x&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,x)),new a({schema:S,schemaId:I,root:y,baseId:C})}return v.call(this,_,k)}}er.resolveSchema=f;const m=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,root:g}){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 _=="boolean")return;const I=_[(0,o.unescapeFragment)(S)];if(I===void 0)return;_=I;const x=typeof _=="object"&&_[this.opts.schemaId];!m.has(S)&&x&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,x))}let b;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);b=f.call(this,g,S)}const{schemaId:k}=this.opts;if(b=b||new a({schema:_,schemaId:k,root:g,baseId:w}),b.schema!==b.root.schema)return b}return er}const Tw={$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 Na={},Ko={exports:{}},Xl,tf;function rf(){if(tf)return Xl;tf=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="",m=0,v=0;for(v=0;v<p.length;v++)if(m=p[v].charCodeAt(0),m!==48){if(!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";f+=p[v];break}for(v+=1;v<p.length;v++){if(m=p[v].charCodeAt(0),!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";f+=p[v]}return f}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,f,m){if(p.length){const v=r(p);if(v!=="")f.push(v);else return m.error=!0,!1;p.length=0}return!0}function a(p){let f=0;const m={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,g=s;for(let C=0;C<p.length;C++){const b=p[C];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(_=!0),!g(y,v,m))break;if(++f>7){m.error=!0;break}C>0&&p[C-1]===":"&&(w=!0),v.push(":");continue}else if(b==="%"){if(!g(y,v,m))break;g=o}else{y.push(b);continue}}return y.length&&(g===o?m.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),m.address=v.join(""),m}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 m=f.address,v=f.address;return f.zone&&(m+="%"+f.zone,v+="%25"+f.zone),{host:m,isIPV6:!0,escapedHost:v}}}function l(p,f){let m=0;for(let v=0;v<p.length;v++)p[v]===f&&m++;return m}function c(p){let f=p;const m=[];let v=-1,y=0;for(;y=f.length;){if(y===1){if(f===".")break;if(f==="/"){m.push("/");break}else{m.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]==="/")){m.push("/");break}}else if(y===3&&f==="/.."){m.length!==0&&m.pop(),m.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),m.length!==0&&m.pop();continue}}if((v=f.indexOf("/",1))===-1){m.push(f);break}else m.push(f.slice(0,v)),f=f.slice(v)}return m.join("")}function u(p,f){const m=f!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=m(p.scheme)),p.userinfo!==void 0&&(p.userinfo=m(p.userinfo)),p.host!==void 0&&(p.host=m(p.host)),p.path!==void 0&&(p.path=m(p.path)),p.query!==void 0&&(p.query=m(p.query)),p.fragment!==void 0&&(p.fragment=m(p.fragment)),p}function h(p){const f=[];if(p.userinfo!==void 0&&(f.push(p.userinfo),f.push("@")),p.host!==void 0){let m=unescape(p.host);if(!t(m)){const v=i(m);v.isIPV6===!0?m=`[${v.escapedHost}]`:m=p.host}f.push(m)}return(typeof p.port=="number"||typeof p.port=="string")&&(f.push(":"),f.push(String(p.port))),f.length?f.join(""):void 0}return Xl={nonSimpleDomain:n,recomposeAuthority:h,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},Xl}var ec,nf;function Cw(){if(nf)return ec;nf=1;const{isUUID:e}=rf(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function a(b){const k=String(b.scheme).toLowerCase()==="https";return(b.port===(k?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function i(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[k,S]=b.resourceName.split("?");b.path=k&&k!=="/"?k:void 0,b.query=S,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,k){if(!b.path)return b.error="URN can not be parsed",b;const S=b.path.match(t);if(S){const I=k.scheme||b.scheme||"urn";b.nid=S[1].toLowerCase(),b.nss=S[2];const x=`${I}:${k.nid||b.nid}`,j=C(x);b.path=void 0,j&&(b=j.parse(b,k))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,k){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=k.scheme||b.scheme||"urn",I=b.nid.toLowerCase(),x=`${S}:${k.nid||I}`,j=C(x);j&&(b=j.serialize(b,k));const O=b,U=b.nss;return O.path=`${I||k.nid}:${U}`,k.skipEscape=!0,O}function h(b,k){const S=b;return S.uuid=S.nss,S.nss=void 0,!k.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(b){const k=b;return k.nss=(b.uuid||"").toLowerCase(),k}const f={scheme:"http",domainHost:!0,parse:s,serialize:a},m={scheme:"https",domainHost:f.domainHost,parse:s,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},g={http:f,https:m,ws:v,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(g,null);function C(b){return b&&(g[b]||g[b.toLowerCase()])||void 0}return ec={wsIsSecure:o,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:C},ec}var of;function Sw(){if(of)return Ko.exports;of=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=rf(),{SCHEMES:a,getSchemeHandler:i}=Cw();function l(y,w){return typeof y=="string"?y=p(m(y,w),w):typeof y=="object"&&(y=m(p(y,w),w)),y}function c(y,w,_){const g=_?Object.assign({scheme:"null"},_):{scheme:"null"},C=u(m(y,g),m(w,g),g,!0);return g.skipEscape=!0,p(C,g)}function u(y,w,_,g){const C={};return g||(y=m(p(y,_),_),w=m(p(w,_),_)),_=_||{},!_.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,_){return typeof y=="string"?(y=unescape(y),y=p(n(m(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(m(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={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:""},g=Object.assign({},w),C=[],b=i(g.scheme||_.scheme);b&&b.serialize&&b.serialize(_,g),_.path!==void 0&&(g.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),g.reference!=="suffix"&&_.scheme&&C.push(_.scheme,":");const k=r(_);if(k!==void 0&&(g.reference!=="suffix"&&C.push("//"),C.push(k),_.path&&_.path[0]!=="/"&&C.push("/")),_.path!==void 0){let S=_.path;!g.absolutePath&&(!b||!b.absolutePath)&&(S=t(S)),k===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),C.push(S)}return _.query!==void 0&&C.push("?",_.query),_.fragment!==void 0&&C.push("#",_.fragment),C.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(y,w){const _=Object.assign({},w),g={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let C=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const b=y.match(f);if(b){if(g.scheme=b[1],g.userinfo=b[3],g.host=b[4],g.port=parseInt(b[5],10),g.path=b[6]||"",g.query=b[7],g.fragment=b[8],isNaN(g.port)&&(g.port=b[5]),g.host)if(o(g.host)===!1){const I=e(g.host);g.host=I.host.toLowerCase(),C=I.isIPV6}else C=!0;g.scheme===void 0&&g.userinfo===void 0&&g.host===void 0&&g.port===void 0&&g.query===void 0&&!g.path?g.reference="same-document":g.scheme===void 0?g.reference="relative":g.fragment===void 0?g.reference="absolute":g.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==g.reference&&(g.error=g.error||"URI is not a "+_.reference+" reference.");const k=i(_.scheme||g.scheme);if(!_.unicodeSupport&&(!k||!k.unicodeSupport)&&g.host&&(_.domainHost||k&&k.domainHost)&&C===!1&&s(g.host))try{g.host=URL.domainToASCII(g.host.toLowerCase())}catch(S){g.error=g.error||"Host's domain name can not be converted to ASCII: "+S}(!k||k&&!k.skipNormalize)&&(y.indexOf("%")!==-1&&(g.scheme!==void 0&&(g.scheme=unescape(g.scheme)),g.host!==void 0&&(g.host=unescape(g.host))),g.path&&(g.path=escape(unescape(g.path))),g.fragment&&(g.fragment=encodeURI(decodeURIComponent(g.fragment)))),k&&k.parse&&k.parse(g,_)}else g.error=g.error||"URI can not be parsed.";return g}const v={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:h,serialize:p,parse:m};return Ko.exports=v,Ko.exports.default=v,Ko.exports.fastUri=v,Ko.exports}var sf;function Iw(){if(sf)return Na;sf=1,Object.defineProperty(Na,"__esModule",{value:!0});const e=Sw();return e.code='require("ajv/dist/runtime/uri").default',Na.default=e,Na}var af;function xw(){return af||(af=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=Ra();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Oe();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=Yl(),o=Oa(),s=Dp(),a=Ql(),i=Oe(),l=$a(),c=Ea(),u=De(),h=Tw,p=Iw(),f=(V,P)=>new RegExp(V,P);f.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],v=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.'},_=200;function g(V){var P,H,Z,E,M,L,W,te,se,Se,z,F,Y,ee,ue,xe,He,ot,ft,et,$,ne,Le,_t,Ht;const We=V.strict,dn=(P=V.code)===null||P===void 0?void 0:P.optimize,ht=dn===!0||dn===void 0?1:dn||0,hr=(Z=(H=V.code)===null||H===void 0?void 0:H.regExp)!==null&&Z!==void 0?Z:f,Mn=(E=V.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(L=(M=V.strictSchema)!==null&&M!==void 0?M:We)!==null&&L!==void 0?L:!0,strictNumbers:(te=(W=V.strictNumbers)!==null&&W!==void 0?W:We)!==null&&te!==void 0?te:!0,strictTypes:(Se=(se=V.strictTypes)!==null&&se!==void 0?se:We)!==null&&Se!==void 0?Se:"log",strictTuples:(F=(z=V.strictTuples)!==null&&z!==void 0?z:We)!==null&&F!==void 0?F:"log",strictRequired:(ee=(Y=V.strictRequired)!==null&&Y!==void 0?Y:We)!==null&&ee!==void 0?ee:!1,code:V.code?{...V.code,optimize:ht,regExp:hr}:{optimize:ht,regExp:hr},loopRequired:(ue=V.loopRequired)!==null&&ue!==void 0?ue:_,loopEnum:(xe=V.loopEnum)!==null&&xe!==void 0?xe:_,meta:(He=V.meta)!==null&&He!==void 0?He:!0,messages:(ot=V.messages)!==null&&ot!==void 0?ot:!0,inlineRefs:(ft=V.inlineRefs)!==null&&ft!==void 0?ft:!0,schemaId:(et=V.schemaId)!==null&&et!==void 0?et:"$id",addUsedSchema:($=V.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(ne=V.validateSchema)!==null&&ne!==void 0?ne:!0,validateFormats:(Le=V.validateFormats)!==null&&Le!==void 0?Le:!0,unicodeRegExp:(_t=V.unicodeRegExp)!==null&&_t!==void 0?_t:!0,int32range:(Ht=V.int32range)!==null&&Ht!==void 0?Ht:!0,uriResolver:Mn}}class C{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,...g(P)};const{es5:H,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:H,lines:Z}),this.logger=U(P.logger);const E=P.validateFormats;P.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,y,P,"NOT SUPPORTED"),b.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&x.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),S.call(this),P.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:H,schemaId:Z}=this.opts;let E=h;Z==="id"&&(E={...h},E.id=E.$id,delete E.$id),H&&P&&this.addMetaSchema(E,E[Z],!1)}defaultMeta(){const{meta:P,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[H]||P:void 0}validate(P,H){let Z;if(typeof P=="string"){if(Z=this.getSchema(P),!Z)throw new Error(`no schema with key or ref "${P}"`)}else Z=this.compile(P);const E=Z(H);return"$async"in Z||(this.errors=Z.errors),E}compile(P,H){const Z=this._addSchema(P,H);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(P,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return E.call(this,P,H);async function E(Se,z){await M.call(this,Se.$schema);const F=this._addSchema(Se,z);return F.validate||L.call(this,F)}async function M(Se){Se&&!this.getSchema(Se)&&await E.call(this,{$ref:Se},!0)}async function L(Se){try{return this._compileSchemaEnv(Se)}catch(z){if(!(z instanceof o.default))throw z;return W.call(this,z),await te.call(this,z.missingSchema),L.call(this,Se)}}function W({missingSchema:Se,missingRef:z}){if(this.refs[Se])throw new Error(`AnySchema ${Se} is loaded but ${z} cannot be resolved`)}async function te(Se){const z=await se.call(this,Se);this.refs[Se]||await M.call(this,z.$schema),this.refs[Se]||this.addSchema(z,Se,H)}async function se(Se){const z=this._loading[Se];if(z)return z;try{return await(this._loading[Se]=Z(Se))}finally{delete this._loading[Se]}}}addSchema(P,H,Z,E=this.opts.validateSchema){if(Array.isArray(P)){for(const L of P)this.addSchema(L,void 0,Z,E);return this}let M;if(typeof P=="object"){const{schemaId:L}=this.opts;if(M=P[L],M!==void 0&&typeof M!="string")throw new Error(`schema ${L} must be string`)}return H=(0,l.normalizeId)(H||M),this._checkUnique(H),this.schemas[H]=this._addSchema(P,Z,H,E,!0),this}addMetaSchema(P,H,Z=this.opts.validateSchema){return this.addSchema(P,H,!0,Z),this}validateSchema(P,H){if(typeof P=="boolean")return!0;let Z;if(Z=P.$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,P);if(!E&&H){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return E}getSchema(P){let H;for(;typeof(H=k.call(this,P))=="string";)P=H;if(H===void 0){const{schemaId:Z}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:Z});if(H=a.resolveSchema.call(this,E,P),!H)return;this.refs[P]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const H=k.call(this,P);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const H=P;this._cache.delete(H);let Z=P[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(P){for(const H of P)this.addKeyword(H);return this}addKeyword(P,H){let Z;if(typeof P=="string")Z=P,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=Z);else if(typeof P=="object"&&H===void 0){if(H=P,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(N.call(this,Z,H),!H)return(0,u.eachItem)(Z,M=>G.call(this,M)),this;Q.call(this,H);const E={...H,type:(0,c.getJSONTypes)(H.type),schemaType:(0,c.getJSONTypes)(H.schemaType)};return(0,u.eachItem)(Z,E.type.length===0?M=>G.call(this,M,E):M=>E.type.forEach(L=>G.call(this,M,E,L))),this}getKeyword(P){const H=this.RULES.all[P];return typeof H=="object"?H.definition:!!H}removeKeyword(P){const{RULES:H}=this;delete H.keywords[P],delete H.all[P];for(const Z of H.rules){const E=Z.rules.findIndex(M=>M.keyword===P);E>=0&&Z.rules.splice(E,1)}return this}addFormat(P,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[P]=H,this}errorsText(P=this.errors,{separator:H=", ",dataVar:Z="data"}={}){return!P||P.length===0?"No errors":P.map(E=>`${Z}${E.instancePath} ${E.message}`).reduce((E,M)=>E+H+M)}$dataMetaSchema(P,H){const Z=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const E of H){const M=E.split("/").slice(1);let L=P;for(const W of M)L=L[W];for(const W in Z){const te=Z[W];if(typeof te!="object")continue;const{$data:se}=te.definition,Se=L[W];se&&Se&&(L[W]=he(Se))}}return P}_removeAllSchemas(P,H){for(const Z in P){const E=P[Z];(!H||H.test(Z))&&(typeof E=="string"?delete P[Z]:E&&!E.meta&&(this._cache.delete(E.schema),delete P[Z]))}}_addSchema(P,H,Z,E=this.opts.validateSchema,M=this.opts.addUsedSchema){let L;const{schemaId:W}=this.opts;if(typeof P=="object")L=P[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(P);if(te!==void 0)return te;Z=(0,l.normalizeId)(L||Z);const se=l.getSchemaRefs.call(this,P,Z);return te=new a.SchemaEnv({schema:P,schemaId:W,meta:H,baseId:Z,localRefs:se}),this._cache.set(te.schema,te),M&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=te),E&&this.validateSchema(P,!0),te}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){const H=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=H}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function b(V,P,H,Z="error"){for(const E in V){const M=E;M in P&&this.logger[Z](`${H}: option ${E}. ${V[M]}`)}}function k(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function S(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const P in V)this.addSchema(V[P],P)}function I(){for(const V in this.opts.formats){const P=this.opts.formats[V];P&&this.addFormat(V,P)}}function x(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in V){const H=V[P];H.keyword||(H.keyword=P),this.addKeyword(H)}}function j(){const V={...this.opts};for(const P of m)delete V[P];return V}const O={log(){},warn(){},error(){}};function U(V){if(V===!1)return O;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const A=/^[a-z_$][a-z0-9_$:-]*$/i;function N(V,P){const{RULES:H}=this;if((0,u.eachItem)(V,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`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function G(V,P,H){var Z;const E=P?.post;if(H&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let L=E?M.post:M.rules.find(({type:te})=>te===H);if(L||(L={type:H,rules:[]},M.rules.push(L)),M.keywords[V]=!0,!P)return;const W={keyword:V,definition:{...P,type:(0,c.getJSONTypes)(P.type),schemaType:(0,c.getJSONTypes)(P.schemaType)}};P.before?X.call(this,L,W,P.before):L.rules.push(W),M.all[V]=W,(Z=P.implements)===null||Z===void 0||Z.forEach(te=>this.addKeyword(te))}function X(V,P,H){const Z=V.rules.findIndex(E=>E.keyword===H);Z>=0?V.rules.splice(Z,0,P):(V.rules.push(P),this.logger.warn(`rule ${H} is not defined`))}function Q(V){let{metaSchema:P}=V;P!==void 0&&(V.$data&&this.opts.$data&&(P=he(P)),V.validateSchema=this.compile(P,!0))}const K={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(V){return{anyOf:[V,K]}}})(Vl)),Vl}var Aa={},qa={},La={},lf;function Ew(){if(lf)return La;lf=1,Object.defineProperty(La,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return La.default=e,La}var gn={},cf;function $w(){if(cf)return gn;cf=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.callRef=gn.getValidate=void 0;const e=Oa(),t=yr(),r=Oe(),n=mn(),o=Ql(),s=De(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:h,it:p}=c,{baseId:f,schemaEnv:m,validateName:v,opts:y,self:w}=p,{root:_}=m;if((h==="#"||h==="#/")&&f===_.baseId)return C();const g=o.resolveRef.call(w,_,f,h);if(g===void 0)throw new e.default(p.opts.uriResolver,f,h);if(g instanceof o.SchemaEnv)return b(g);return k(g);function C(){if(m===_)return l(c,v,m,m.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function b(S){const I=i(c,S);l(c,I,S,S.$async)}function k(S){const I=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),x=u.name("valid"),j=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:h},x);c.mergeEvaluated(j),c.ok(x)}}};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`}gn.getValidate=i;function l(c,u,h,p){const{gen:f,it:m}=c,{allErrors:v,schemaEnv:y,opts:w}=m,_=w.passContext?n.default.this:r.nil;p?g():C();function g(){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,_)}`),k(u),v||f.assign(S,!0)},I=>{f.if((0,r._)`!(${I} instanceof ${m.ValidationError})`,()=>f.throw(I)),b(I),v||f.assign(S,!1)}),c.ok(S)}function C(){c.result((0,t.callValidateCode)(c,u,_),()=>k(u),()=>b(u))}function b(S){const I=(0,r._)`${S}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(S){var I;if(!m.opts.unevaluated)return;const x=(I=h?.validate)===null||I===void 0?void 0:I.evaluated;if(m.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(m.props=s.mergeEvaluated.props(f,x.props,m.props));else{const j=f.var("props",(0,r._)`${S}.evaluated.props`);m.props=s.mergeEvaluated.props(f,j,m.props,r.Name)}if(m.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(m.items=s.mergeEvaluated.items(f,x.items,m.items));else{const j=f.var("items",(0,r._)`${S}.evaluated.items`);m.items=s.mergeEvaluated.items(f,j,m.items,r.Name)}}}return gn.callRef=l,gn.default=a,gn}var uf;function Rw(){if(uf)return qa;uf=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=Ew(),t=$w(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return qa.default=r,qa}var ja={},Da={},df;function Pw(){if(df)return Da;df=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=Oe(),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 Da.default=o,Da}var Ua={},pf;function Mw(){if(pf)return Ua;pf=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=Oe(),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 Ua.default=r,Ua}var za={},Za={},ff;function Ow(){if(ff)return Za;ff=1,Object.defineProperty(Za,"__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 Za.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Za}var hf;function Nw(){if(hf)return za;hf=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Oe(),t=De(),r=Ow(),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 za.default=o,za}var Fa={},mf;function Aw(){if(mf)return Fa;mf=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=yr(),t=De(),r=Oe(),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,m=f.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,f),v=a.let("valid");a.try(()=>a.assign(v,(0,r._)`${m}(${u}, ${p}).test(${i})`),()=>a.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${i})`)}}};return Fa.default=o,Fa}var Va={},gf;function qw(){if(gf)return Va;gf=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Oe(),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 Va.default=r,Va}var Ha={},yf;function Lw(){if(yf)return Ha;yf=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=yr(),t=Oe(),r=De(),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?m():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:g}=s.it;for(const C of i)if(_?.[C]===void 0&&!g.has(C)){const b=h.schemaEnv.baseId+h.errSchemaPath,k=`required property "${C}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(h,k,h.opts.strictRequired)}}function m(){if(f||u)s.block$data(t.nil,y);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function v(){const _=a.let("missing");if(f||u){const g=a.let("valid",!0);s.block$data(g,()=>w(_,g)),s.ok(g)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function y(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,p.ownProperties),()=>s.error())})}function w(_,g){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(g,(0,e.propertyInData)(a,c,_,p.ownProperties)),a.if((0,t.not)(g),()=>{s.error(),a.break()})},t.nil)}}};return Ha.default=o,Ha}var Ba={},vf;function jw(){if(vf)return Ba;vf=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Oe(),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 Ba.default=r,Ba}var Ja={},Ga={},_f;function tc(){if(_f)return Ga;_f=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Gp();return e.code='require("ajv/dist/runtime/equal").default',Ga.default=e,Ga}var wf;function Dw(){if(wf)return Ja;wf=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Ea(),t=Oe(),r=De(),n=tc(),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 m=i.let("valid"),v=h.items?(0,e.getSchemaTypes)(h.items):[];a.block$data(m,y,(0,t._)`${p} === false`),a.ok(m);function y(){const C=i.let("i",(0,t._)`${l}.length`),b=i.let("j");a.setParams({i:C,j:b}),i.assign(m,!0),i.if((0,t._)`${C} > 1`,()=>(w()?_:g)(C,b))}function w(){return v.length>0&&!v.some(C=>C==="object"||C==="array")}function _(C,b){const k=i.name("item"),S=(0,e.checkDataTypes)(v,k,f.opts.strictNumbers,e.DataType.Wrong),I=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${C}--;`,()=>{i.let(k,(0,t._)`${l}[${C}]`),i.if(S,(0,t._)`continue`),v.length>1&&i.if((0,t._)`typeof ${k} == "string"`,(0,t._)`${k} += "_"`),i.if((0,t._)`typeof ${I}[${k}] == "number"`,()=>{i.assign(b,(0,t._)`${I}[${k}]`),a.error(),i.assign(m,!1).break()}).code((0,t._)`${I}[${k}] = ${C}`)})}function g(C,b){const k=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${C}--;`,()=>i.for((0,t._)`${b} = ${C}; ${b}--;`,()=>i.if((0,t._)`${k}(${l}[${C}], ${l}[${b}])`,()=>{a.error(),i.assign(m,!1).break(S)})))}}};return Ja.default=s,Ja}var Wa={},bf;function Uw(){if(bf)return Wa;bf=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Oe(),t=De(),r=tc(),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 Wa.default=o,Wa}var Ka={},kf;function zw(){if(kf)return Ka;kf=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Oe(),t=De(),r=tc(),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 m=()=>f??(f=(0,t.useFunc)(a,r.default));let v;if(p||l)v=a.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);v=(0,e.or)(...c.map((g,C)=>w(_,C)))}s.pass(v);function y(){a.assign(v,!1),a.forOf("v",u,_=>a.if((0,e._)`${m()}(${i}, ${_})`,()=>a.assign(v,!0).break()))}function w(_,g){const C=c[g];return typeof C=="object"&&C!==null?(0,e._)`${m()}(${i}, ${_}[${g}])`:(0,e._)`${i} === ${C}`}}};return Ka.default=o,Ka}var Tf;function Zw(){if(Tf)return ja;Tf=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=Pw(),t=Mw(),r=Nw(),n=Aw(),o=qw(),s=Lw(),a=jw(),i=Dw(),l=Uw(),c=zw(),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 ja.default=u,ja}var Ya={},co={},Cf;function Sf(){if(Cf)return co;Cf=1,Object.defineProperty(co,"__esModule",{value:!0}),co.validateAdditionalItems=void 0;const e=Oe(),t=De(),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 m=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(m),()=>f(m)),s.ok(m)}function f(m){i.forRange("i",a.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},m),h.allErrors||i.if((0,e.not)(m),()=>i.break())})}}return co.validateAdditionalItems=o,co.default=n,co}var Qa={},uo={},If;function xf(){if(If)return uo;If=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.validateTuple=void 0;const e=Oe(),t=De(),r=yr(),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;v(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const f=l.name("valid"),m=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${m} > ${w}`,()=>s.subschema({keyword:h,schemaProp:w,dataProp:w},f)),s.ok(f))});function v(y){const{opts:w,errSchemaPath:_}=p,g=i.length,C=g===y.minItems&&(g===y.maxItems||y[a]===!1);if(w.strictTuples&&!C){const b=`"${h}" is ${g}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return uo.validateTuple=o,uo.default=n,uo}var Ef;function Fw(){if(Ef)return Qa;Ef=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=xf(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Qa.default=t,Qa}var Xa={},$f;function Vw(){if($f)return Xa;$f=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=Oe(),t=De(),r=yr(),n=Sf(),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 Xa.default=s,Xa}var ei={},Rf;function Hw(){if(Rf)return ei;Rf=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Oe(),t=De(),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 m=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 g=(0,e._)`${m} >= ${u}`;h!==void 0&&(g=(0,e._)`${g} && ${m} <= ${h}`),o.pass(g);return}c.items=!0;const v=s.name("valid");h===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),h!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const g=s.name("_valid"),C=s.let("count",0);w(g,()=>s.if(g,()=>_(C)))}function w(g,C){s.forRange("i",0,m,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},g),C()})}function _(g){s.code((0,e._)`${g}++`),h===void 0?s.if((0,e._)`${g} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${g} > ${h}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${g} >= ${u}`,()=>s.assign(v,!0)))}}};return ei.default=n,ei}var rc={},Pf;function Bw(){return Pf||(Pf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Oe(),r=De(),n=yr();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
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 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 v=c[g];if(v.length===0)continue;const y=(0,n.propertyInData)(u,h,g,p.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,v,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 v in c)(0,r.alwaysValidSchema)(f,c[v])||(u.if((0,n.propertyInData)(u,h,v,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:v},g);l.mergeValidEvaluated(y,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=i,e.default=o})(Wl)),Wl}var Qa={},If;function zw(){if(If)return Qa;If=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=Oe(),t=De(),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 Qa.default=n,Qa}var Xa={},Ef;function xf(){if(Ef)return Xa;Ef=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=yr(),t=Oe(),r=hn(),n=De(),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 v=(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,k=>{!v.length&&!y.length?C(k):i.if(_(k),()=>C(k))})}function _(k){let S;if(v.length>8){const I=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,I,k)}else v.length?S=(0,t.or)(...v.map(I=>(0,t._)`${k} === ${I}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(I=>(0,t._)`${(0,e.usePattern)(a,I)}.test(${k})`))),(0,t.not)(S)}function m(k){i.code((0,t._)`delete ${u}[${k}]`)}function C(k){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){m(k);return}if(l===!1){a.setParams({additionalProperty:k}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");g.removeAdditional==="failing"?(b(k,S,!1),i.if((0,t.not)(S),()=>{a.reset(),m(k)})):(b(k,S),f||i.if((0,t.not)(S),()=>i.break()))}}function b(k,S,I){const E={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};I===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(E,S)}}};return Xa.default=s,Xa}var ei={},$f;function Zw(){if($f)return ei;$f=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ea(),t=yr(),r=De(),n=xf(),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)?v(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),v(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 v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return ei.default=o,ei}var ti={},Rf;function Fw(){if(Rf)return ti;Rf=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=yr(),t=Oe(),r=De(),n=De(),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,v=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&&_(C),u.allErrors?m(C):(a.var(v,!0),m(C),a.if(v))}function _(C){for(const b in g)new RegExp(C).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${C} (use allowMatchingProperties)`)}function m(C){a.forIn("key",l,b=>{a.if((0,t._)`${(0,e.usePattern)(s,C)}.test(${b})`,()=>{const k=f.includes(C);k||s.subschema({keyword:"patternProperties",schemaProp:C,dataProp:b,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${b}]`,!0):!k&&!u.allErrors&&a.if((0,t.not)(v),()=>a.break())})})}}};return ti.default=o,ti}var ri={},Pf;function Vw(){if(Pf)return ri;Pf=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=De(),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 ri.default=t,ri}var ni={},Mf;function Hw(){if(Mf)return ni;Mf=1,Object.defineProperty(ni,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:yr().validateUnion,error:{message:"must match a schema in anyOf"}};return ni.default=t,ni}var oi={},Of;function Bw(){if(Of)return oi;Of=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Oe(),t=De(),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,v)=>{let y;(0,t.alwaysValidSchema)(l,g)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},p),v>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(h,(0,e._)`[${h}, ${v}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(h,v),y&&o.mergeEvaluated(y,e.Name)})})}}};return oi.default=n,oi}var si={},Nf;function Jw(){if(Nf)return si;Nf=1,Object.defineProperty(si,"__esModule",{value:!0});const e=De(),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 si.default=t,si}var ai={},Af;function Gw(){if(Af)return ai;Af=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=Oe(),t=De(),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 v=a.let("ifClause");s.setParams({ifClause:v}),a.if(p,g("then",v),g("else",v))}else c?a.if(p,g("then")):a.if((0,e.not)(p),g("else"));s.pass(h,()=>s.error(!0));function f(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(v)}function g(v,y){return()=>{const w=s.subschema({keyword:v},p);a.assign(h,p),s.mergeValidEvaluated(w,h),y?a.assign(y,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return ai.default=n,ai}var ii={},qf;function Ww(){if(qf)return ii;qf=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=De(),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 ii.default=t,ii}var Lf;function Kw(){if(Lf)return Ga;Lf=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=_f(),t=Lw(),r=bf(),n=jw(),o=Dw(),s=Uw(),a=zw(),i=xf(),l=Zw(),c=Fw(),u=Vw(),h=Hw(),p=Bw(),f=Jw(),g=Gw(),v=Ww();function y(w=!1){const _=[u.default,h.default,p.default,f.default,g.default,v.default,a.default,i.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Ga.default=y,Ga}var li={},ci={},jf;function Yw(){if(jf)return ci;jf=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Oe(),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?v():y();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:h.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),m=s.let("fType"),C=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(m,(0,e._)`${_}.type || "string"`).assign(C,(0,e._)`${_}.validate`),()=>s.assign(m,(0,e._)`"string"`).assign(C,_)),n.fail$data((0,e.or)(b(),k()));function b(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${C}`}function k(){const S=f.$async?(0,e._)`(${_}.async ? await ${C}(${a}) : ${C}(${a}))`:(0,e._)`${C}(${a})`,I=(0,e._)`(typeof ${C} == "function" ? ${S} : ${C}.test(${a}))`;return(0,e._)`${C} && ${C} !== true && ${m} === ${o} && !${I}`}}function y(){const w=g.formats[l];if(!w){b();return}if(w===!0)return;const[_,m,C]=k(w);_===o&&n.pass(S());function b(){if(h.strictSchema===!1){g.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function k(I){const E=I instanceof RegExp?(0,e.regexpCode)(I):h.code.formats?(0,e._)`${h.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:I,code:E});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${j}.validate`]:["string",I,j]}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 ci.default=r,ci}var Df;function Qw(){if(Df)return li;Df=1,Object.defineProperty(li,"__esModule",{value:!0});const t=[Yw().default];return li.default=t,li}var Ln={},Uf;function Xw(){return Uf||(Uf=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.contentVocabulary=Ln.metadataVocabulary=void 0,Ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Ln}var zf;function eb(){if(zf)return Ma;zf=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=Cw(),t=qw(),r=Kw(),n=Qw(),o=Xw(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Ma.default=s,Ma}var ui={},Wo={},Zf;function tb(){if(Zf)return Wo;Zf=1,Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Wo.DiscrError=e={})),Wo}var Ff;function rb(){if(Ff)return ui;Ff=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Oe(),t=tb(),r=Hl(),n=Ra(),o=De(),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 v=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(v);function w(){const C=m();l.if(!1);for(const b in C)l.elseIf((0,e._)`${y} === ${b}`),l.assign(v,_(C[b]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function _(C){const b=l.name("valid"),k=i.subschema({keyword:"oneOf",schemaProp:C},b);return i.mergeEvaluated(k,e.Name),b}function m(){var C;const b={},k=I(h);let S=!0;for(let O=0;O<f.length;O++){let U=f[O];if(U?.$ref&&!(0,o.schemaHasRulesButRef)(U,p.self.RULES)){const N=U.$ref;if(U=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,N),U instanceof r.SchemaEnv&&(U=U.schema),U===void 0)throw new n.default(p.opts.uriResolver,p.baseId,N)}const A=(C=U?.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&&(k||I(U)),E(A,O)}if(!S)throw new Error(`discriminator: "${g}" must be required`);return b;function I({required:O}){return Array.isArray(O)&&O.includes(g)}function E(O,U){if(O.const)j(O.const,U);else if(O.enum)for(const A of O.enum)j(A,U);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function j(O,U){if(typeof O!="string"||O in b)throw new Error(`discriminator: "${g}" values must be unique strings`);b[O]=U}}}};return ui.default=a,ui}const nb={$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 Hf(){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=bw(),n=eb(),o=rb(),s=nb,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=Ea();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Oe();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=Vl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=Ra();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(ba,ba.exports)),ba.exports}var ob=Hf();const Bf=Nn(ob);var je;(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})(je||(je={}));var Kl;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Kl||(Kl={}));const ce=je.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Kr=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}},oe=je.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"]),sb=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class tr 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 tr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,je.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()}}tr.create=e=>new tr(e);const uo=(e,t)=>{let r;switch(e.code){case oe.invalid_type:e.received===ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,je.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${je.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${je.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${je.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.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}"`:je.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case oe.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 oe.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 oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,je.assertNever(e)}return{message:r}};let Jf=uo;function ab(e){Jf=e}function di(){return Jf}const pi=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}},ib=[];function ie(e,t){const r=di(),n=pi({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===uo?void 0:uo].filter(o=>!!o)});e.common.issues.push(n)}class At{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 Te;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 At.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 Te;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 Te=Object.freeze({status:"aborted"}),po=e=>({status:"dirty",value:e}),Ut=e=>({status:"valid",value:e}),Yl=e=>e.status==="aborted",Ql=e=>e.status==="dirty",jn=e=>e.status==="valid",Ko=e=>typeof Promise<"u"&&e instanceof Promise;var me;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(me||(me={}));class Lr{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 Gf=(e,t)=>{if(jn(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 tr(e.common.issues);return this._error=r,this._error}}};function Re(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 Kr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Kr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new At,ctx:{common:t.parent.common,data:t.data,parsedType:Kr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Ko(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:Kr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Gf(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Kr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return jn(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=>jn(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:Kr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Ko(o)?o:Promise.resolve(o));return Gf(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:oe.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 vr({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 _r.create(this,this._def)}nullable(){return yn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zn.create(this)}promise(){return yo.create(this,this._def)}or(t){return ts.create([this,t],this._def)}and(t){return rs.create(this,t,this._def)}transform(t){return new vr({...Re(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new is({...Re(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new tc({typeName:B.ZodBranded,type:this,...Re(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ls({...Re(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 cs.create(this,t)}readonly(){return us.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const lb=/^c[^\s-]{8,}$/i,cb=/^[0-9a-z]+$/,ub=/^[0-9A-HJKMNP-TV-Z]{26}$/i,db=/^[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,pb=/^[a-z0-9_-]{21}$/i,fb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hb=/^[-+]?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)?)??$/,mb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xl;const yb=/^(?:(?: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])$/,vb=/^(?:(?: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])$/,_b=/^(([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]))$/,wb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Wf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Tb=new RegExp(`^${Wf}$`);function Kf(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 Cb(e){return new RegExp(`^${Kf(e)}$`)}function Yf(e){let t=`${Wf}T${Kf(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)&&yb.test(e)||(t==="v6"||!t)&&_b.test(e))}function Ib(e,t){if(!fb.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 Eb(e,t){return!!((t==="v4"||!t)&&vb.test(e)||(t==="v6"||!t)&&wb.test(e))}let fo=class wa extends Pe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ce.string){const s=this._getOrReturnCtx(t);return ie(s,{code:oe.invalid_type,expected:ce.string,received:s.parsedType}),Te}const n=new At;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.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),ie(o,{code:oe.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?ie(o,{code:oe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ie(o,{code:oe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")mb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"email",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Xl||(Xl=new RegExp(gb,"u")),Xl.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"emoji",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")db.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"uuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")pb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"nanoid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")lb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")cb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid2",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")ub.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ulid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ie(o,{validation:"url",code:oe.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),ie(o,{validation:"regex",code:oe.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),ie(o,{code:oe.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),ie(o,{code:oe.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Yf(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Tb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Cb(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?hb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"duration",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Sb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ip",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Ib(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"jwt",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Eb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cidr",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?bb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?kb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64url",code:oe.invalid_string,message:s.message}),n.dirty()):je.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:oe.invalid_string,...me.errToObj(n)})}_addCheck(t){return new wa({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...me.errToObj(t)})}url(t){return this._addCheck({kind:"url",...me.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...me.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...me.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...me.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...me.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...me.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...me.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...me.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...me.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...me.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...me.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...me.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,...me.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,...me.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...me.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...me.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...me.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...me.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...me.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...me.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...me.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...me.errToObj(r)})}nonempty(t){return this.min(1,me.errToObj(t))}trim(){return new wa({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new wa({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new wa({...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}};fo.create=e=>new fo({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...Re(e)});function xb(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 Yo=class _p 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 ie(s,{code:oe.invalid_type,expected:ce.number,received:s.parsedType}),Te}let n;const o=new At;for(const s of this._def.checks)s.kind==="int"?je.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.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),ie(n,{code:oe.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),ie(n,{code:oe.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?xb(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.not_finite,message:s.message}),o.dirty()):je.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new _p({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new _p({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:me.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:me.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.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"&&je.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)}};Yo.create=e=>new Yo({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...Re(e)});class gn 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 At;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),ie(n,{code:oe.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),ie(n,{code:oe.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),ie(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):je.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ie(r,{code:oe.invalid_type,expected:ce.bigint,received:r.parsedType}),Te}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new gn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new gn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.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}}gn.create=e=>new gn({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...Re(e)});let Qo=class extends Pe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ce.boolean){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.boolean,received:n.parsedType}),Te}return Ut(t.data)}};Qo.create=e=>new Qo({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...Re(e)});class Dn 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 ie(s,{code:oe.invalid_type,expected:ce.date,received:s.parsedType}),Te}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ie(s,{code:oe.invalid_date}),Te}const n=new At;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.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),ie(o,{code:oe.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):je.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Dn({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:me.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:me.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}}Dn.create=e=>new Dn({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...Re(e)});class fi extends Pe{_parse(t){if(this._getType(t)!==ce.symbol){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.symbol,received:n.parsedType}),Te}return Ut(t.data)}}fi.create=e=>new fi({typeName:B.ZodSymbol,...Re(e)});class Xo extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.undefined,received:n.parsedType}),Te}return Ut(t.data)}}Xo.create=e=>new Xo({typeName:B.ZodUndefined,...Re(e)});let es=class extends Pe{_parse(t){if(this._getType(t)!==ce.null){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.null,received:n.parsedType}),Te}return Ut(t.data)}};es.create=e=>new es({typeName:B.ZodNull,...Re(e)});let ho=class extends Pe{constructor(){super(...arguments),this._any=!0}_parse(t){return Ut(t.data)}};ho.create=e=>new ho({typeName:B.ZodAny,...Re(e)});let Un=class extends Pe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ut(t.data)}};Un.create=e=>new Un({typeName:B.ZodUnknown,...Re(e)});let Yr=class extends Pe{_parse(t){const r=this._getOrReturnCtx(t);return ie(r,{code:oe.invalid_type,expected:ce.never,received:r.parsedType}),Te}};Yr.create=e=>new Yr({typeName:B.ZodNever,...Re(e)});class hi extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.void,received:n.parsedType}),Te}return Ut(t.data)}}hi.create=e=>new hi({typeName:B.ZodVoid,...Re(e)});let zn=class ql extends Pe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ce.array)return ie(r,{code:oe.invalid_type,expected:ce.array,received:r.parsedType}),Te;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(ie(r,{code:a?oe.too_big:oe.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&&(ie(r,{code:oe.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&&(ie(r,{code:oe.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 Lr(r,a,r.path,i)))).then(a=>At.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Lr(r,a,r.path,i)));return At.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new ql({...this._def,minLength:{value:t,message:me.toString(r)}})}max(t,r){return new ql({...this._def,maxLength:{value:t,message:me.toString(r)}})}length(t,r){return new ql({...this._def,exactLength:{value:t,message:me.toString(r)}})}nonempty(t){return this.min(1,t)}};zn.create=(e,t)=>new zn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...Re(t)});function mo(e){if(e instanceof ar){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=_r.create(mo(n))}return new ar({...e._def,shape:()=>t})}else return e instanceof zn?new zn({...e._def,type:mo(e.element)}):e instanceof _r?_r.create(mo(e.unwrap())):e instanceof yn?yn.create(mo(e.unwrap())):e instanceof jr?jr.create(e.items.map(t=>mo(t))):e}let ar=class qr 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=je.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 ie(c,{code:oe.invalid_type,expected:ce.object,received:c.parsedType}),Te}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Yr&&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 Lr(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Yr){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&&(ie(o,{code:oe.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 Lr(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=>At.mergeObjectSync(n,c)):At.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return me.errToObj,new qr({...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:me.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new qr({...this._def,unknownKeys:"strip"})}passthrough(){return new qr({...this._def,unknownKeys:"passthrough"})}extend(t){return new qr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new qr({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 qr({...this._def,catchall:t})}pick(t){const r={};for(const n of je.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new qr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of je.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new qr({...this._def,shape:()=>r})}deepPartial(){return mo(this)}partial(t){const r={};for(const n of je.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new qr({...this._def,shape:()=>r})}required(t){const r={};for(const n of je.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof _r;)s=s._def.innerType;r[n]=s}return new qr({...this._def,shape:()=>r})}keyof(){return eh(je.objectKeys(this.shape))}};ar.create=(e,t)=>new ar({shape:()=>e,unknownKeys:"strip",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)}),ar.strictCreate=(e,t)=>new ar({shape:()=>e,unknownKeys:"strict",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)}),ar.lazycreate=(e,t)=>new ar({shape:e,unknownKeys:"strip",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)});let ts=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 tr(i.ctx.common.issues));return ie(r,{code:oe.invalid_union,unionErrors:a}),Te}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 tr(l));return ie(r,{code:oe.invalid_union,unionErrors:i}),Te}}get options(){return this._def.options}};ts.create=(e,t)=>new ts({options:e,typeName:B.ZodUnion,...Re(t)});const Qr=e=>e instanceof ns?Qr(e.schema):e instanceof vr?Qr(e.innerType()):e instanceof os?[e.value]:e instanceof ss?e.options:e instanceof as?je.objectValues(e.enum):e instanceof is?Qr(e._def.innerType):e instanceof Xo?[void 0]:e instanceof es?[null]:e instanceof _r?[void 0,...Qr(e.unwrap())]:e instanceof yn?[null,...Qr(e.unwrap())]:e instanceof tc||e instanceof us?Qr(e.unwrap()):e instanceof ls?Qr(e._def.innerType):[];let Qf=class aw extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.object)return ie(r,{code:oe.invalid_type,expected:ce.object,received:r.parsedType}),Te;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}):(ie(r,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Te)}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=Qr(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 aw({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...Re(n)})}};function ec(e,t){const r=Kr(e),n=Kr(t);if(e===t)return{valid:!0,data:e};if(r===ce.object&&n===ce.object){const o=je.objectKeys(t),s=je.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=ec(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=ec(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 rs=class extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Yl(s)||Yl(a))return Te;const i=ec(s.value,a.value);return i.valid?((Ql(s)||Ql(a))&&r.dirty(),{status:r.value,value:i.data}):(ie(n,{code:oe.invalid_intersection_types}),Te)};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}))}};rs.create=(e,t,r)=>new rs({left:e,right:t,typeName:B.ZodIntersection,...Re(r)});class jr extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.array)return ie(n,{code:oe.invalid_type,expected:ce.array,received:n.parsedType}),Te;if(n.data.length<this._def.items.length)return ie(n,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Te;!this._def.rest&&n.data.length>this._def.items.length&&(ie(n,{code:oe.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 Lr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>At.mergeArray(r,a)):At.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new jr({...this._def,rest:t})}}jr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new jr({items:e,typeName:B.ZodTuple,rest:null,...Re(t)})};let Xf=class wp 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 ie(n,{code:oe.invalid_type,expected:ce.object,received:n.parsedType}),Te;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Lr(n,i,n.path,i)),value:a._parse(new Lr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?At.mergeObjectAsync(r,o):At.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Pe?new wp({keyType:t,valueType:r,typeName:B.ZodRecord,...Re(n)}):new wp({keyType:fo.create(),valueType:t,typeName:B.ZodRecord,...Re(r)})}};class mi 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 ie(n,{code:oe.invalid_type,expected:ce.map,received:n.parsedType}),Te;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Lr(n,i,n.path,[c,"key"])),value:s._parse(new Lr(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 Te;(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 Te;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}mi.create=(e,t,r)=>new mi({valueType:t,keyType:e,typeName:B.ZodMap,...Re(r)});class Zn extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.set)return ie(n,{code:oe.invalid_type,expected:ce.set,received:n.parsedType}),Te;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ie(n,{code:oe.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&&(ie(n,{code:oe.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 Te;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 Lr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Zn({...this._def,minSize:{value:t,message:me.toString(r)}})}max(t,r){return new Zn({...this._def,maxSize:{value:t,message:me.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Zn.create=(e,t)=>new Zn({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...Re(t)});class go extends Pe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.function)return ie(r,{code:oe.invalid_type,expected:ce.function,received:r.parsedType}),Te;function n(i,l){return pi({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,di(),uo].filter(c=>!!c),issueData:{code:oe.invalid_arguments,argumentsError:l}})}function o(i,l){return pi({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,di(),uo].filter(c=>!!c),issueData:{code:oe.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof yo){const i=this;return Ut(async function(...l){const c=new tr([]),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 Ut(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new tr([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),h=i._def.returns.safeParse(u,s);if(!h.success)throw new tr([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new go({...this._def,args:jr.create(t).rest(Un.create())})}returns(t){return new go({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new go({args:t||jr.create([]).rest(Un.create()),returns:r||Un.create(),typeName:B.ZodFunction,...Re(n)})}}let ns=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})}};ns.create=(e,t)=>new ns({getter:e,typeName:B.ZodLazy,...Re(t)});let os=class extends Pe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ie(r,{received:r.data,code:oe.invalid_literal,expected:this._def.value}),Te}return{status:"valid",value:t.data}}get value(){return this._def.value}};os.create=(e,t)=>new os({value:e,typeName:B.ZodLiteral,...Re(t)});function eh(e,t){return new ss({values:e,typeName:B.ZodEnum,...Re(t)})}let ss=class bp extends Pe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ie(r,{expected:je.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Te}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 ie(r,{received:r.data,code:oe.invalid_enum_value,options:n}),Te}return Ut(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 bp.create(t,{...this._def,...r})}exclude(t,r=this._def){return bp.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};ss.create=eh;class as extends Pe{_parse(t){const r=je.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ce.string&&n.parsedType!==ce.number){const o=je.objectValues(r);return ie(n,{expected:je.joinValues(o),received:n.parsedType,code:oe.invalid_type}),Te}if(this._cache||(this._cache=new Set(je.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=je.objectValues(r);return ie(n,{received:n.data,code:oe.invalid_enum_value,options:o}),Te}return Ut(t.data)}get enum(){return this._def.values}}as.create=(e,t)=>new as({values:e,typeName:B.ZodNativeEnum,...Re(t)});class yo 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 ie(r,{code:oe.invalid_type,expected:ce.promise,received:r.parsedType}),Te;const n=r.parsedType===ce.promise?r.data:Promise.resolve(r.data);return Ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}yo.create=(e,t)=>new yo({type:e,typeName:B.ZodPromise,...Re(t)});class vr extends Pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{ie(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 Te;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?Te:l.status==="dirty"||r.value==="dirty"?po(l.value):l});{if(r.value==="aborted")return Te;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?Te:i.status==="dirty"||r.value==="dirty"?po(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"?Te:(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"?Te:(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(!jn(a))return Te;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=>jn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):Te);je.assertNever(o)}}vr.create=(e,t,r)=>new vr({schema:e,typeName:B.ZodEffects,effect:t,...Re(r)}),vr.createWithPreprocess=(e,t,r)=>new vr({schema:t,effect:{type:"preprocess",transform:e},typeName:B.ZodEffects,...Re(r)});let _r=class extends Pe{_parse(t){return this._getType(t)===ce.undefined?Ut(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:B.ZodOptional,...Re(t)});let yn=class extends Pe{_parse(t){return this._getType(t)===ce.null?Ut(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:B.ZodNullable,...Re(t)});let is=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}};is.create=(e,t)=>new is({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Re(t)});let ls=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 Ko(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new tr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new tr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ls.create=(e,t)=>new ls({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Re(t)});class gi extends Pe{_parse(t){if(this._getType(t)!==ce.nan){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.nan,received:n.parsedType}),Te}return{status:"valid",value:t.data}}}gi.create=e=>new gi({typeName:B.ZodNaN,...Re(e)});const $b=Symbol("zod_brand");class tc 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 cs 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"?Te:s.status==="dirty"?(r.dirty(),po(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"?Te: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 cs({in:t,out:r,typeName:B.ZodPipeline})}}let us=class extends Pe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(jn(o)&&(o.value=Object.freeze(o.value)),o);return Ko(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};us.create=(e,t)=>new us({innerType:e,typeName:B.ZodReadonly,...Re(t)});function th(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function rh(e,t={},r){return e?ho.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=th(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=th(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):ho.create()}const Rb={object:ar.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 Pb=(e,t={message:`Input not instance of ${e.name}`})=>rh(r=>r instanceof e,t),Ze=fo.create,ir=Yo.create,Mb=gi.create,Ob=gn.create,nh=Qo.create,Nb=Dn.create,Ab=fi.create,qb=Xo.create,Lb=es.create,jb=ho.create,Db=Un.create,Ub=Yr.create,zb=hi.create,Xr=zn.create,Bt=ar.create,Zb=ar.strictCreate,yi=ts.create,Fb=Qf.create,Vb=rs.create,Hb=jr.create,Bb=Xf.create,Jb=mi.create,Gb=Zn.create,Wb=go.create,Kb=ns.create,Yb=os.create,ds=ss.create,Qb=as.create,Xb=yo.create,oh=vr.create,e3=_r.create,t3=yn.create,r3=vr.createWithPreprocess,n3=cs.create,o3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:$b,DIRTY:po,EMPTY_PATH:ib,INVALID:Te,NEVER:Te,OK:Ut,ParseStatus:At,Schema:Pe,ZodAny:ho,ZodArray:zn,ZodBigInt:gn,ZodBoolean:Qo,ZodBranded:tc,ZodCatch:ls,ZodDate:Dn,ZodDefault:is,ZodDiscriminatedUnion:Qf,ZodEffects:vr,ZodEnum:ss,ZodError:tr,get ZodFirstPartyTypeKind(){return B},ZodFunction:go,ZodIntersection:rs,ZodIssueCode:oe,ZodLazy:ns,ZodLiteral:os,ZodMap:mi,ZodNaN:gi,ZodNativeEnum:as,ZodNever:Yr,ZodNull:es,ZodNullable:yn,ZodNumber:Yo,ZodObject:ar,ZodOptional:_r,ZodParsedType:ce,ZodPipeline:cs,ZodPromise:yo,ZodReadonly:us,ZodRecord:Xf,ZodSchema:Pe,ZodSet:Zn,ZodString:fo,ZodSymbol:fi,ZodTransformer:vr,ZodTuple:jr,ZodType:Pe,ZodUndefined:Xo,ZodUnion:ts,ZodUnknown:Un,ZodVoid:hi,addIssueToContext:ie,any:jb,array:Xr,bigint:Ob,boolean:nh,coerce:{string:(e=>fo.create({...e,coerce:!0})),number:(e=>Yo.create({...e,coerce:!0})),boolean:(e=>Qo.create({...e,coerce:!0})),bigint:(e=>gn.create({...e,coerce:!0})),date:(e=>Dn.create({...e,coerce:!0}))},custom:rh,date:Nb,datetimeRegex:Yf,defaultErrorMap:uo,discriminatedUnion:Fb,effect:oh,enum:ds,function:Wb,getErrorMap:di,getParsedType:Kr,instanceof:Pb,intersection:Vb,isAborted:Yl,isAsync:Ko,isDirty:Ql,isValid:jn,late:Rb,lazy:Kb,literal:Yb,makeIssue:pi,map:Jb,nan:Mb,nativeEnum:Qb,never:Ub,null:Lb,nullable:t3,number:ir,object:Bt,get objectUtil(){return Kl},oboolean:()=>nh().optional(),onumber:()=>ir().optional(),optional:e3,ostring:()=>Ze().optional(),pipeline:n3,preprocess:r3,promise:Xb,quotelessJson:sb,record:Bb,set:Gb,setErrorMap:ab,strictObject:Zb,string:Ze,symbol:Ab,transformer:oh,tuple:Hb,undefined:qb,union:yi,unknown:Db,get util(){return je},void:zb},Symbol.toStringTag,{value:"Module"})),sh=Object.freeze({status:"aborted"});function J(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 ps extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ah={};function vn(e){return ah}function ih(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 s3(e,t){return typeof t=="bigint"?t.toString():t}function rc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nc(e){return e==null}function oc(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function a3(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 Fe(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 fs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function hs(e){return JSON.stringify(e)}const lh=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function vi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const i3=rc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function _i(e){if(vi(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(vi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const l3=new Set(["string","number","symbol"]);function ms(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _n(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 c3(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const u3={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 d3(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 _n(e,{...e._zod.def,shape:r,checks:[]})}function p3(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 _n(e,{...e._zod.def,shape:r,checks:[]})}function f3(e,t){if(!_i(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 fs(this,"shape",n),n},checks:[]};return _n(e,r)}function h3(e,t){return _n(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return fs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function m3(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 _n(t,{...t._zod.def,shape:o,checks:[]})}function g3(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 _n(t,{...t._zod.def,shape:o,checks:[]})}function gs(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Fn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function wi(e){return typeof e=="string"?e:e?.message}function wn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=wi(e.inst?._zod.def?.error?.(e))??wi(t?.error?.(e))??wi(r.customError?.(e))??wi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function sc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ys(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const ch=(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,s3,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},uh=J("$ZodError",ch),bi=J("$ZodError",ch,{Parent:Error});function y3(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 v3(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 dh=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 ps;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>wn(l,s,vn())));throw lh(i,o?.callee),i}return a.value},_3=dh(bi),ph=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=>wn(l,s,vn())));throw lh(i,o?.callee),i}return a.value},w3=ph(bi),fh=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 ps;return s.issues.length?{success:!1,error:new(e??uh)(s.issues.map(a=>wn(a,o,vn())))}:{success:!0,data:s.value}},ac=fh(bi),hh=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=>wn(a,o,vn())))}:{success:!0,data:s.value}},ic=hh(bi),b3=/^[cC][^\s-]{8,}$/,k3=/^[0-9a-z]+$/,T3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,C3=/^[0-9a-vA-V]{20}$/,S3=/^[A-Za-z0-9]{27}$/,I3=/^[a-zA-Z0-9_-]{21}$/,E3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,x3=/^([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})$/,mh=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)$/,$3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,R3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function P3(){return new RegExp(R3,"u")}const M3=/^(?:(?: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])$/,O3=/^(([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})$/,N3=/^((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])$/,A3=/^(([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])$/,q3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gh=/^[A-Za-z0-9_-]*$/,L3=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,j3=/^\+(?:[0-9]){6,14}[0-9]$/,yh="(?:(?:\\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])))",D3=new RegExp(`^${yh}$`);function vh(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 U3(e){return new RegExp(`^${vh(e)}$`)}function z3(e){const t=vh({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(`^${yh}T(?:${n})$`)}const Z3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},F3=/^\d+$/,V3=/^-?\d+(?:\.\d+)?/i,H3=/true|false/i,B3=/null/i,J3=/^[^A-Z]*$/,G3=/^[^a-z]*$/,Jt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),_h={number:"number",bigint:"bigint",object:"date"},wh=J("$ZodCheckLessThan",(e,t)=>{Jt.init(e,t);const r=_h[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})}}),bh=J("$ZodCheckGreaterThan",(e,t)=>{Jt.init(e,t);const r=_h[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})}}),W3=J("$ZodCheckMultipleOf",(e,t)=>{Jt.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):a3(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})}}),K3=J("$ZodCheckNumberFormat",(e,t)=>{Jt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=u3[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=F3)}),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})}}),Y3=J("$ZodCheckMaxLength",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nc(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=sc(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Q3=J("$ZodCheckMinLength",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nc(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=sc(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),X3=J("$ZodCheckLengthEquals",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!nc(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=sc(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})}}),ki=J("$ZodCheckStringFormat",(e,t)=>{var r,n;Jt.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=()=>{})}),e9=J("$ZodCheckRegex",(e,t)=>{ki.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})}}),t9=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=J3),ki.init(e,t)}),r9=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=G3),ki.init(e,t)}),n9=J("$ZodCheckIncludes",(e,t)=>{Jt.init(e,t);const r=ms(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})}}),o9=J("$ZodCheckStartsWith",(e,t)=>{Jt.init(e,t);const r=new RegExp(`^${ms(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})}}),s9=J("$ZodCheckEndsWith",(e,t)=>{Jt.init(e,t);const r=new RegExp(`.*${ms(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})}}),a9=J("$ZodCheckOverwrite",(e,t)=>{Jt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class i9{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 m in c){const v=c[m];if(v.length===0)continue;const y=(0,n.propertyInData)(u,h,m,p.opts.ownProperties);l.setParams({property:m,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,v,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,m=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(f,c[v])||(u.if((0,n.propertyInData)(u,h,v,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:v},m);l.mergeValidEvaluated(y,m)},()=>u.var(m,!0)),l.ok(m))}e.validateSchemaDeps=i,e.default=o})(rc)),rc}var ti={},Mf;function Jw(){if(Mf)return ti;Mf=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Oe(),t=De(),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 ti.default=n,ti}var ri={},Of;function Nf(){if(Of)return ri;Of=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=yr(),t=Oe(),r=mn(),n=De(),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:m}=p;if(p.props=!0,m.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const v=(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,k=>{!v.length&&!y.length?C(k):i.if(_(k),()=>C(k))})}function _(k){let S;if(v.length>8){const I=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,I,k)}else v.length?S=(0,t.or)(...v.map(I=>(0,t._)`${k} === ${I}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(I=>(0,t._)`${(0,e.usePattern)(a,I)}.test(${k})`))),(0,t.not)(S)}function g(k){i.code((0,t._)`delete ${u}[${k}]`)}function C(k){if(m.removeAdditional==="all"||m.removeAdditional&&l===!1){g(k);return}if(l===!1){a.setParams({additionalProperty:k}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");m.removeAdditional==="failing"?(b(k,S,!1),i.if((0,t.not)(S),()=>{a.reset(),g(k)})):(b(k,S),f||i.if((0,t.not)(S),()=>i.break()))}}function b(k,S,I){const x={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};I===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(x,S)}}};return ri.default=s,ri}var ni={},Af;function Gw(){if(Af)return ni;Af=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=Ra(),t=yr(),r=De(),n=Nf(),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)m(y)?v(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),v(y),u.allErrors||a.else().var(f,!0),a.endIf()),s.it.definedProperties.add(y),s.ok(f);function m(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return ni.default=o,ni}var oi={},qf;function Ww(){if(qf)return oi;qf=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=yr(),t=Oe(),r=De(),n=De(),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 m=h.strictSchema&&!h.allowMatchingProperties&&c.properties,v=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)m&&_(C),u.allErrors?g(C):(a.var(v,!0),g(C),a.if(v))}function _(C){for(const b in m)new RegExp(C).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${C} (use allowMatchingProperties)`)}function g(C){a.forIn("key",l,b=>{a.if((0,t._)`${(0,e.usePattern)(s,C)}.test(${b})`,()=>{const k=f.includes(C);k||s.subschema({keyword:"patternProperties",schemaProp:C,dataProp:b,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${b}]`,!0):!k&&!u.allErrors&&a.if((0,t.not)(v),()=>a.break())})})}}};return oi.default=o,oi}var si={},Lf;function Kw(){if(Lf)return si;Lf=1,Object.defineProperty(si,"__esModule",{value:!0});const e=De(),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 si.default=t,si}var ai={},jf;function Yw(){if(jf)return ai;jf=1,Object.defineProperty(ai,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:yr().validateUnion,error:{message:"must match a schema in anyOf"}};return ai.default=t,ai}var ii={},Df;function Qw(){if(Df)return ii;Df=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=Oe(),t=De(),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((m,v)=>{let y;(0,t.alwaysValidSchema)(l,m)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},p),v>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(h,(0,e._)`[${h}, ${v}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(h,v),y&&o.mergeEvaluated(y,e.Name)})})}}};return ii.default=n,ii}var li={},Uf;function Xw(){if(Uf)return li;Uf=1,Object.defineProperty(li,"__esModule",{value:!0});const e=De(),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 li.default=t,li}var ci={},zf;function eb(){if(zf)return ci;zf=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Oe(),t=De(),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 v=a.let("ifClause");s.setParams({ifClause:v}),a.if(p,m("then",v),m("else",v))}else c?a.if(p,m("then")):a.if((0,e.not)(p),m("else"));s.pass(h,()=>s.error(!0));function f(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(v)}function m(v,y){return()=>{const w=s.subschema({keyword:v},p);a.assign(h,p),s.mergeValidEvaluated(w,h),y?a.assign(y,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return ci.default=n,ci}var ui={},Zf;function tb(){if(Zf)return ui;Zf=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=De(),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 ui.default=t,ui}var Ff;function rb(){if(Ff)return Ya;Ff=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Sf(),t=Fw(),r=xf(),n=Vw(),o=Hw(),s=Bw(),a=Jw(),i=Nf(),l=Gw(),c=Ww(),u=Kw(),h=Yw(),p=Qw(),f=Xw(),m=eb(),v=tb();function y(w=!1){const _=[u.default,h.default,p.default,f.default,m.default,v.default,a.default,i.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Ya.default=y,Ya}var di={},pi={},Vf;function nb(){if(Vf)return pi;Vf=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Oe(),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:m}=u;if(!h.validateFormats)return;i?v():y();function v(){const w=s.scopeValue("formats",{ref:m.formats,code:h.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),g=s.let("fType"),C=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(g,(0,e._)`${_}.type || "string"`).assign(C,(0,e._)`${_}.validate`),()=>s.assign(g,(0,e._)`"string"`).assign(C,_)),n.fail$data((0,e.or)(b(),k()));function b(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${C}`}function k(){const S=f.$async?(0,e._)`(${_}.async ? await ${C}(${a}) : ${C}(${a}))`:(0,e._)`${C}(${a})`,I=(0,e._)`(typeof ${C} == "function" ? ${S} : ${C}.test(${a}))`;return(0,e._)`${C} && ${C} !== true && ${g} === ${o} && !${I}`}}function y(){const w=m.formats[l];if(!w){b();return}if(w===!0)return;const[_,g,C]=k(w);_===o&&n.pass(S());function b(){if(h.strictSchema===!1){m.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function k(I){const x=I instanceof RegExp?(0,e.regexpCode)(I):h.code.formats?(0,e._)`${h.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:I,code:x});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${j}.validate`]:["string",I,j]}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 g=="function"?(0,e._)`${C}(${a})`:(0,e._)`${C}.test(${a})`}}}};return pi.default=r,pi}var Hf;function ob(){if(Hf)return di;Hf=1,Object.defineProperty(di,"__esModule",{value:!0});const t=[nb().default];return di.default=t,di}var jn={},Bf;function sb(){return Bf||(Bf=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.contentVocabulary=jn.metadataVocabulary=void 0,jn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],jn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),jn}var Jf;function ab(){if(Jf)return Aa;Jf=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Rw(),t=Zw(),r=rb(),n=ob(),o=sb(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Aa.default=s,Aa}var fi={},Yo={},Gf;function ib(){if(Gf)return Yo;Gf=1,Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Yo.DiscrError=e={})),Yo}var Wf;function lb(){if(Wf)return fi;Wf=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Oe(),t=ib(),r=Ql(),n=Oa(),o=De(),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 m=u.propertyName;if(typeof m!="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 v=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(m)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:m})),i.ok(v);function w(){const C=g();l.if(!1);for(const b in C)l.elseIf((0,e._)`${y} === ${b}`),l.assign(v,_(C[b]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:m}),l.endIf()}function _(C){const b=l.name("valid"),k=i.subschema({keyword:"oneOf",schemaProp:C},b);return i.mergeEvaluated(k,e.Name),b}function g(){var C;const b={},k=I(h);let S=!0;for(let O=0;O<f.length;O++){let U=f[O];if(U?.$ref&&!(0,o.schemaHasRulesButRef)(U,p.self.RULES)){const N=U.$ref;if(U=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,N),U instanceof r.SchemaEnv&&(U=U.schema),U===void 0)throw new n.default(p.opts.uriResolver,p.baseId,N)}const A=(C=U?.properties)===null||C===void 0?void 0:C[m];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);S=S&&(k||I(U)),x(A,O)}if(!S)throw new Error(`discriminator: "${m}" must be required`);return b;function I({required:O}){return Array.isArray(O)&&O.includes(m)}function x(O,U){if(O.const)j(O.const,U);else if(O.enum)for(const A of O.enum)j(A,U);else throw new Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function j(O,U){if(typeof O!="string"||O in b)throw new Error(`discriminator: "${m}" values must be unique strings`);b[O]=U}}}};return fi.default=a,fi}const cb={$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 Kf;function Yf(){return Kf||(Kf=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=xw(),n=ab(),o=lb(),s=cb,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(m,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=Ra();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Oe();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=Yl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=Oa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ca,Ca.exports)),Ca.exports}var ub=Yf();const Qf=An(ub);var je;(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})(je||(je={}));var nc;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(nc||(nc={}));const ce=je.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Kr=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}},oe=je.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"]),db=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class tr 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 tr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,je.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()}}tr.create=e=>new tr(e);const po=(e,t)=>{let r;switch(e.code){case oe.invalid_type:e.received===ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,je.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${je.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${je.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${je.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.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}"`:je.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case oe.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 oe.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 oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,je.assertNever(e)}return{message:r}};let Xf=po;function pb(e){Xf=e}function hi(){return Xf}const mi=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}},fb=[];function ie(e,t){const r=hi(),n=mi({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===po?void 0:po].filter(o=>!!o)});e.common.issues.push(n)}class At{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 Ce;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 At.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 Ce;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 Ce=Object.freeze({status:"aborted"}),fo=e=>({status:"dirty",value:e}),Ut=e=>({status:"valid",value:e}),oc=e=>e.status==="aborted",sc=e=>e.status==="dirty",Dn=e=>e.status==="valid",Qo=e=>typeof Promise<"u"&&e instanceof Promise;var me;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(me||(me={}));class Lr{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 eh=(e,t)=>{if(Dn(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 tr(e.common.issues);return this._error=r,this._error}}};function Re(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 Kr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Kr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new At,ctx:{common:t.parent.common,data:t.data,parsedType:Kr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Qo(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:Kr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return eh(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Kr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Dn(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=>Dn(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:Kr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Qo(o)?o:Promise.resolve(o));return eh(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:oe.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 vr({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 _r.create(this,this._def)}nullable(){return vn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zn.create(this)}promise(){return vo.create(this,this._def)}or(t){return ns.create([this,t],this._def)}and(t){return os.create(this,t,this._def)}transform(t){return new vr({...Re(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new cs({...Re(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new lc({typeName:B.ZodBranded,type:this,...Re(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new us({...Re(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 ds.create(this,t)}readonly(){return ps.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const hb=/^c[^\s-]{8,}$/i,mb=/^[0-9a-z]+$/,gb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yb=/^[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,vb=/^[a-z0-9_-]{21}$/i,_b=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wb=/^[-+]?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)?)??$/,bb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ac;const Tb=/^(?:(?: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])$/,Cb=/^(?:(?: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])$/,Sb=/^(([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]))$/,Ib=/^(([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])$/,xb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Eb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,th="((\\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])))",$b=new RegExp(`^${th}$`);function rh(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Rb(e){return new RegExp(`^${rh(e)}$`)}function nh(e){let t=`${th}T${rh(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 Pb(e,t){return!!((t==="v4"||!t)&&Tb.test(e)||(t==="v6"||!t)&&Sb.test(e))}function Mb(e,t){if(!_b.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 Ob(e,t){return!!((t==="v4"||!t)&&Cb.test(e)||(t==="v6"||!t)&&Ib.test(e))}let ho=class Ta extends Pe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ce.string){const s=this._getOrReturnCtx(t);return ie(s,{code:oe.invalid_type,expected:ce.string,received:s.parsedType}),Ce}const n=new At;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.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),ie(o,{code:oe.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?ie(o,{code:oe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ie(o,{code:oe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")bb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"email",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ac||(ac=new RegExp(kb,"u")),ac.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"emoji",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")yb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"uuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")vb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"nanoid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")hb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")mb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid2",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")gb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ulid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ie(o,{validation:"url",code:oe.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),ie(o,{validation:"regex",code:oe.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),ie(o,{code:oe.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),ie(o,{code:oe.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?nh(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?$b.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Rb(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?wb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"duration",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Pb(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ip",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Mb(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"jwt",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Ob(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cidr",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?xb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Eb.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64url",code:oe.invalid_string,message:s.message}),n.dirty()):je.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:oe.invalid_string,...me.errToObj(n)})}_addCheck(t){return new Ta({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...me.errToObj(t)})}url(t){return this._addCheck({kind:"url",...me.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...me.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...me.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...me.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...me.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...me.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...me.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...me.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...me.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...me.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...me.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...me.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,...me.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,...me.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...me.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...me.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...me.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...me.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...me.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...me.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...me.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...me.errToObj(r)})}nonempty(t){return this.min(1,me.errToObj(t))}trim(){return new Ta({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ta({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ta({...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}};ho.create=e=>new ho({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...Re(e)});function Nb(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 Xo=class Sp 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 ie(s,{code:oe.invalid_type,expected:ce.number,received:s.parsedType}),Ce}let n;const o=new At;for(const s of this._def.checks)s.kind==="int"?je.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.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),ie(n,{code:oe.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),ie(n,{code:oe.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Nb(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:oe.not_finite,message:s.message}),o.dirty()):je.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new Sp({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new Sp({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:me.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:me.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.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"&&je.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)}};Xo.create=e=>new Xo({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...Re(e)});class yn 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 At;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),ie(n,{code:oe.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),ie(n,{code:oe.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),ie(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):je.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ie(r,{code:oe.invalid_type,expected:ce.bigint,received:r.parsedType}),Ce}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new yn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new yn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.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}}yn.create=e=>new yn({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...Re(e)});let es=class extends Pe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ce.boolean){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.boolean,received:n.parsedType}),Ce}return Ut(t.data)}};es.create=e=>new es({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...Re(e)});class Un 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 ie(s,{code:oe.invalid_type,expected:ce.date,received:s.parsedType}),Ce}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ie(s,{code:oe.invalid_date}),Ce}const n=new At;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:oe.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),ie(o,{code:oe.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):je.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Un({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:me.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:me.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}}Un.create=e=>new Un({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...Re(e)});class gi extends Pe{_parse(t){if(this._getType(t)!==ce.symbol){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.symbol,received:n.parsedType}),Ce}return Ut(t.data)}}gi.create=e=>new gi({typeName:B.ZodSymbol,...Re(e)});class ts extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.undefined,received:n.parsedType}),Ce}return Ut(t.data)}}ts.create=e=>new ts({typeName:B.ZodUndefined,...Re(e)});let rs=class extends Pe{_parse(t){if(this._getType(t)!==ce.null){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.null,received:n.parsedType}),Ce}return Ut(t.data)}};rs.create=e=>new rs({typeName:B.ZodNull,...Re(e)});let mo=class extends Pe{constructor(){super(...arguments),this._any=!0}_parse(t){return Ut(t.data)}};mo.create=e=>new mo({typeName:B.ZodAny,...Re(e)});let zn=class extends Pe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ut(t.data)}};zn.create=e=>new zn({typeName:B.ZodUnknown,...Re(e)});let Yr=class extends Pe{_parse(t){const r=this._getOrReturnCtx(t);return ie(r,{code:oe.invalid_type,expected:ce.never,received:r.parsedType}),Ce}};Yr.create=e=>new Yr({typeName:B.ZodNever,...Re(e)});class yi extends Pe{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.void,received:n.parsedType}),Ce}return Ut(t.data)}}yi.create=e=>new yi({typeName:B.ZodVoid,...Re(e)});let Zn=class Fl extends Pe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ce.array)return ie(r,{code:oe.invalid_type,expected:ce.array,received:r.parsedType}),Ce;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(ie(r,{code:a?oe.too_big:oe.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&&(ie(r,{code:oe.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&&(ie(r,{code:oe.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 Lr(r,a,r.path,i)))).then(a=>At.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Lr(r,a,r.path,i)));return At.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Fl({...this._def,minLength:{value:t,message:me.toString(r)}})}max(t,r){return new Fl({...this._def,maxLength:{value:t,message:me.toString(r)}})}length(t,r){return new Fl({...this._def,exactLength:{value:t,message:me.toString(r)}})}nonempty(t){return this.min(1,t)}};Zn.create=(e,t)=>new Zn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...Re(t)});function go(e){if(e instanceof ar){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=_r.create(go(n))}return new ar({...e._def,shape:()=>t})}else return e instanceof Zn?new Zn({...e._def,type:go(e.element)}):e instanceof _r?_r.create(go(e.unwrap())):e instanceof vn?vn.create(go(e.unwrap())):e instanceof jr?jr.create(e.items.map(t=>go(t))):e}let ar=class qr 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=je.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 ie(c,{code:oe.invalid_type,expected:ce.object,received:c.parsedType}),Ce}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Yr&&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 Lr(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Yr){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&&(ie(o,{code:oe.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 Lr(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=>At.mergeObjectSync(n,c)):At.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return me.errToObj,new qr({...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:me.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new qr({...this._def,unknownKeys:"strip"})}passthrough(){return new qr({...this._def,unknownKeys:"passthrough"})}extend(t){return new qr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new qr({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 qr({...this._def,catchall:t})}pick(t){const r={};for(const n of je.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new qr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of je.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new qr({...this._def,shape:()=>r})}deepPartial(){return go(this)}partial(t){const r={};for(const n of je.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new qr({...this._def,shape:()=>r})}required(t){const r={};for(const n of je.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof _r;)s=s._def.innerType;r[n]=s}return new qr({...this._def,shape:()=>r})}keyof(){return ah(je.objectKeys(this.shape))}};ar.create=(e,t)=>new ar({shape:()=>e,unknownKeys:"strip",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)}),ar.strictCreate=(e,t)=>new ar({shape:()=>e,unknownKeys:"strict",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)}),ar.lazycreate=(e,t)=>new ar({shape:e,unknownKeys:"strip",catchall:Yr.create(),typeName:B.ZodObject,...Re(t)});let ns=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 tr(i.ctx.common.issues));return ie(r,{code:oe.invalid_union,unionErrors:a}),Ce}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 tr(l));return ie(r,{code:oe.invalid_union,unionErrors:i}),Ce}}get options(){return this._def.options}};ns.create=(e,t)=>new ns({options:e,typeName:B.ZodUnion,...Re(t)});const Qr=e=>e instanceof ss?Qr(e.schema):e instanceof vr?Qr(e.innerType()):e instanceof as?[e.value]:e instanceof is?e.options:e instanceof ls?je.objectValues(e.enum):e instanceof cs?Qr(e._def.innerType):e instanceof ts?[void 0]:e instanceof rs?[null]:e instanceof _r?[void 0,...Qr(e.unwrap())]:e instanceof vn?[null,...Qr(e.unwrap())]:e instanceof lc||e instanceof ps?Qr(e.unwrap()):e instanceof us?Qr(e._def.innerType):[];let oh=class pw extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.object)return ie(r,{code:oe.invalid_type,expected:ce.object,received:r.parsedType}),Ce;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}):(ie(r,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ce)}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=Qr(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 pw({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...Re(n)})}};function ic(e,t){const r=Kr(e),n=Kr(t);if(e===t)return{valid:!0,data:e};if(r===ce.object&&n===ce.object){const o=je.objectKeys(t),s=je.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=ic(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=ic(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 os=class extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(oc(s)||oc(a))return Ce;const i=ic(s.value,a.value);return i.valid?((sc(s)||sc(a))&&r.dirty(),{status:r.value,value:i.data}):(ie(n,{code:oe.invalid_intersection_types}),Ce)};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}))}};os.create=(e,t,r)=>new os({left:e,right:t,typeName:B.ZodIntersection,...Re(r)});class jr extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.array)return ie(n,{code:oe.invalid_type,expected:ce.array,received:n.parsedType}),Ce;if(n.data.length<this._def.items.length)return ie(n,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ce;!this._def.rest&&n.data.length>this._def.items.length&&(ie(n,{code:oe.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 Lr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>At.mergeArray(r,a)):At.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new jr({...this._def,rest:t})}}jr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new jr({items:e,typeName:B.ZodTuple,rest:null,...Re(t)})};let sh=class Ip 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 ie(n,{code:oe.invalid_type,expected:ce.object,received:n.parsedType}),Ce;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Lr(n,i,n.path,i)),value:a._parse(new Lr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?At.mergeObjectAsync(r,o):At.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Pe?new Ip({keyType:t,valueType:r,typeName:B.ZodRecord,...Re(n)}):new Ip({keyType:ho.create(),valueType:t,typeName:B.ZodRecord,...Re(r)})}};class vi 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 ie(n,{code:oe.invalid_type,expected:ce.map,received:n.parsedType}),Ce;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Lr(n,i,n.path,[c,"key"])),value:s._parse(new Lr(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 Ce;(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 Ce;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}vi.create=(e,t,r)=>new vi({valueType:t,keyType:e,typeName:B.ZodMap,...Re(r)});class Fn extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.set)return ie(n,{code:oe.invalid_type,expected:ce.set,received:n.parsedType}),Ce;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ie(n,{code:oe.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&&(ie(n,{code:oe.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 Ce;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 Lr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Fn({...this._def,minSize:{value:t,message:me.toString(r)}})}max(t,r){return new Fn({...this._def,maxSize:{value:t,message:me.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Fn.create=(e,t)=>new Fn({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...Re(t)});class yo extends Pe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.function)return ie(r,{code:oe.invalid_type,expected:ce.function,received:r.parsedType}),Ce;function n(i,l){return mi({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hi(),po].filter(c=>!!c),issueData:{code:oe.invalid_arguments,argumentsError:l}})}function o(i,l){return mi({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hi(),po].filter(c=>!!c),issueData:{code:oe.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof vo){const i=this;return Ut(async function(...l){const c=new tr([]),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 Ut(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new tr([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),h=i._def.returns.safeParse(u,s);if(!h.success)throw new tr([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new yo({...this._def,args:jr.create(t).rest(zn.create())})}returns(t){return new yo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new yo({args:t||jr.create([]).rest(zn.create()),returns:r||zn.create(),typeName:B.ZodFunction,...Re(n)})}}let ss=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})}};ss.create=(e,t)=>new ss({getter:e,typeName:B.ZodLazy,...Re(t)});let as=class extends Pe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ie(r,{received:r.data,code:oe.invalid_literal,expected:this._def.value}),Ce}return{status:"valid",value:t.data}}get value(){return this._def.value}};as.create=(e,t)=>new as({value:e,typeName:B.ZodLiteral,...Re(t)});function ah(e,t){return new is({values:e,typeName:B.ZodEnum,...Re(t)})}let is=class xp extends Pe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ie(r,{expected:je.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Ce}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 ie(r,{received:r.data,code:oe.invalid_enum_value,options:n}),Ce}return Ut(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 xp.create(t,{...this._def,...r})}exclude(t,r=this._def){return xp.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};is.create=ah;class ls extends Pe{_parse(t){const r=je.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ce.string&&n.parsedType!==ce.number){const o=je.objectValues(r);return ie(n,{expected:je.joinValues(o),received:n.parsedType,code:oe.invalid_type}),Ce}if(this._cache||(this._cache=new Set(je.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=je.objectValues(r);return ie(n,{received:n.data,code:oe.invalid_enum_value,options:o}),Ce}return Ut(t.data)}get enum(){return this._def.values}}ls.create=(e,t)=>new ls({values:e,typeName:B.ZodNativeEnum,...Re(t)});class vo 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 ie(r,{code:oe.invalid_type,expected:ce.promise,received:r.parsedType}),Ce;const n=r.parsedType===ce.promise?r.data:Promise.resolve(r.data);return Ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}vo.create=(e,t)=>new vo({type:e,typeName:B.ZodPromise,...Re(t)});class vr extends Pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{ie(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 Ce;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?Ce:l.status==="dirty"||r.value==="dirty"?fo(l.value):l});{if(r.value==="aborted")return Ce;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?Ce:i.status==="dirty"||r.value==="dirty"?fo(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"?Ce:(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"?Ce:(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(!Dn(a))return Ce;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=>Dn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):Ce);je.assertNever(o)}}vr.create=(e,t,r)=>new vr({schema:e,typeName:B.ZodEffects,effect:t,...Re(r)}),vr.createWithPreprocess=(e,t,r)=>new vr({schema:t,effect:{type:"preprocess",transform:e},typeName:B.ZodEffects,...Re(r)});let _r=class extends Pe{_parse(t){return this._getType(t)===ce.undefined?Ut(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:B.ZodOptional,...Re(t)});let vn=class extends Pe{_parse(t){return this._getType(t)===ce.null?Ut(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};vn.create=(e,t)=>new vn({innerType:e,typeName:B.ZodNullable,...Re(t)});let cs=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}};cs.create=(e,t)=>new cs({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Re(t)});let us=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 Qo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new tr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new tr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};us.create=(e,t)=>new us({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Re(t)});class _i extends Pe{_parse(t){if(this._getType(t)!==ce.nan){const n=this._getOrReturnCtx(t);return ie(n,{code:oe.invalid_type,expected:ce.nan,received:n.parsedType}),Ce}return{status:"valid",value:t.data}}}_i.create=e=>new _i({typeName:B.ZodNaN,...Re(e)});const Ab=Symbol("zod_brand");class lc 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 ds 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"?Ce:s.status==="dirty"?(r.dirty(),fo(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"?Ce: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 ds({in:t,out:r,typeName:B.ZodPipeline})}}let ps=class extends Pe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Dn(o)&&(o.value=Object.freeze(o.value)),o);return Qo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};ps.create=(e,t)=>new ps({innerType:e,typeName:B.ZodReadonly,...Re(t)});function ih(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function lh(e,t={},r){return e?mo.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=ih(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=ih(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):mo.create()}const qb={object:ar.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 Lb=(e,t={message:`Input not instance of ${e.name}`})=>lh(r=>r instanceof e,t),Ue=ho.create,ir=Xo.create,jb=_i.create,Db=yn.create,ch=es.create,Ub=Un.create,zb=gi.create,Zb=ts.create,Fb=rs.create,Vb=mo.create,Hb=zn.create,Bb=Yr.create,Jb=yi.create,Xr=Zn.create,Bt=ar.create,Gb=ar.strictCreate,wi=ns.create,Wb=oh.create,Kb=os.create,Yb=jr.create,Qb=sh.create,Xb=vi.create,e3=Fn.create,t3=yo.create,r3=ss.create,n3=as.create,fs=is.create,o3=ls.create,s3=vo.create,uh=vr.create,a3=_r.create,i3=vn.create,l3=vr.createWithPreprocess,c3=ds.create,u3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Ab,DIRTY:fo,EMPTY_PATH:fb,INVALID:Ce,NEVER:Ce,OK:Ut,ParseStatus:At,Schema:Pe,ZodAny:mo,ZodArray:Zn,ZodBigInt:yn,ZodBoolean:es,ZodBranded:lc,ZodCatch:us,ZodDate:Un,ZodDefault:cs,ZodDiscriminatedUnion:oh,ZodEffects:vr,ZodEnum:is,ZodError:tr,get ZodFirstPartyTypeKind(){return B},ZodFunction:yo,ZodIntersection:os,ZodIssueCode:oe,ZodLazy:ss,ZodLiteral:as,ZodMap:vi,ZodNaN:_i,ZodNativeEnum:ls,ZodNever:Yr,ZodNull:rs,ZodNullable:vn,ZodNumber:Xo,ZodObject:ar,ZodOptional:_r,ZodParsedType:ce,ZodPipeline:ds,ZodPromise:vo,ZodReadonly:ps,ZodRecord:sh,ZodSchema:Pe,ZodSet:Fn,ZodString:ho,ZodSymbol:gi,ZodTransformer:vr,ZodTuple:jr,ZodType:Pe,ZodUndefined:ts,ZodUnion:ns,ZodUnknown:zn,ZodVoid:yi,addIssueToContext:ie,any:Vb,array:Xr,bigint:Db,boolean:ch,coerce:{string:(e=>ho.create({...e,coerce:!0})),number:(e=>Xo.create({...e,coerce:!0})),boolean:(e=>es.create({...e,coerce:!0})),bigint:(e=>yn.create({...e,coerce:!0})),date:(e=>Un.create({...e,coerce:!0}))},custom:lh,date:Ub,datetimeRegex:nh,defaultErrorMap:po,discriminatedUnion:Wb,effect:uh,enum:fs,function:t3,getErrorMap:hi,getParsedType:Kr,instanceof:Lb,intersection:Kb,isAborted:oc,isAsync:Qo,isDirty:sc,isValid:Dn,late:qb,lazy:r3,literal:n3,makeIssue:mi,map:Xb,nan:jb,nativeEnum:o3,never:Bb,null:Fb,nullable:i3,number:ir,object:Bt,get objectUtil(){return nc},oboolean:()=>ch().optional(),onumber:()=>ir().optional(),optional:a3,ostring:()=>Ue().optional(),pipeline:c3,preprocess:l3,promise:s3,quotelessJson:db,record:Qb,set:e3,setErrorMap:pb,strictObject:Gb,string:Ue,symbol:zb,transformer:uh,tuple:Yb,undefined:Zb,union:wi,unknown:Hb,get util(){return je},void:Jb},Symbol.toStringTag,{value:"Module"})),dh=Object.freeze({status:"aborted"});function J(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 hs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ph={};function _n(e){return ph}function fh(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 d3(e,t){return typeof t=="bigint"?t.toString():t}function cc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function uc(e){return e==null}function dc(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function p3(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 Fe(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 ms(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gs(e){return JSON.stringify(e)}const hh=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function bi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const f3=cc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ki(e){if(bi(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(bi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const h3=new Set(["string","number","symbol"]);function ys(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wn(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 m3(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const g3={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 y3(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function v3(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function _3(e,t){if(!ki(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 ms(this,"shape",n),n},checks:[]};return wn(e,r)}function w3(e,t){return wn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ms(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function b3(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function k3(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function vs(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Vn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ti(e){return typeof e=="string"?e:e?.message}function bn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Ti(e.inst?._zod.def?.error?.(e))??Ti(t?.error?.(e))??Ti(r.customError?.(e))??Ti(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function pc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _s(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const mh=(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,d3,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},gh=J("$ZodError",mh),Ci=J("$ZodError",mh,{Parent:Error});function T3(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 C3(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 yh=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 hs;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>bn(l,s,_n())));throw hh(i,o?.callee),i}return a.value},S3=yh(Ci),vh=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=>bn(l,s,_n())));throw hh(i,o?.callee),i}return a.value},I3=vh(Ci),_h=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 hs;return s.issues.length?{success:!1,error:new(e??gh)(s.issues.map(a=>bn(a,o,_n())))}:{success:!0,data:s.value}},fc=_h(Ci),wh=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=>bn(a,o,_n())))}:{success:!0,data:s.value}},hc=wh(Ci),x3=/^[cC][^\s-]{8,}$/,E3=/^[0-9a-z]+$/,$3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,R3=/^[0-9a-vA-V]{20}$/,P3=/^[A-Za-z0-9]{27}$/,M3=/^[a-zA-Z0-9_-]{21}$/,O3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,N3=/^([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})$/,bh=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)$/,A3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,q3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function L3(){return new RegExp(q3,"u")}const j3=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,D3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,U3=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,z3=/^(([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])$/,Z3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kh=/^[A-Za-z0-9_-]*$/,F3=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,V3=/^\+(?:[0-9]){6,14}[0-9]$/,Th="(?:(?:\\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])))",H3=new RegExp(`^${Th}$`);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 B3(e){return new RegExp(`^${Ch(e)}$`)}function J3(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(`^${Th}T(?:${n})$`)}const G3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},W3=/^\d+$/,K3=/^-?\d+(?:\.\d+)?/i,Y3=/true|false/i,Q3=/null/i,X3=/^[^A-Z]*$/,e9=/^[^a-z]*$/,Jt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sh={number:"number",bigint:"bigint",object:"date"},Ih=J("$ZodCheckLessThan",(e,t)=>{Jt.init(e,t);const r=Sh[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})}}),xh=J("$ZodCheckGreaterThan",(e,t)=>{Jt.init(e,t);const r=Sh[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})}}),t9=J("$ZodCheckMultipleOf",(e,t)=>{Jt.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):p3(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})}}),r9=J("$ZodCheckNumberFormat",(e,t)=>{Jt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=g3[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=W3)}),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})}}),n9=J("$ZodCheckMaxLength",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!uc(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=pc(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),o9=J("$ZodCheckMinLength",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!uc(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=pc(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),s9=J("$ZodCheckLengthEquals",(e,t)=>{var r;Jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!uc(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=pc(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=J("$ZodCheckStringFormat",(e,t)=>{var r,n;Jt.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=()=>{})}),a9=J("$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})}}),i9=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=X3),Si.init(e,t)}),l9=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=e9),Si.init(e,t)}),c9=J("$ZodCheckIncludes",(e,t)=>{Jt.init(e,t);const r=ys(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})}}),u9=J("$ZodCheckStartsWith",(e,t)=>{Jt.init(e,t);const r=new RegExp(`^${ys(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})}}),d9=J("$ZodCheckEndsWith",(e,t)=>{Jt.init(e,t);const r=new RegExp(`.*${ys(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})}}),p9=J("$ZodCheckOverwrite",(e,t)=>{Jt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class f9{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
|
|
11
|
-
if (${
|
|
10
|
+
`))}}const h9={major:4,minor:0,patch:0},Ke=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=h9;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=vs(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 hs;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==h&&(l||(l=vs(s,h)))});else{if(s.issues.length===h)continue;l||(l=vs(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 hs;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=fc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return hc(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),mc=J("$ZodString",(e,t)=>{Ke.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??G3(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}}),rt=J("$ZodStringFormat",(e,t)=>{Si.init(e,t),mc.init(e,t)}),m9=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=N3),rt.init(e,t)}),g9=J("$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=bh(n))}else t.pattern??(t.pattern=bh());rt.init(e,t)}),y9=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=A3),rt.init(e,t)}),v9=J("$ZodURL",(e,t)=>{rt.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:F3.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})}}}),_9=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=L3()),rt.init(e,t)}),w9=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=M3),rt.init(e,t)}),b9=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=x3),rt.init(e,t)}),k9=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=E3),rt.init(e,t)}),T9=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=$3),rt.init(e,t)}),C9=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=R3),rt.init(e,t)}),S9=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=P3),rt.init(e,t)}),I9=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=J3(t)),rt.init(e,t)}),x9=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=H3),rt.init(e,t)}),E9=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=B3(t)),rt.init(e,t)}),$9=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=O3),rt.init(e,t)}),R9=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=j3),rt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),P9=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=D3),rt.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})}}}),M9=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=U3),rt.init(e,t)}),O9=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=z3),rt.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 Eh(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const N9=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Z3),rt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Eh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function A9(e){if(!kh.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Eh(r)}const q9=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=kh),rt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{A9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),L9=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=V3),rt.init(e,t)});function j9(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const D9=J("$ZodJWT",(e,t)=>{rt.init(e,t),e._zod.check=r=>{j9(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),$h=J("$ZodNumber",(e,t)=>{Ke.init(e,t),e._zod.pattern=e._zod.bag.pattern??K3,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),U9=J("$ZodNumber",(e,t)=>{r9.init(e,t),$h.init(e,t)}),z9=J("$ZodBoolean",(e,t)=>{Ke.init(e,t),e._zod.pattern=Y3,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}}),Z9=J("$ZodNull",(e,t)=>{Ke.init(e,t),e._zod.pattern=Q3,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}}),F9=J("$ZodAny",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),V9=J("$ZodUnknown",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),H9=J("$ZodNever",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Rh(e,t,r){e.issues.length&&t.issues.push(...Vn(r,e.issues)),t.value[r]=e.value}const B9=J("$ZodArray",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>Rh(c,r,a))):Rh(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Ii(e,t,r){e.issues.length&&t.issues.push(...Vn(r,e.issues)),t.value[r]=e.value}function Ph(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(...Vn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const Mh=J("$ZodObject",(e,t)=>{Ke.init(e,t);const r=cc(()=>{const h=Object.keys(t.shape);for(const f of h)if(!(t.shape[f]instanceof Ke))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=m3(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(p)}});Fe(e._zod,"propValues",()=>{const h=t.shape,p={};for(const f in h){const m=h[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(const v of m.values)p[f].add(v)}}return p});const n=h=>{const p=new f9(["shape","payload","ctx"]),f=r.value,m=_=>{const g=gs(_);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const _ of f.keys)v[_]=`key_${y++}`;p.write("const newResult = {}");for(const _ of f.keys)if(f.optionalKeys.has(_)){const g=v[_];p.write(`const ${g} = ${m(_)};`);const C=gs(_);p.write(`
|
|
11
|
+
if (${g}.issues.length) {
|
|
12
12
|
if (input[${C}] === undefined) {
|
|
13
13
|
if (${C} in input) {
|
|
14
14
|
newResult[${C}] = undefined;
|
|
15
15
|
}
|
|
16
16
|
} else {
|
|
17
17
|
payload.issues = payload.issues.concat(
|
|
18
|
-
${
|
|
18
|
+
${g}.issues.map((iss) => ({
|
|
19
19
|
...iss,
|
|
20
20
|
path: iss.path ? [${C}, ...iss.path] : [${C}],
|
|
21
21
|
}))
|
|
22
22
|
);
|
|
23
23
|
}
|
|
24
|
-
} else if (${
|
|
24
|
+
} else if (${g}.value === undefined) {
|
|
25
25
|
if (${C} in input) newResult[${C}] = undefined;
|
|
26
26
|
} else {
|
|
27
|
-
newResult[${C}] = ${
|
|
27
|
+
newResult[${C}] = ${g}.value;
|
|
28
28
|
}
|
|
29
|
-
`)}else{const
|
|
30
|
-
if (${
|
|
29
|
+
`)}else{const g=v[_];p.write(`const ${g} = ${m(_)};`),p.write(`
|
|
30
|
+
if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
|
|
31
31
|
...iss,
|
|
32
|
-
path: iss.path ? [${
|
|
33
|
-
})));`),p.write(`newResult[${hs(_)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,m)=>w(h,_,m)};let o;const s=vi,a=!ah.jitless,l=a&&i3.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 b=m[C],k=b._zod.run({value:f[C],issues:[]},p),S=b._zod.optin==="optional"&&b._zod.optout==="optional";k instanceof Promise?g.push(k.then(I=>S?Sh(I,h,C,f):Ti(I,h,C))):S?Sh(k,h,C,f):Ti(k,h,C)}}if(!c)return g.length?Promise.all(g).then(()=>h):h;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const m of Object.keys(f)){if(y.has(m))continue;if(_==="never"){v.push(m);continue}const C=w.run({value:f[m],issues:[]},p);C instanceof Promise?g.push(C.then(b=>Ti(b,h,m))):Ti(C,h,m)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>h):h}});function Eh(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=>wn(s,n,vn())))}),t}const xh=J("$ZodUnion",(e,t)=>{Ke.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(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=>oc(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=>Eh(a,r,e,n)):Eh(s,r,e,n)}}),z9=J("$ZodDiscriminatedUnion",(e,t)=>{xh.init(e,t);const r=e._zod.parse;Fe(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=rc(()=>{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(!vi(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)}}),Z9=J("$ZodIntersection",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>$h(r,l,c)):$h(r,s,a)}});function cc(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(_i(e)&&_i(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=cc(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=cc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function $h(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),gs(e))return e;const n=cc(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 F9=J("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!_i(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(...Fn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Fn(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=>wn(c,n,vn())),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(...Fn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Fn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),V9=J("$ZodEnum",(e,t)=>{Ke.init(e,t);const r=ih(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>l3.has(typeof n)).map(n=>typeof n=="string"?ms(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}}),H9=J("$ZodLiteral",(e,t)=>{Ke.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ms(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}}),B9=J("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new ps;return r.value=o,r}}),J9=J("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${oc(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)}),G9=J("$ZodNullable",(e,t)=>{Ke.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${oc(r.source)}|null)$`):void 0}),Fe(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)}),W9=J("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(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=>Rh(s,t)):Rh(o,t)}});function Rh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const K9=J("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(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))}),Y9=J("$ZodNonOptional",(e,t)=>{Ke.init(e,t),Fe(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=>Ph(s,e)):Ph(o,e)}});function Ph(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 Q9=J("$ZodCatch",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(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=>wn(a,n,vn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>wn(s,n,vn()))},input:r.value}),r.issues=[]),r)}}),X9=J("$ZodPipe",(e,t)=>{Ke.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(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=>Mh(s,t,n)):Mh(o,t,n)}});function Mh(e,t,r){return gs(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const e4=J("$ZodReadonly",(e,t)=>{Ke.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(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(Oh):Oh(o)}});function Oh(e){return e.value=Object.freeze(e.value),e}const t4=J("$ZodLazy",(e,t)=>{Ke.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),r4=J("$ZodCustom",(e,t)=>{Jt.init(e,t),Ke.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Nh(s,r,n,e));Nh(o,r,n,e)}});function Nh(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(ys(o))}}class Ah{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 n4(){return new Ah}const vs=n4();function o4(e,t){return new e({type:"string",...fe(t)})}function s4(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function qh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function a4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function i4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function l4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function c4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function Lh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function u4(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function d4(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function p4(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function f4(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function h4(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function m4(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function g4(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function y4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function v4(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function _4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(t)})}function w4(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function jh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function b4(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function k4(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function T4(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function C4(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function S4(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function I4(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function E4(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function x4(e,t){return new e({type:"number",checks:[],...fe(t)})}function $4(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function R4(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function P4(e,t){return new e({type:"boolean",...fe(t)})}function M4(e,t){return new e({type:"null",...fe(t)})}function O4(e){return new e({type:"any"})}function N4(e){return new e({type:"unknown"})}function A4(e,t){return new e({type:"never",...fe(t)})}function Dh(e,t){return new wh({check:"less_than",...fe(t),value:e,inclusive:!1})}function uc(e,t){return new wh({check:"less_than",...fe(t),value:e,inclusive:!0})}function Uh(e,t){return new bh({check:"greater_than",...fe(t),value:e,inclusive:!1})}function dc(e,t){return new bh({check:"greater_than",...fe(t),value:e,inclusive:!0})}function zh(e,t){return new W3({check:"multiple_of",...fe(t),value:e})}function Zh(e,t){return new Y3({check:"max_length",...fe(t),maximum:e})}function Ci(e,t){return new Q3({check:"min_length",...fe(t),minimum:e})}function Fh(e,t){return new X3({check:"length_equals",...fe(t),length:e})}function q4(e,t){return new e9({check:"string_format",format:"regex",...fe(t),pattern:e})}function L4(e){return new t9({check:"string_format",format:"lowercase",...fe(e)})}function j4(e){return new r9({check:"string_format",format:"uppercase",...fe(e)})}function D4(e,t){return new n9({check:"string_format",format:"includes",...fe(t),includes:e})}function U4(e,t){return new o9({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function z4(e,t){return new s9({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function _s(e){return new a9({check:"overwrite",tx:e})}function Z4(e){return _s(t=>t.normalize(e))}function F4(){return _s(e=>e.trim())}function V4(){return _s(e=>e.toLowerCase())}function H4(){return _s(e=>e.toUpperCase())}function B4(e,t,r){return new e({type:"array",element:t,...fe(r)})}function J4(e,t,r){const n=fe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function G4(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??vs,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:v,maximum:y,format:w,patterns:_,contentEncoding:m}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),m&&(g.contentEncoding=m),_&&_.size>0){const C=[..._];C.length===1?g.pattern=C[0].source:C.length>1&&(i.schema.allOf=[...C.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const g=f,{minimum:v,maximum:y,format:w,multipleOf:_,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 v=="number"&&(g.minimum=v,typeof C=="number"&&(C>=v?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 _=="number"&&(g.multipleOf=_);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:v,maximum:y}=t._zod.bag;typeof v=="number"&&(g.minItems=v),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 v=o.shape;for(const _ in v)g.properties[_]=this.process(v[_],{...h,path:[...h.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const m=o.shape[_]._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((v,y)=>this.process(v,{...h,path:[...h.path,"anyOf",y]}));break}case"intersection":{const g=f,v=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,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];g.allOf=_;break}case"tuple":{const g=f;g.type="array";const v=o.items.map((_,m)=>this.process(_,{...h,path:[...h.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const _=this.process(o.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?g.items=_:g.additionalItems=_}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,v=ih(o.entries);v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),g.enum=v;break}case"literal":{const g=f,v=[];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");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];g.type=y===null?"null":typeof y,g.const=y}else v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),v.every(y=>typeof y=="boolean")&&(g.type="string"),v.every(y=>y===null)&&(g.type="null"),g.enum=v;break}case"file":{const g=f,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:_}=t._zod.bag;y!==void 0&&(v.minLength=y),w!==void 0&&(v.maxLength=w),_?_.length===1?(v.contentMediaType=_[0],Object.assign(g,v)):g.anyOf=_.map(m=>({...v,contentMediaType:m})):Object.assign(g,v);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,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");g.type="string",g.pattern=v.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"&&bt(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 v=n.external.registry.get(u[0])?.id,y=n.external.uri??(_=>_);if(v)return{ref:y(v)};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 v in g)delete g[v];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>
|
|
32
|
+
path: iss.path ? [${gs(_)}, ...iss.path] : [${gs(_)}]
|
|
33
|
+
})));`),p.write(`newResult[${gs(_)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,g)=>w(h,_,g)};let o;const s=bi,a=!ph.jitless,l=a&&f3.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 m=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),h=o(h,p);else{h.value={};const g=u.shape;for(const C of u.keys){const b=g[C],k=b._zod.run({value:f[C],issues:[]},p),S=b._zod.optin==="optional"&&b._zod.optout==="optional";k instanceof Promise?m.push(k.then(I=>S?Ph(I,h,C,f):Ii(I,h,C))):S?Ph(k,h,C,f):Ii(k,h,C)}}if(!c)return m.length?Promise.all(m).then(()=>h):h;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const g of Object.keys(f)){if(y.has(g))continue;if(_==="never"){v.push(g);continue}const C=w.run({value:f[g],issues:[]},p);C instanceof Promise?m.push(C.then(b=>Ii(b,h,g))):Ii(C,h,g)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),m.length?Promise.all(m).then(()=>h):h}});function Oh(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=>bn(s,n,_n())))}),t}const Nh=J("$ZodUnion",(e,t)=>{Ke.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(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=>dc(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=>Oh(a,r,e,n)):Oh(s,r,e,n)}}),J9=J("$ZodDiscriminatedUnion",(e,t)=>{Nh.init(e,t);const r=e._zod.parse;Fe(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=cc(()=>{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(!bi(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)}}),G9=J("$ZodIntersection",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Ah(r,l,c)):Ah(r,s,a)}});function gc(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(ki(e)&&ki(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=gc(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=gc(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 Ah(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),vs(e))return e;const n=gc(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 W9=J("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!ki(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(...Vn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Vn(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=>bn(c,n,_n())),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(...Vn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Vn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),K9=J("$ZodEnum",(e,t)=>{Ke.init(e,t);const r=fh(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>h3.has(typeof n)).map(n=>typeof n=="string"?ys(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}}),Y9=J("$ZodLiteral",(e,t)=>{Ke.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ys(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}}),Q9=J("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new hs;return r.value=o,r}}),X9=J("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${dc(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)}),ek=J("$ZodNullable",(e,t)=>{Ke.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${dc(r.source)}|null)$`):void 0}),Fe(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)}),tk=J("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(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=>qh(s,t)):qh(o,t)}});function qh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const rk=J("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(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))}),nk=J("$ZodNonOptional",(e,t)=>{Ke.init(e,t),Fe(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=>Lh(s,e)):Lh(o,e)}});function Lh(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 ok=J("$ZodCatch",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(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=>bn(a,n,_n()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>bn(s,n,_n()))},input:r.value}),r.issues=[]),r)}}),sk=J("$ZodPipe",(e,t)=>{Ke.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(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=>jh(s,t,n)):jh(o,t,n)}});function jh(e,t,r){return vs(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const ak=J("$ZodReadonly",(e,t)=>{Ke.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(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(Dh):Dh(o)}});function Dh(e){return e.value=Object.freeze(e.value),e}const ik=J("$ZodLazy",(e,t)=>{Ke.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),lk=J("$ZodCustom",(e,t)=>{Jt.init(e,t),Ke.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Uh(s,r,n,e));Uh(o,r,n,e)}});function Uh(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(_s(o))}}class zh{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 ck(){return new zh}const ws=ck();function uk(e,t){return new e({type:"string",...fe(t)})}function dk(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function Zh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function pk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function fk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function hk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function mk(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function Fh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function gk(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function yk(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function vk(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function _k(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function wk(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function bk(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function kk(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function Tk(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function Ck(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function Sk(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(t)})}function Ik(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function Vh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function xk(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function Ek(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function $k(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function Rk(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function Pk(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function Mk(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function Ok(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function Nk(e,t){return new e({type:"number",checks:[],...fe(t)})}function Ak(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function qk(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function Lk(e,t){return new e({type:"boolean",...fe(t)})}function jk(e,t){return new e({type:"null",...fe(t)})}function Dk(e){return new e({type:"any"})}function Uk(e){return new e({type:"unknown"})}function zk(e,t){return new e({type:"never",...fe(t)})}function Hh(e,t){return new Ih({check:"less_than",...fe(t),value:e,inclusive:!1})}function yc(e,t){return new Ih({check:"less_than",...fe(t),value:e,inclusive:!0})}function Bh(e,t){return new xh({check:"greater_than",...fe(t),value:e,inclusive:!1})}function vc(e,t){return new xh({check:"greater_than",...fe(t),value:e,inclusive:!0})}function Jh(e,t){return new t9({check:"multiple_of",...fe(t),value:e})}function Gh(e,t){return new n9({check:"max_length",...fe(t),maximum:e})}function xi(e,t){return new o9({check:"min_length",...fe(t),minimum:e})}function Wh(e,t){return new s9({check:"length_equals",...fe(t),length:e})}function Zk(e,t){return new a9({check:"string_format",format:"regex",...fe(t),pattern:e})}function Fk(e){return new i9({check:"string_format",format:"lowercase",...fe(e)})}function Vk(e){return new l9({check:"string_format",format:"uppercase",...fe(e)})}function Hk(e,t){return new c9({check:"string_format",format:"includes",...fe(t),includes:e})}function Bk(e,t){return new u9({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function Jk(e,t){return new d9({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function bs(e){return new p9({check:"overwrite",tx:e})}function Gk(e){return bs(t=>t.normalize(e))}function Wk(){return bs(e=>e.trim())}function Kk(){return bs(e=>e.toLowerCase())}function Yk(){return bs(e=>e.toUpperCase())}function Qk(e,t,r){return new e({type:"array",element:t,...fe(r)})}function Xk(e,t,r){const n=fe(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,...fe(r)})}class Kh{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??ws,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 m=f;m.type="string";const{minimum:v,maximum:y,format:w,patterns:_,contentEncoding:g}=t._zod.bag;if(typeof v=="number"&&(m.minLength=v),typeof y=="number"&&(m.maxLength=y),w&&(m.format=s[w]??w,m.format===""&&delete m.format),g&&(m.contentEncoding=g),_&&_.size>0){const C=[..._];C.length===1?m.pattern=C[0].source:C.length>1&&(i.schema.allOf=[...C.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const m=f,{minimum:v,maximum:y,format:w,multipleOf:_,exclusiveMaximum:g,exclusiveMinimum:C}=t._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof C=="number"&&(m.exclusiveMinimum=C),typeof v=="number"&&(m.minimum=v,typeof C=="number"&&(C>=v?delete m.minimum:delete m.exclusiveMinimum)),typeof g=="number"&&(m.exclusiveMaximum=g),typeof y=="number"&&(m.maximum=y,typeof g=="number"&&(g<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{const m=f;m.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 m=f,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(m.minItems=v),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...h,path:[...h.path,"items"]});break}case"object":{const m=f;m.type="object",m.properties={};const v=o.shape;for(const _ in v)m.properties[_]=this.process(v[_],{...h,path:[...h.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const g=o.shape[_]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));w.size>0&&(m.required=Array.from(w)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=f;m.anyOf=o.options.map((v,y)=>this.process(v,{...h,path:[...h.path,"anyOf",y]}));break}case"intersection":{const m=f,v=this.process(o.left,{...h,path:[...h.path,"allOf",0]}),y=this.process(o.right,{...h,path:[...h.path,"allOf",1]}),w=g=>"allOf"in g&&Object.keys(g).length===1,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];m.allOf=_;break}case"tuple":{const m=f;m.type="array";const v=o.items.map((_,g)=>this.process(_,{...h,path:[...h.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?m.prefixItems=v:m.items=v,o.rest){const _=this.process(o.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...h,path:[...h.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(m.minItems=y),typeof w=="number"&&(m.maxItems=w);break}case"record":{const m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...h,path:[...h.path,"propertyNames"]}),m.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 m=f,v=fh(o.entries);v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),m.enum=v;break}case"literal":{const m=f,v=[];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");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];m.type=y===null?"null":typeof y,m.const=y}else v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),v.every(y=>typeof y=="boolean")&&(m.type="string"),v.every(y=>y===null)&&(m.type="null"),m.enum=v;break}case"file":{const m=f,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:_}=t._zod.bag;y!==void 0&&(v.minLength=y),w!==void 0&&(v.maxLength=w),_?_.length===1?(v.contentMediaType=_[0],Object.assign(m,v)):m.anyOf=_.map(g=>({...v,contentMediaType:g})):Object.assign(m,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,h);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,h),i.ref=o.innerType;break}case"success":{const m=f;m.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 m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=f,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=v.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,h),i.ref=m;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 m=t._zod.innerType;this.process(m,h),i.ref=m;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"&&bt(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 v=n.external.registry.get(u[0])?.id,y=n.external.uri??(_=>_);if(v)return{ref:y(v)};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}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},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 m=h.schema;for(const v in m)delete m[v];m.$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 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 v=p.ref;if(p.ref=null,v){i(v,h);const y=this.seen.get(v).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 Hh(e,t){if(e instanceof Ah){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 bt(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 bt(o.element,r);case"object":{for(const s in o.shape)if(bt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(bt(s,r))return!0;return!1}case"intersection":return bt(o.left,r)||bt(o.right,r);case"tuple":{for(const s of o.items)if(bt(s,r))return!0;return!!(o.rest&&bt(o.rest,r))}case"record":return bt(o.keyType,r)||bt(o.valueType,r);case"map":return bt(o.keyType,r)||bt(o.valueType,r);case"set":return bt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return bt(o.innerType,r);case"lazy":return bt(o.getter(),r);case"default":return bt(o.innerType,r);case"prefault":return bt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return bt(o.in,r)||bt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const W4=J("ZodISODateTime",(e,t)=>{w9.init(e,t),it.init(e,t)});function Bh(e){return C4(W4,e)}const K4=J("ZodISODate",(e,t)=>{b9.init(e,t),it.init(e,t)});function Y4(e){return S4(K4,e)}const Q4=J("ZodISOTime",(e,t)=>{k9.init(e,t),it.init(e,t)});function X4(e){return I4(Q4,e)}const ek=J("ZodISODuration",(e,t)=>{T9.init(e,t),it.init(e,t)});function tk(e){return E4(ek,e)}const Si=J("ZodError",(e,t)=>{uh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>v3(e,r)},flatten:{value:r=>y3(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}),rk=dh(Si),nk=ph(Si),ok=fh(Si),Jh=hh(Si),tt=J("ZodType",(e,t)=>(Ke.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>_n(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>rk(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>ok(e,r,n),e.parseAsync=async(r,n)=>nk(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(Gk(r,n)),e.superRefine=r=>e.check(Wk(r)),e.overwrite=r=>e.check(_s(r)),e.optional=()=>pe(e),e.nullable=()=>om(e),e.nullish=()=>pe(om(e)),e.nonoptional=r=>Uk(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>fc(e,r),e.transform=r=>mc(e,rm(r)),e.default=r=>Lk(e,r),e.prefault=r=>Dk(e,r),e.catch=r=>Zk(e,r),e.pipe=r=>mc(e,r),e.readonly=()=>Hk(e),e.describe=r=>{const n=e.clone();return vs.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return vs.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return vs.get(e);const n=e.clone();return vs.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Gh=J("_ZodString",(e,t)=>{lc.init(e,t),tt.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(q4(...n)),e.includes=(...n)=>e.check(D4(...n)),e.startsWith=(...n)=>e.check(U4(...n)),e.endsWith=(...n)=>e.check(z4(...n)),e.min=(...n)=>e.check(Ci(...n)),e.max=(...n)=>e.check(Zh(...n)),e.length=(...n)=>e.check(Fh(...n)),e.nonempty=(...n)=>e.check(Ci(1,...n)),e.lowercase=n=>e.check(L4(n)),e.uppercase=n=>e.check(j4(n)),e.trim=()=>e.check(F4()),e.normalize=(...n)=>e.check(Z4(...n)),e.toLowerCase=()=>e.check(V4()),e.toUpperCase=()=>e.check(H4())}),sk=J("ZodString",(e,t)=>{lc.init(e,t),Gh.init(e,t),e.email=r=>e.check(s4(ak,r)),e.url=r=>e.check(Lh(Kh,r)),e.jwt=r=>e.check(T4(bk,r)),e.emoji=r=>e.check(u4(lk,r)),e.guid=r=>e.check(qh(Wh,r)),e.uuid=r=>e.check(a4(Ii,r)),e.uuidv4=r=>e.check(i4(Ii,r)),e.uuidv6=r=>e.check(l4(Ii,r)),e.uuidv7=r=>e.check(c4(Ii,r)),e.nanoid=r=>e.check(d4(ck,r)),e.guid=r=>e.check(qh(Wh,r)),e.cuid=r=>e.check(p4(uk,r)),e.cuid2=r=>e.check(f4(dk,r)),e.ulid=r=>e.check(h4(pk,r)),e.base64=r=>e.check(jh(Yh,r)),e.base64url=r=>e.check(b4(_k,r)),e.xid=r=>e.check(m4(fk,r)),e.ksuid=r=>e.check(g4(hk,r)),e.ipv4=r=>e.check(y4(mk,r)),e.ipv6=r=>e.check(v4(gk,r)),e.cidrv4=r=>e.check(_4(yk,r)),e.cidrv6=r=>e.check(w4(vk,r)),e.e164=r=>e.check(k4(wk,r)),e.datetime=r=>e.check(Bh(r)),e.date=r=>e.check(Y4(r)),e.time=r=>e.check(X4(r)),e.duration=r=>e.check(tk(r))});function d(e){return o4(sk,e)}const it=J("ZodStringFormat",(e,t)=>{rt.init(e,t),Gh.init(e,t)}),ak=J("ZodEmail",(e,t)=>{d9.init(e,t),it.init(e,t)}),Wh=J("ZodGUID",(e,t)=>{c9.init(e,t),it.init(e,t)}),Ii=J("ZodUUID",(e,t)=>{u9.init(e,t),it.init(e,t)}),Kh=J("ZodURL",(e,t)=>{p9.init(e,t),it.init(e,t)});function ik(e){return Lh(Kh,e)}const lk=J("ZodEmoji",(e,t)=>{f9.init(e,t),it.init(e,t)}),ck=J("ZodNanoID",(e,t)=>{h9.init(e,t),it.init(e,t)}),uk=J("ZodCUID",(e,t)=>{m9.init(e,t),it.init(e,t)}),dk=J("ZodCUID2",(e,t)=>{g9.init(e,t),it.init(e,t)}),pk=J("ZodULID",(e,t)=>{y9.init(e,t),it.init(e,t)}),fk=J("ZodXID",(e,t)=>{v9.init(e,t),it.init(e,t)}),hk=J("ZodKSUID",(e,t)=>{_9.init(e,t),it.init(e,t)}),mk=J("ZodIPv4",(e,t)=>{C9.init(e,t),it.init(e,t)}),gk=J("ZodIPv6",(e,t)=>{S9.init(e,t),it.init(e,t)}),yk=J("ZodCIDRv4",(e,t)=>{I9.init(e,t),it.init(e,t)}),vk=J("ZodCIDRv6",(e,t)=>{E9.init(e,t),it.init(e,t)}),Yh=J("ZodBase64",(e,t)=>{x9.init(e,t),it.init(e,t)});function Qh(e){return jh(Yh,e)}const _k=J("ZodBase64URL",(e,t)=>{R9.init(e,t),it.init(e,t)}),wk=J("ZodE164",(e,t)=>{P9.init(e,t),it.init(e,t)}),bk=J("ZodJWT",(e,t)=>{O9.init(e,t),it.init(e,t)}),pc=J("ZodNumber",(e,t)=>{Th.init(e,t),tt.init(e,t),e.gt=(n,o)=>e.check(Uh(n,o)),e.gte=(n,o)=>e.check(dc(n,o)),e.min=(n,o)=>e.check(dc(n,o)),e.lt=(n,o)=>e.check(Dh(n,o)),e.lte=(n,o)=>e.check(uc(n,o)),e.max=(n,o)=>e.check(uc(n,o)),e.int=n=>e.check(Xh(n)),e.safe=n=>e.check(Xh(n)),e.positive=n=>e.check(Uh(0,n)),e.nonnegative=n=>e.check(dc(0,n)),e.negative=n=>e.check(Dh(0,n)),e.nonpositive=n=>e.check(uc(0,n)),e.multipleOf=(n,o)=>e.check(zh(n,o)),e.step=(n,o)=>e.check(zh(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 D(e){return x4(pc,e)}const kk=J("ZodNumberFormat",(e,t)=>{N9.init(e,t),pc.init(e,t)});function Xh(e){return R4(kk,e)}const Tk=J("ZodBoolean",(e,t)=>{A9.init(e,t),tt.init(e,t)});function ge(e){return P4(Tk,e)}const Ck=J("ZodNull",(e,t)=>{q9.init(e,t),tt.init(e,t)});function Ei(e){return M4(Ck,e)}const Sk=J("ZodAny",(e,t)=>{L9.init(e,t),tt.init(e,t)});function Tt(){return O4(Sk)}const Ik=J("ZodUnknown",(e,t)=>{j9.init(e,t),tt.init(e,t)});function Me(){return N4(Ik)}const Ek=J("ZodNever",(e,t)=>{D9.init(e,t),tt.init(e,t)});function xk(e){return A4(Ek,e)}const $k=J("ZodArray",(e,t)=>{U9.init(e,t),tt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ci(r,n)),e.nonempty=r=>e.check(Ci(1,r)),e.max=(r,n)=>e.check(Zh(r,n)),e.length=(r,n)=>e.check(Fh(r,n)),e.unwrap=()=>e.element});function q(e,t){return B4($k,e,t)}const em=J("ZodObject",(e,t)=>{Ih.init(e,t),tt.init(e,t),Fe(e,"shape",()=>t.shape),e.keyof=()=>ye(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:xk()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>f3(e,r),e.merge=r=>h3(e,r),e.pick=r=>d3(e,r),e.omit=r=>p3(e,r),e.partial=(...r)=>m3(nm,e,r[0]),e.required=(...r)=>g3(sm,e,r[0])});function T(e,t){const r={type:"object",get shape(){return fs(this,"shape",{...e}),this.shape},...fe(t)};return new em(r)}function lt(e,t){return new em({type:"object",get shape(){return fs(this,"shape",{...e}),this.shape},catchall:Me(),...fe(t)})}const tm=J("ZodUnion",(e,t)=>{xh.init(e,t),tt.init(e,t),e.options=t.options});function ae(e,t){return new tm({type:"union",options:e,...fe(t)})}const Rk=J("ZodDiscriminatedUnion",(e,t)=>{tm.init(e,t),z9.init(e,t)});function Ue(e,t,r){return new Rk({type:"union",options:t,discriminator:e,...fe(r)})}const Pk=J("ZodIntersection",(e,t)=>{Z9.init(e,t),tt.init(e,t)});function fc(e,t){return new Pk({type:"intersection",left:e,right:t})}const Mk=J("ZodRecord",(e,t)=>{F9.init(e,t),tt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,r){return new Mk({type:"record",keyType:e,valueType:t,...fe(r)})}const hc=J("ZodEnum",(e,t)=>{V9.init(e,t),tt.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 hc({...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 hc({...t,checks:[],...fe(o),entries:s})}});function ye(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new hc({type:"enum",entries:r,...fe(t)})}const Ok=J("ZodLiteral",(e,t)=>{H9.init(e,t),tt.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 Ok({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const Nk=J("ZodTransform",(e,t)=>{B9.init(e,t),tt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ys(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(ys(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function rm(e){return new Nk({type:"transform",transform:e})}const nm=J("ZodOptional",(e,t)=>{J9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pe(e){return new nm({type:"optional",innerType:e})}const Ak=J("ZodNullable",(e,t)=>{G9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function om(e){return new Ak({type:"nullable",innerType:e})}const qk=J("ZodDefault",(e,t)=>{W9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Lk(e,t){return new qk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const jk=J("ZodPrefault",(e,t)=>{K9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Dk(e,t){return new jk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const sm=J("ZodNonOptional",(e,t)=>{Y9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Uk(e,t){return new sm({type:"nonoptional",innerType:e,...fe(t)})}const zk=J("ZodCatch",(e,t)=>{Q9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zk(e,t){return new zk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Fk=J("ZodPipe",(e,t)=>{X9.init(e,t),tt.init(e,t),e.in=t.in,e.out=t.out});function mc(e,t){return new Fk({type:"pipe",in:e,out:t})}const Vk=J("ZodReadonly",(e,t)=>{e4.init(e,t),tt.init(e,t)});function Hk(e){return new Vk({type:"readonly",innerType:e})}const Bk=J("ZodLazy",(e,t)=>{t4.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function gc(e){return new Bk({type:"lazy",getter:e})}const yc=J("ZodCustom",(e,t)=>{r4.init(e,t),tt.init(e,t)});function Jk(e){const t=new Jt({check:"custom"});return t._zod.check=e,t}function am(e,t){return J4(yc,e??(()=>!0),t)}function Gk(e,t={}){return G4(yc,e,t)}function Wk(e){const t=Jk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ys(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(ys(o))}},e(r.value,r)));return t}function xi(e,t={error:`Input not instance of ${e.name}`}){const r=new yc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...fe(t)});return r._zod.bag.Class=e,r}function im(e,t){return mc(rm(e),t)}const lm={custom:"custom"};function cm(e){return $4(pc,e)}const ws="2025-11-25",um=[ws,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vn="io.modelcontextprotocol/related-task",$i="2.0",Rt=am(e=>e!==null&&(typeof e=="object"||typeof e=="function")),dm=ae([d(),D().int()]),pm=d();lt({ttl:ae([D(),Ei()]).optional(),pollInterval:D().optional()});const Kk=T({ttl:D().optional()}),Yk=T({taskId:d()}),vc=lt({progressToken:dm.optional(),[Vn]:Yk.optional()}),rr=T({_meta:vc.optional()}),bs=rr.extend({task:Kk.optional()}),Qk=e=>bs.safeParse(e).success,Pt=T({method:d(),params:rr.loose().optional()}),lr=T({_meta:vc.optional()}),cr=T({method:d(),params:lr.loose().optional()}),Mt=lt({_meta:vc.optional()}),Ri=ae([d(),D().int()]),fm=T({jsonrpc:R($i),id:Ri,...Pt.shape}).strict(),_c=e=>fm.safeParse(e).success,hm=T({jsonrpc:R($i),...cr.shape}).strict(),Xk=e=>hm.safeParse(e).success,wc=T({jsonrpc:R($i),id:Ri,result:Mt}).strict(),ks=e=>wc.safeParse(e).success;var de;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(de||(de={}));const bc=T({jsonrpc:R($i),id:Ri.optional(),error:T({code:D().int(),message:d(),data:Me().optional()})}).strict(),eT=e=>bc.safeParse(e).success,en=ae([fm,hm,wc,bc]);ae([wc,bc]);const bn=Mt.strict(),tT=lr.extend({requestId:Ri.optional(),reason:d().optional()}),kc=cr.extend({method:R("notifications/cancelled"),params:tT}),rT=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:ye(["light","dark"]).optional()}),Ts=T({icons:q(rT).optional()}),vo=T({name:d(),title:d().optional()}),mm=vo.extend({...vo.shape,...Ts.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),nT=fc(T({applyDefaults:ge().optional()}),ve(d(),Me())),oT=im(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,fc(T({form:nT.optional(),url:Rt.optional()}),ve(d(),Me()).optional())),sT=lt({list:Rt.optional(),cancel:Rt.optional(),requests:lt({sampling:lt({createMessage:Rt.optional()}).optional(),elicitation:lt({create:Rt.optional()}).optional()}).optional()}),aT=lt({list:Rt.optional(),cancel:Rt.optional(),requests:lt({tools:lt({call:Rt.optional()}).optional()}).optional()}),iT=T({experimental:ve(d(),Rt).optional(),sampling:T({context:Rt.optional(),tools:Rt.optional()}).optional(),elicitation:oT.optional(),roots:T({listChanged:ge().optional()}).optional(),tasks:sT.optional()}),lT=rr.extend({protocolVersion:d(),capabilities:iT,clientInfo:mm}),gm=Pt.extend({method:R("initialize"),params:lT}),cT=T({experimental:ve(d(),Rt).optional(),logging:Rt.optional(),completions:Rt.optional(),prompts:T({listChanged:ge().optional()}).optional(),resources:T({subscribe:ge().optional(),listChanged:ge().optional()}).optional(),tools:T({listChanged:ge().optional()}).optional(),tasks:aT.optional()}),ym=Mt.extend({protocolVersion:d(),capabilities:cT,serverInfo:mm,instructions:d().optional()}),Tc=cr.extend({method:R("notifications/initialized"),params:lr.optional()}),uT=e=>Tc.safeParse(e).success,Cc=Pt.extend({method:R("ping"),params:rr.optional()}),dT=T({progress:D(),total:pe(D()),message:pe(d())}),pT=T({...lr.shape,...dT.shape,progressToken:dm}),Sc=cr.extend({method:R("notifications/progress"),params:pT}),fT=rr.extend({cursor:pm.optional()}),Cs=Pt.extend({params:fT.optional()}),Ss=Mt.extend({nextCursor:pm.optional()}),hT=ye(["working","input_required","completed","failed","cancelled"]),Is=T({taskId:d(),status:hT,ttl:ae([D(),Ei()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:pe(D()),statusMessage:pe(d())}),_o=Mt.extend({task:Is}),mT=lr.merge(Is),Pi=cr.extend({method:R("notifications/tasks/status"),params:mT}),Ic=Pt.extend({method:R("tasks/get"),params:rr.extend({taskId:d()})}),Ec=Mt.merge(Is),xc=Pt.extend({method:R("tasks/result"),params:rr.extend({taskId:d()})});Mt.loose();const $c=Cs.extend({method:R("tasks/list")}),Rc=Ss.extend({tasks:q(Is)}),Pc=Pt.extend({method:R("tasks/cancel"),params:rr.extend({taskId:d()})}),gT=Mt.merge(Is),vm=T({uri:d(),mimeType:pe(d()),_meta:ve(d(),Me()).optional()}),_m=vm.extend({text:d()}),Mc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),wm=vm.extend({blob:Mc}),Es=ye(["user","assistant"]),wo=T({audience:q(Es).optional(),priority:D().min(0).max(1).optional(),lastModified:Bh({offset:!0}).optional()}),bm=T({...vo.shape,...Ts.shape,uri:d(),description:pe(d()),mimeType:pe(d()),annotations:wo.optional(),_meta:pe(lt({}))}),yT=T({...vo.shape,...Ts.shape,uriTemplate:d(),description:pe(d()),mimeType:pe(d()),annotations:wo.optional(),_meta:pe(lt({}))}),Mi=Cs.extend({method:R("resources/list")}),km=Ss.extend({resources:q(bm)}),Oc=Cs.extend({method:R("resources/templates/list")}),Tm=Ss.extend({resourceTemplates:q(yT)}),Nc=rr.extend({uri:d()}),vT=Nc,Ac=Pt.extend({method:R("resources/read"),params:vT}),Cm=Mt.extend({contents:q(ae([_m,wm]))}),qc=cr.extend({method:R("notifications/resources/list_changed"),params:lr.optional()}),_T=Nc,Sm=Pt.extend({method:R("resources/subscribe"),params:_T}),wT=Nc,Im=Pt.extend({method:R("resources/unsubscribe"),params:wT}),bT=lr.extend({uri:d()}),Em=cr.extend({method:R("notifications/resources/updated"),params:bT}),kT=T({name:d(),description:pe(d()),required:pe(ge())}),TT=T({...vo.shape,...Ts.shape,description:pe(d()),arguments:pe(q(kT)),_meta:pe(lt({}))}),Lc=Cs.extend({method:R("prompts/list")}),xm=Ss.extend({prompts:q(TT)}),CT=rr.extend({name:d(),arguments:ve(d(),d()).optional()}),jc=Pt.extend({method:R("prompts/get"),params:CT}),Dc=T({type:R("text"),text:d(),annotations:wo.optional(),_meta:ve(d(),Me()).optional()}),Uc=T({type:R("image"),data:Mc,mimeType:d(),annotations:wo.optional(),_meta:ve(d(),Me()).optional()}),zc=T({type:R("audio"),data:Mc,mimeType:d(),annotations:wo.optional(),_meta:ve(d(),Me()).optional()}),ST=T({type:R("tool_use"),name:d(),id:d(),input:ve(d(),Me()),_meta:ve(d(),Me()).optional()}),IT=T({type:R("resource"),resource:ae([_m,wm]),annotations:wo.optional(),_meta:ve(d(),Me()).optional()}),ET=bm.extend({type:R("resource_link")}),Zc=ae([Dc,Uc,zc,ET,IT]),xT=T({role:Es,content:Zc}),$m=Mt.extend({description:d().optional(),messages:q(xT)}),Fc=cr.extend({method:R("notifications/prompts/list_changed"),params:lr.optional()}),$T=T({title:d().optional(),readOnlyHint:ge().optional(),destructiveHint:ge().optional(),idempotentHint:ge().optional(),openWorldHint:ge().optional()}),RT=T({taskSupport:ye(["required","optional","forbidden"]).optional()}),Rm=T({...vo.shape,...Ts.shape,description:d().optional(),inputSchema:T({type:R("object"),properties:ve(d(),Rt).optional(),required:q(d()).optional()}).catchall(Me()),outputSchema:T({type:R("object"),properties:ve(d(),Rt).optional(),required:q(d()).optional()}).catchall(Me()).optional(),annotations:$T.optional(),execution:RT.optional(),_meta:ve(d(),Me()).optional()}),Vc=Cs.extend({method:R("tools/list")}),Pm=Ss.extend({tools:q(Rm)}),bo=Mt.extend({content:q(Zc).default([]),structuredContent:ve(d(),Me()).optional(),isError:ge().optional()});bo.or(Mt.extend({toolResult:Me()}));const PT=bs.extend({name:d(),arguments:ve(d(),Me()).optional()}),Oi=Pt.extend({method:R("tools/call"),params:PT}),Hc=cr.extend({method:R("notifications/tools/list_changed"),params:lr.optional()}),MT=T({autoRefresh:ge().default(!0),debounceMs:D().int().nonnegative().default(300)}),Ni=ye(["debug","info","notice","warning","error","critical","alert","emergency"]),OT=rr.extend({level:Ni}),Ai=Pt.extend({method:R("logging/setLevel"),params:OT}),NT=lr.extend({level:Ni,logger:d().optional(),data:Me()}),Mm=cr.extend({method:R("notifications/message"),params:NT}),AT=T({name:d().optional()}),qT=T({hints:q(AT).optional(),costPriority:D().min(0).max(1).optional(),speedPriority:D().min(0).max(1).optional(),intelligencePriority:D().min(0).max(1).optional()}),LT=T({mode:ye(["auto","required","none"]).optional()}),jT=T({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Zc).default([]),structuredContent:T({}).loose().optional(),isError:ge().optional(),_meta:ve(d(),Me()).optional()}),DT=Ue("type",[Dc,Uc,zc]),qi=Ue("type",[Dc,Uc,zc,ST,jT]),UT=T({role:Es,content:ae([qi,q(qi)]),_meta:ve(d(),Me()).optional()}),zT=bs.extend({messages:q(UT),modelPreferences:qT.optional(),systemPrompt:d().optional(),includeContext:ye(["none","thisServer","allServers"]).optional(),temperature:D().optional(),maxTokens:D().int(),stopSequences:q(d()).optional(),metadata:Rt.optional(),tools:q(Rm).optional(),toolChoice:LT.optional()}),Bc=Pt.extend({method:R("sampling/createMessage"),params:zT}),Li=Mt.extend({model:d(),stopReason:pe(ye(["endTurn","stopSequence","maxTokens"]).or(d())),role:Es,content:DT}),Jc=Mt.extend({model:d(),stopReason:pe(ye(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Es,content:ae([qi,q(qi)])}),ZT=T({type:R("boolean"),title:d().optional(),description:d().optional(),default:ge().optional()}),FT=T({type:R("string"),title:d().optional(),description:d().optional(),minLength:D().optional(),maxLength:D().optional(),format:ye(["email","uri","date","date-time"]).optional(),default:d().optional()}),VT=T({type:ye(["number","integer"]),title:d().optional(),description:d().optional(),minimum:D().optional(),maximum:D().optional(),default:D().optional()}),HT=T({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),BT=T({type:R("string"),title:d().optional(),description:d().optional(),oneOf:q(T({const:d(),title:d()})),default:d().optional()}),JT=T({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),GT=ae([HT,BT]),WT=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:D().optional(),maxItems:D().optional(),items:T({type:R("string"),enum:q(d())}),default:q(d()).optional()}),KT=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:D().optional(),maxItems:D().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),YT=ae([WT,KT]),QT=ae([JT,GT,YT]),XT=ae([QT,ZT,FT,VT]),eC=bs.extend({mode:R("form").optional(),message:d(),requestedSchema:T({type:R("object"),properties:ve(d(),XT),required:q(d()).optional()})}),tC=bs.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),rC=ae([eC,tC]),Gc=Pt.extend({method:R("elicitation/create"),params:rC}),nC=lr.extend({elicitationId:d()}),oC=cr.extend({method:R("notifications/elicitation/complete"),params:nC}),xs=Mt.extend({action:ye(["accept","decline","cancel"]),content:im(e=>e===null?void 0:e,ve(d(),ae([d(),D(),ge(),q(d())])).optional())}),sC=T({type:R("ref/resource"),uri:d()}),aC=T({type:R("ref/prompt"),name:d()}),iC=rr.extend({ref:ae([aC,sC]),argument:T({name:d(),value:d()}),context:T({arguments:ve(d(),d()).optional()}).optional()}),Wc=Pt.extend({method:R("completion/complete"),params:iC});function lC(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function cC(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Om=Mt.extend({completion:lt({values:q(d()).max(100),total:pe(D().int()),hasMore:pe(ge())})}),uC=T({uri:d().startsWith("file://"),name:d().optional(),_meta:ve(d(),Me()).optional()}),Nm=Pt.extend({method:R("roots/list"),params:rr.optional()}),Kc=Mt.extend({roots:q(uC)}),Am=cr.extend({method:R("notifications/roots/list_changed"),params:lr.optional()});ae([Cc,gm,Wc,Ai,jc,Lc,Mi,Oc,Ac,Sm,Im,Oi,Vc,Ic,xc,$c,Pc]),ae([kc,Sc,Tc,Am,Pi]),ae([bn,Li,Jc,xs,Kc,Ec,Rc,_o]),ae([Cc,Bc,Gc,Nm,Ic,xc,$c,Pc]),ae([kc,Sc,Mm,Em,qc,Hc,Fc,Pi,oC]),ae([bn,ym,Om,$m,xm,km,Tm,Cm,bo,Pm,Ec,Rc,_o]);class le extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===de.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new dC(o.elicitations,r)}return new le(t,r,n)}}class dC extends le{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(de.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const pC=J("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ke.init(e,t),e.def=t,e.parse=(r,n)=>_3(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>ac(e,r,n),e.parseAsync=async(r,n)=>w3(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ic(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)=>_n(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),fC=J("ZodMiniObject",(e,t)=>{Ih.init(e,t),pC.init(e,t),Fe(e,"shape",()=>t.shape)});function qm(e,t){const r={type:"object",get shape(){return fs(this,"shape",{...e}),this.shape},...fe(t)};return new fC(r)}function wr(e){return!!e._zod}function ko(e){const t=Object.values(e);if(t.length===0)return qm({});const r=t.every(wr),n=t.every(o=>!wr(o));if(r)return qm(e);if(n)return Bt(e);throw new Error("Mixed Zod versions detected in object shape.")}function br(e,t){return wr(e)?ac(e,t):e.safeParse(t)}async function Yc(e,t){return wr(e)?await ic(e,t):await e.safeParseAsync(t)}function To(e){if(!e)return;let t;if(wr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $s(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 ko(e)}}if(wr(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 Qc(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 hC(e){return e.description}function mC(e){if(wr(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Lm(e){if(wr(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 Hn(e){return e==="completed"||e==="failed"||e==="cancelled"}const gC=Symbol("Let zodToJsonSchema decide on which parser to use"),jm={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"},yC=e=>typeof e=="string"?{...jm,name:e}:{...jm,...e},vC=e=>{const t=yC(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 Dm(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Je(e,t,r,n,o){e[t]=r,Dm(e,t,n,o)}const Um=(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 Gt(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Um(t,e.currentPath):t.join("/")}}function _C(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(r.items=Ve(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 wC(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 bC(){return{type:"boolean"}}function zm(e,t){return Ve(e.type._def,t)}const kC=(e,t)=>Ve(e.innerType._def,t);function Zm(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Zm(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return TC(e,t)}}const TC=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Je(r,"minimum",n.value,n.message,t);break;case"max":Je(r,"maximum",n.value,n.message,t);break}return r};function CC(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function SC(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Gt(t)}function IC(e){return{type:"string",enum:Array.from(e.values)}}const EC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function xC(e,t){const r=[Ve(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ve(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(EC(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 $C(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 Xc;const kr={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:()=>(Xc===void 0&&(Xc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Xc),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 Fm(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":Tr(r,"email",n.message,t);break;case"format:idn-email":Tr(r,"idn-email",n.message,t);break;case"pattern:zod":zt(r,kr.email,n.message,t);break}break;case"url":Tr(r,"uri",n.message,t);break;case"uuid":Tr(r,"uuid",n.message,t);break;case"regex":zt(r,n.regex,n.message,t);break;case"cuid":zt(r,kr.cuid,n.message,t);break;case"cuid2":zt(r,kr.cuid2,n.message,t);break;case"startsWith":zt(r,RegExp(`^${eu(n.value,t)}`),n.message,t);break;case"endsWith":zt(r,RegExp(`${eu(n.value,t)}$`),n.message,t);break;case"datetime":Tr(r,"date-time",n.message,t);break;case"date":Tr(r,"date",n.message,t);break;case"time":Tr(r,"time",n.message,t);break;case"duration":Tr(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":{zt(r,RegExp(eu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Tr(r,"ipv4",n.message,t),n.version!=="v4"&&Tr(r,"ipv6",n.message,t);break}case"base64url":zt(r,kr.base64url,n.message,t);break;case"jwt":zt(r,kr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&zt(r,kr.ipv4Cidr,n.message,t),n.version!=="v4"&&zt(r,kr.ipv6Cidr,n.message,t);break}case"emoji":zt(r,kr.emoji(),n.message,t);break;case"ulid":{zt(r,kr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Tr(r,"binary",n.message,t);break}case"contentEncoding:base64":{Je(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{zt(r,kr.base64,n.message,t);break}}break}case"nanoid":zt(r,kr.nanoid,n.message,t)}return r}function eu(e,t){return t.patternStrategy==="escape"?PC(e):e}const RC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PC(e){let t="";for(let r=0;r<e.length;r++)RC.has(e[r])||(t+="\\"),t+=e[r];return t}function Tr(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 zt(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}}})):Je(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,m={...f};if(p.ref===null)return;const v=p.ref;if(p.ref=null,v){i(v,h);const y=this.seen.get(v).schema;y.$ref&&h.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,m))}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 Yh(e,t){if(e instanceof zh){const n=new Kh(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 Kh(t);return r.process(e),r.emit(e,t)}function bt(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 bt(o.element,r);case"object":{for(const s in o.shape)if(bt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(bt(s,r))return!0;return!1}case"intersection":return bt(o.left,r)||bt(o.right,r);case"tuple":{for(const s of o.items)if(bt(s,r))return!0;return!!(o.rest&&bt(o.rest,r))}case"record":return bt(o.keyType,r)||bt(o.valueType,r);case"map":return bt(o.keyType,r)||bt(o.valueType,r);case"set":return bt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return bt(o.innerType,r);case"lazy":return bt(o.getter(),r);case"default":return bt(o.innerType,r);case"prefault":return bt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return bt(o.in,r)||bt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const t4=J("ZodISODateTime",(e,t)=>{I9.init(e,t),it.init(e,t)});function Qh(e){return Rk(t4,e)}const r4=J("ZodISODate",(e,t)=>{x9.init(e,t),it.init(e,t)});function n4(e){return Pk(r4,e)}const o4=J("ZodISOTime",(e,t)=>{E9.init(e,t),it.init(e,t)});function s4(e){return Mk(o4,e)}const a4=J("ZodISODuration",(e,t)=>{$9.init(e,t),it.init(e,t)});function i4(e){return Ok(a4,e)}const Ei=J("ZodError",(e,t)=>{gh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>C3(e,r)},flatten:{value:r=>T3(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}),l4=yh(Ei),c4=vh(Ei),u4=_h(Ei),Xh=wh(Ei),tt=J("ZodType",(e,t)=>(Ke.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>wn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>l4(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>u4(e,r,n),e.parseAsync=async(r,n)=>c4(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Xh(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(eT(r,n)),e.superRefine=r=>e.check(tT(r)),e.overwrite=r=>e.check(bs(r)),e.optional=()=>pe(e),e.nullable=()=>um(e),e.nullish=()=>pe(um(e)),e.nonoptional=r=>B4(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>wc(e,r),e.transform=r=>kc(e,lm(r)),e.default=r=>F4(e,r),e.prefault=r=>H4(e,r),e.catch=r=>G4(e,r),e.pipe=r=>kc(e,r),e.readonly=()=>Y4(e),e.describe=r=>{const n=e.clone();return ws.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ws.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ws.get(e);const n=e.clone();return ws.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),em=J("_ZodString",(e,t)=>{mc.init(e,t),tt.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(Zk(...n)),e.includes=(...n)=>e.check(Hk(...n)),e.startsWith=(...n)=>e.check(Bk(...n)),e.endsWith=(...n)=>e.check(Jk(...n)),e.min=(...n)=>e.check(xi(...n)),e.max=(...n)=>e.check(Gh(...n)),e.length=(...n)=>e.check(Wh(...n)),e.nonempty=(...n)=>e.check(xi(1,...n)),e.lowercase=n=>e.check(Fk(n)),e.uppercase=n=>e.check(Vk(n)),e.trim=()=>e.check(Wk()),e.normalize=(...n)=>e.check(Gk(...n)),e.toLowerCase=()=>e.check(Kk()),e.toUpperCase=()=>e.check(Yk())}),d4=J("ZodString",(e,t)=>{mc.init(e,t),em.init(e,t),e.email=r=>e.check(dk(p4,r)),e.url=r=>e.check(Fh(rm,r)),e.jwt=r=>e.check($k(x4,r)),e.emoji=r=>e.check(gk(h4,r)),e.guid=r=>e.check(Zh(tm,r)),e.uuid=r=>e.check(pk($i,r)),e.uuidv4=r=>e.check(fk($i,r)),e.uuidv6=r=>e.check(hk($i,r)),e.uuidv7=r=>e.check(mk($i,r)),e.nanoid=r=>e.check(yk(m4,r)),e.guid=r=>e.check(Zh(tm,r)),e.cuid=r=>e.check(vk(g4,r)),e.cuid2=r=>e.check(_k(y4,r)),e.ulid=r=>e.check(wk(v4,r)),e.base64=r=>e.check(Vh(nm,r)),e.base64url=r=>e.check(xk(S4,r)),e.xid=r=>e.check(bk(_4,r)),e.ksuid=r=>e.check(kk(w4,r)),e.ipv4=r=>e.check(Tk(b4,r)),e.ipv6=r=>e.check(Ck(k4,r)),e.cidrv4=r=>e.check(Sk(T4,r)),e.cidrv6=r=>e.check(Ik(C4,r)),e.e164=r=>e.check(Ek(I4,r)),e.datetime=r=>e.check(Qh(r)),e.date=r=>e.check(n4(r)),e.time=r=>e.check(s4(r)),e.duration=r=>e.check(i4(r))});function d(e){return uk(d4,e)}const it=J("ZodStringFormat",(e,t)=>{rt.init(e,t),em.init(e,t)}),p4=J("ZodEmail",(e,t)=>{y9.init(e,t),it.init(e,t)}),tm=J("ZodGUID",(e,t)=>{m9.init(e,t),it.init(e,t)}),$i=J("ZodUUID",(e,t)=>{g9.init(e,t),it.init(e,t)}),rm=J("ZodURL",(e,t)=>{v9.init(e,t),it.init(e,t)});function f4(e){return Fh(rm,e)}const h4=J("ZodEmoji",(e,t)=>{_9.init(e,t),it.init(e,t)}),m4=J("ZodNanoID",(e,t)=>{w9.init(e,t),it.init(e,t)}),g4=J("ZodCUID",(e,t)=>{b9.init(e,t),it.init(e,t)}),y4=J("ZodCUID2",(e,t)=>{k9.init(e,t),it.init(e,t)}),v4=J("ZodULID",(e,t)=>{T9.init(e,t),it.init(e,t)}),_4=J("ZodXID",(e,t)=>{C9.init(e,t),it.init(e,t)}),w4=J("ZodKSUID",(e,t)=>{S9.init(e,t),it.init(e,t)}),b4=J("ZodIPv4",(e,t)=>{R9.init(e,t),it.init(e,t)}),k4=J("ZodIPv6",(e,t)=>{P9.init(e,t),it.init(e,t)}),T4=J("ZodCIDRv4",(e,t)=>{M9.init(e,t),it.init(e,t)}),C4=J("ZodCIDRv6",(e,t)=>{O9.init(e,t),it.init(e,t)}),nm=J("ZodBase64",(e,t)=>{N9.init(e,t),it.init(e,t)});function om(e){return Vh(nm,e)}const S4=J("ZodBase64URL",(e,t)=>{q9.init(e,t),it.init(e,t)}),I4=J("ZodE164",(e,t)=>{L9.init(e,t),it.init(e,t)}),x4=J("ZodJWT",(e,t)=>{D9.init(e,t),it.init(e,t)}),_c=J("ZodNumber",(e,t)=>{$h.init(e,t),tt.init(e,t),e.gt=(n,o)=>e.check(Bh(n,o)),e.gte=(n,o)=>e.check(vc(n,o)),e.min=(n,o)=>e.check(vc(n,o)),e.lt=(n,o)=>e.check(Hh(n,o)),e.lte=(n,o)=>e.check(yc(n,o)),e.max=(n,o)=>e.check(yc(n,o)),e.int=n=>e.check(sm(n)),e.safe=n=>e.check(sm(n)),e.positive=n=>e.check(Bh(0,n)),e.nonnegative=n=>e.check(vc(0,n)),e.negative=n=>e.check(Hh(0,n)),e.nonpositive=n=>e.check(yc(0,n)),e.multipleOf=(n,o)=>e.check(Jh(n,o)),e.step=(n,o)=>e.check(Jh(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 D(e){return Nk(_c,e)}const E4=J("ZodNumberFormat",(e,t)=>{U9.init(e,t),_c.init(e,t)});function sm(e){return qk(E4,e)}const $4=J("ZodBoolean",(e,t)=>{z9.init(e,t),tt.init(e,t)});function ge(e){return Lk($4,e)}const R4=J("ZodNull",(e,t)=>{Z9.init(e,t),tt.init(e,t)});function Ri(e){return jk(R4,e)}const P4=J("ZodAny",(e,t)=>{F9.init(e,t),tt.init(e,t)});function Tt(){return Dk(P4)}const M4=J("ZodUnknown",(e,t)=>{V9.init(e,t),tt.init(e,t)});function Me(){return Uk(M4)}const O4=J("ZodNever",(e,t)=>{H9.init(e,t),tt.init(e,t)});function N4(e){return zk(O4,e)}const A4=J("ZodArray",(e,t)=>{B9.init(e,t),tt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(xi(r,n)),e.nonempty=r=>e.check(xi(1,r)),e.max=(r,n)=>e.check(Gh(r,n)),e.length=(r,n)=>e.check(Wh(r,n)),e.unwrap=()=>e.element});function q(e,t){return Qk(A4,e,t)}const am=J("ZodObject",(e,t)=>{Mh.init(e,t),tt.init(e,t),Fe(e,"shape",()=>t.shape),e.keyof=()=>ye(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:N4()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>_3(e,r),e.merge=r=>w3(e,r),e.pick=r=>y3(e,r),e.omit=r=>v3(e,r),e.partial=(...r)=>b3(cm,e,r[0]),e.required=(...r)=>k3(dm,e,r[0])});function T(e,t){const r={type:"object",get shape(){return ms(this,"shape",{...e}),this.shape},...fe(t)};return new am(r)}function lt(e,t){return new am({type:"object",get shape(){return ms(this,"shape",{...e}),this.shape},catchall:Me(),...fe(t)})}const im=J("ZodUnion",(e,t)=>{Nh.init(e,t),tt.init(e,t),e.options=t.options});function ae(e,t){return new im({type:"union",options:e,...fe(t)})}const q4=J("ZodDiscriminatedUnion",(e,t)=>{im.init(e,t),J9.init(e,t)});function ze(e,t,r){return new q4({type:"union",options:t,discriminator:e,...fe(r)})}const L4=J("ZodIntersection",(e,t)=>{G9.init(e,t),tt.init(e,t)});function wc(e,t){return new L4({type:"intersection",left:e,right:t})}const j4=J("ZodRecord",(e,t)=>{W9.init(e,t),tt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,r){return new j4({type:"record",keyType:e,valueType:t,...fe(r)})}const bc=J("ZodEnum",(e,t)=>{K9.init(e,t),tt.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 bc({...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 bc({...t,checks:[],...fe(o),entries:s})}});function ye(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new bc({type:"enum",entries:r,...fe(t)})}const D4=J("ZodLiteral",(e,t)=>{Y9.init(e,t),tt.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 D4({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const U4=J("ZodTransform",(e,t)=>{Q9.init(e,t),tt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(_s(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(_s(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function lm(e){return new U4({type:"transform",transform:e})}const cm=J("ZodOptional",(e,t)=>{X9.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pe(e){return new cm({type:"optional",innerType:e})}const z4=J("ZodNullable",(e,t)=>{ek.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function um(e){return new z4({type:"nullable",innerType:e})}const Z4=J("ZodDefault",(e,t)=>{tk.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F4(e,t){return new Z4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const V4=J("ZodPrefault",(e,t)=>{rk.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function H4(e,t){return new V4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const dm=J("ZodNonOptional",(e,t)=>{nk.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function B4(e,t){return new dm({type:"nonoptional",innerType:e,...fe(t)})}const J4=J("ZodCatch",(e,t)=>{ok.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function G4(e,t){return new J4({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const W4=J("ZodPipe",(e,t)=>{sk.init(e,t),tt.init(e,t),e.in=t.in,e.out=t.out});function kc(e,t){return new W4({type:"pipe",in:e,out:t})}const K4=J("ZodReadonly",(e,t)=>{ak.init(e,t),tt.init(e,t)});function Y4(e){return new K4({type:"readonly",innerType:e})}const Q4=J("ZodLazy",(e,t)=>{ik.init(e,t),tt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Tc(e){return new Q4({type:"lazy",getter:e})}const Cc=J("ZodCustom",(e,t)=>{lk.init(e,t),tt.init(e,t)});function X4(e){const t=new Jt({check:"custom"});return t._zod.check=e,t}function pm(e,t){return Xk(Cc,e??(()=>!0),t)}function eT(e,t={}){return e4(Cc,e,t)}function tT(e){const t=X4(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(_s(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(_s(o))}},e(r.value,r)));return t}function Pi(e,t={error:`Input not instance of ${e.name}`}){const r=new Cc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...fe(t)});return r._zod.bag.Class=e,r}function fm(e,t){return kc(lm(e),t)}const hm={custom:"custom"};function mm(e){return Ak(_c,e)}const ks="2025-11-25",gm=[ks,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Hn="io.modelcontextprotocol/related-task",Mi="2.0",Rt=pm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ym=ae([d(),D().int()]),vm=d();lt({ttl:ae([D(),Ri()]).optional(),pollInterval:D().optional()});const rT=T({ttl:D().optional()}),nT=T({taskId:d()}),Sc=lt({progressToken:ym.optional(),[Hn]:nT.optional()}),rr=T({_meta:Sc.optional()}),Ts=rr.extend({task:rT.optional()}),oT=e=>Ts.safeParse(e).success,Pt=T({method:d(),params:rr.loose().optional()}),lr=T({_meta:Sc.optional()}),cr=T({method:d(),params:lr.loose().optional()}),Mt=lt({_meta:Sc.optional()}),Oi=ae([d(),D().int()]),_m=T({jsonrpc:R(Mi),id:Oi,...Pt.shape}).strict(),Ic=e=>_m.safeParse(e).success,wm=T({jsonrpc:R(Mi),...cr.shape}).strict(),sT=e=>wm.safeParse(e).success,xc=T({jsonrpc:R(Mi),id:Oi,result:Mt}).strict(),Cs=e=>xc.safeParse(e).success;var de;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(de||(de={}));const Ec=T({jsonrpc:R(Mi),id:Oi.optional(),error:T({code:D().int(),message:d(),data:Me().optional()})}).strict(),aT=e=>Ec.safeParse(e).success,en=ae([_m,wm,xc,Ec]);ae([xc,Ec]);const kn=Mt.strict(),iT=lr.extend({requestId:Oi.optional(),reason:d().optional()}),$c=cr.extend({method:R("notifications/cancelled"),params:iT}),lT=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:ye(["light","dark"]).optional()}),Ss=T({icons:q(lT).optional()}),_o=T({name:d(),title:d().optional()}),bm=_o.extend({..._o.shape,...Ss.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),cT=wc(T({applyDefaults:ge().optional()}),ve(d(),Me())),uT=fm(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,wc(T({form:cT.optional(),url:Rt.optional()}),ve(d(),Me()).optional())),dT=lt({list:Rt.optional(),cancel:Rt.optional(),requests:lt({sampling:lt({createMessage:Rt.optional()}).optional(),elicitation:lt({create:Rt.optional()}).optional()}).optional()}),pT=lt({list:Rt.optional(),cancel:Rt.optional(),requests:lt({tools:lt({call:Rt.optional()}).optional()}).optional()}),fT=T({experimental:ve(d(),Rt).optional(),sampling:T({context:Rt.optional(),tools:Rt.optional()}).optional(),elicitation:uT.optional(),roots:T({listChanged:ge().optional()}).optional(),tasks:dT.optional()}),hT=rr.extend({protocolVersion:d(),capabilities:fT,clientInfo:bm}),km=Pt.extend({method:R("initialize"),params:hT}),mT=T({experimental:ve(d(),Rt).optional(),logging:Rt.optional(),completions:Rt.optional(),prompts:T({listChanged:ge().optional()}).optional(),resources:T({subscribe:ge().optional(),listChanged:ge().optional()}).optional(),tools:T({listChanged:ge().optional()}).optional(),tasks:pT.optional()}),Tm=Mt.extend({protocolVersion:d(),capabilities:mT,serverInfo:bm,instructions:d().optional()}),Rc=cr.extend({method:R("notifications/initialized"),params:lr.optional()}),gT=e=>Rc.safeParse(e).success,Pc=Pt.extend({method:R("ping"),params:rr.optional()}),yT=T({progress:D(),total:pe(D()),message:pe(d())}),vT=T({...lr.shape,...yT.shape,progressToken:ym}),Mc=cr.extend({method:R("notifications/progress"),params:vT}),_T=rr.extend({cursor:vm.optional()}),Is=Pt.extend({params:_T.optional()}),xs=Mt.extend({nextCursor:vm.optional()}),wT=ye(["working","input_required","completed","failed","cancelled"]),Es=T({taskId:d(),status:wT,ttl:ae([D(),Ri()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:pe(D()),statusMessage:pe(d())}),wo=Mt.extend({task:Es}),bT=lr.merge(Es),Ni=cr.extend({method:R("notifications/tasks/status"),params:bT}),Oc=Pt.extend({method:R("tasks/get"),params:rr.extend({taskId:d()})}),Nc=Mt.merge(Es),Ac=Pt.extend({method:R("tasks/result"),params:rr.extend({taskId:d()})});Mt.loose();const qc=Is.extend({method:R("tasks/list")}),Lc=xs.extend({tasks:q(Es)}),jc=Pt.extend({method:R("tasks/cancel"),params:rr.extend({taskId:d()})}),kT=Mt.merge(Es),Cm=T({uri:d(),mimeType:pe(d()),_meta:ve(d(),Me()).optional()}),Sm=Cm.extend({text:d()}),Dc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Im=Cm.extend({blob:Dc}),$s=ye(["user","assistant"]),bo=T({audience:q($s).optional(),priority:D().min(0).max(1).optional(),lastModified:Qh({offset:!0}).optional()}),xm=T({..._o.shape,...Ss.shape,uri:d(),description:pe(d()),mimeType:pe(d()),annotations:bo.optional(),_meta:pe(lt({}))}),TT=T({..._o.shape,...Ss.shape,uriTemplate:d(),description:pe(d()),mimeType:pe(d()),annotations:bo.optional(),_meta:pe(lt({}))}),Ai=Is.extend({method:R("resources/list")}),Em=xs.extend({resources:q(xm)}),Uc=Is.extend({method:R("resources/templates/list")}),$m=xs.extend({resourceTemplates:q(TT)}),zc=rr.extend({uri:d()}),CT=zc,Zc=Pt.extend({method:R("resources/read"),params:CT}),Rm=Mt.extend({contents:q(ae([Sm,Im]))}),Fc=cr.extend({method:R("notifications/resources/list_changed"),params:lr.optional()}),ST=zc,Pm=Pt.extend({method:R("resources/subscribe"),params:ST}),IT=zc,Mm=Pt.extend({method:R("resources/unsubscribe"),params:IT}),xT=lr.extend({uri:d()}),Om=cr.extend({method:R("notifications/resources/updated"),params:xT}),ET=T({name:d(),description:pe(d()),required:pe(ge())}),$T=T({..._o.shape,...Ss.shape,description:pe(d()),arguments:pe(q(ET)),_meta:pe(lt({}))}),Vc=Is.extend({method:R("prompts/list")}),Nm=xs.extend({prompts:q($T)}),RT=rr.extend({name:d(),arguments:ve(d(),d()).optional()}),Hc=Pt.extend({method:R("prompts/get"),params:RT}),Bc=T({type:R("text"),text:d(),annotations:bo.optional(),_meta:ve(d(),Me()).optional()}),Jc=T({type:R("image"),data:Dc,mimeType:d(),annotations:bo.optional(),_meta:ve(d(),Me()).optional()}),Gc=T({type:R("audio"),data:Dc,mimeType:d(),annotations:bo.optional(),_meta:ve(d(),Me()).optional()}),PT=T({type:R("tool_use"),name:d(),id:d(),input:ve(d(),Me()),_meta:ve(d(),Me()).optional()}),MT=T({type:R("resource"),resource:ae([Sm,Im]),annotations:bo.optional(),_meta:ve(d(),Me()).optional()}),OT=xm.extend({type:R("resource_link")}),Wc=ae([Bc,Jc,Gc,OT,MT]),NT=T({role:$s,content:Wc}),Am=Mt.extend({description:d().optional(),messages:q(NT)}),Kc=cr.extend({method:R("notifications/prompts/list_changed"),params:lr.optional()}),AT=T({title:d().optional(),readOnlyHint:ge().optional(),destructiveHint:ge().optional(),idempotentHint:ge().optional(),openWorldHint:ge().optional()}),qT=T({taskSupport:ye(["required","optional","forbidden"]).optional()}),qm=T({..._o.shape,...Ss.shape,description:d().optional(),inputSchema:T({type:R("object"),properties:ve(d(),Rt).optional(),required:q(d()).optional()}).catchall(Me()),outputSchema:T({type:R("object"),properties:ve(d(),Rt).optional(),required:q(d()).optional()}).catchall(Me()).optional(),annotations:AT.optional(),execution:qT.optional(),_meta:ve(d(),Me()).optional()}),Yc=Is.extend({method:R("tools/list")}),Lm=xs.extend({tools:q(qm)}),ko=Mt.extend({content:q(Wc).default([]),structuredContent:ve(d(),Me()).optional(),isError:ge().optional()});ko.or(Mt.extend({toolResult:Me()}));const LT=Ts.extend({name:d(),arguments:ve(d(),Me()).optional()}),qi=Pt.extend({method:R("tools/call"),params:LT}),Qc=cr.extend({method:R("notifications/tools/list_changed"),params:lr.optional()}),jT=T({autoRefresh:ge().default(!0),debounceMs:D().int().nonnegative().default(300)}),Li=ye(["debug","info","notice","warning","error","critical","alert","emergency"]),DT=rr.extend({level:Li}),ji=Pt.extend({method:R("logging/setLevel"),params:DT}),UT=lr.extend({level:Li,logger:d().optional(),data:Me()}),jm=cr.extend({method:R("notifications/message"),params:UT}),zT=T({name:d().optional()}),ZT=T({hints:q(zT).optional(),costPriority:D().min(0).max(1).optional(),speedPriority:D().min(0).max(1).optional(),intelligencePriority:D().min(0).max(1).optional()}),FT=T({mode:ye(["auto","required","none"]).optional()}),VT=T({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Wc).default([]),structuredContent:T({}).loose().optional(),isError:ge().optional(),_meta:ve(d(),Me()).optional()}),HT=ze("type",[Bc,Jc,Gc]),Di=ze("type",[Bc,Jc,Gc,PT,VT]),BT=T({role:$s,content:ae([Di,q(Di)]),_meta:ve(d(),Me()).optional()}),JT=Ts.extend({messages:q(BT),modelPreferences:ZT.optional(),systemPrompt:d().optional(),includeContext:ye(["none","thisServer","allServers"]).optional(),temperature:D().optional(),maxTokens:D().int(),stopSequences:q(d()).optional(),metadata:Rt.optional(),tools:q(qm).optional(),toolChoice:FT.optional()}),Xc=Pt.extend({method:R("sampling/createMessage"),params:JT}),Ui=Mt.extend({model:d(),stopReason:pe(ye(["endTurn","stopSequence","maxTokens"]).or(d())),role:$s,content:HT}),eu=Mt.extend({model:d(),stopReason:pe(ye(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:$s,content:ae([Di,q(Di)])}),GT=T({type:R("boolean"),title:d().optional(),description:d().optional(),default:ge().optional()}),WT=T({type:R("string"),title:d().optional(),description:d().optional(),minLength:D().optional(),maxLength:D().optional(),format:ye(["email","uri","date","date-time"]).optional(),default:d().optional()}),KT=T({type:ye(["number","integer"]),title:d().optional(),description:d().optional(),minimum:D().optional(),maximum:D().optional(),default:D().optional()}),YT=T({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),QT=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()}),eC=ae([YT,QT]),tC=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:D().optional(),maxItems:D().optional(),items:T({type:R("string"),enum:q(d())}),default:q(d()).optional()}),rC=T({type:R("array"),title:d().optional(),description:d().optional(),minItems:D().optional(),maxItems:D().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),nC=ae([tC,rC]),oC=ae([XT,eC,nC]),sC=ae([oC,GT,WT,KT]),aC=Ts.extend({mode:R("form").optional(),message:d(),requestedSchema:T({type:R("object"),properties:ve(d(),sC),required:q(d()).optional()})}),iC=Ts.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),lC=ae([aC,iC]),tu=Pt.extend({method:R("elicitation/create"),params:lC}),cC=lr.extend({elicitationId:d()}),uC=cr.extend({method:R("notifications/elicitation/complete"),params:cC}),Rs=Mt.extend({action:ye(["accept","decline","cancel"]),content:fm(e=>e===null?void 0:e,ve(d(),ae([d(),D(),ge(),q(d())])).optional())}),dC=T({type:R("ref/resource"),uri:d()}),pC=T({type:R("ref/prompt"),name:d()}),fC=rr.extend({ref:ae([pC,dC]),argument:T({name:d(),value:d()}),context:T({arguments:ve(d(),d()).optional()}).optional()}),ru=Pt.extend({method:R("completion/complete"),params:fC});function hC(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function mC(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Dm=Mt.extend({completion:lt({values:q(d()).max(100),total:pe(D().int()),hasMore:pe(ge())})}),gC=T({uri:d().startsWith("file://"),name:d().optional(),_meta:ve(d(),Me()).optional()}),Um=Pt.extend({method:R("roots/list"),params:rr.optional()}),nu=Mt.extend({roots:q(gC)}),zm=cr.extend({method:R("notifications/roots/list_changed"),params:lr.optional()});ae([Pc,km,ru,ji,Hc,Vc,Ai,Uc,Zc,Pm,Mm,qi,Yc,Oc,Ac,qc,jc]),ae([$c,Mc,Rc,zm,Ni]),ae([kn,Ui,eu,Rs,nu,Nc,Lc,wo]),ae([Pc,Xc,tu,Um,Oc,Ac,qc,jc]),ae([$c,Mc,jm,Om,Fc,Qc,Kc,Ni,uC]),ae([kn,Tm,Dm,Am,Nm,Em,$m,Rm,ko,Lm,Nc,Lc,wo]);class le extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===de.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new yC(o.elicitations,r)}return new le(t,r,n)}}class yC extends le{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(de.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const vC=J("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ke.init(e,t),e.def=t,e.parse=(r,n)=>S3(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>fc(e,r,n),e.parseAsync=async(r,n)=>I3(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>hc(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)=>wn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),_C=J("ZodMiniObject",(e,t)=>{Mh.init(e,t),vC.init(e,t),Fe(e,"shape",()=>t.shape)});function Zm(e,t){const r={type:"object",get shape(){return ms(this,"shape",{...e}),this.shape},...fe(t)};return new _C(r)}function wr(e){return!!e._zod}function To(e){const t=Object.values(e);if(t.length===0)return Zm({});const r=t.every(wr),n=t.every(o=>!wr(o));if(r)return Zm(e);if(n)return Bt(e);throw new Error("Mixed Zod versions detected in object shape.")}function br(e,t){return wr(e)?fc(e,t):e.safeParse(t)}async function ou(e,t){return wr(e)?await hc(e,t):await e.safeParseAsync(t)}function Co(e){if(!e)return;let t;if(wr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Ps(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 To(e)}}if(wr(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 su(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 wC(e){return e.description}function bC(e){if(wr(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Fm(e){if(wr(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 Bn(e){return e==="completed"||e==="failed"||e==="cancelled"}const kC=Symbol("Let zodToJsonSchema decide on which parser to use"),Vm={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"},TC=e=>typeof e=="string"?{...Vm,name:e}:{...Vm,...e},CC=e=>{const t=TC(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 Hm(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Je(e,t,r,n,o){e[t]=r,Hm(e,t,n,o)}const Bm=(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 Gt(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Bm(t,e.currentPath):t.join("/")}}function SC(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(r.items=Ve(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 IC(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 xC(){return{type:"boolean"}}function Jm(e,t){return Ve(e.type._def,t)}const EC=(e,t)=>Ve(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 $C(e,t)}}const $C=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Je(r,"minimum",n.value,n.message,t);break;case"max":Je(r,"maximum",n.value,n.message,t);break}return r};function RC(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function PC(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Gt(t)}function MC(e){return{type:"string",enum:Array.from(e.values)}}const OC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function NC(e,t){const r=[Ve(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ve(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(OC(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 AC(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 au;const kr={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:()=>(au===void 0&&(au=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),au),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 Wm(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":Tr(r,"email",n.message,t);break;case"format:idn-email":Tr(r,"idn-email",n.message,t);break;case"pattern:zod":zt(r,kr.email,n.message,t);break}break;case"url":Tr(r,"uri",n.message,t);break;case"uuid":Tr(r,"uuid",n.message,t);break;case"regex":zt(r,n.regex,n.message,t);break;case"cuid":zt(r,kr.cuid,n.message,t);break;case"cuid2":zt(r,kr.cuid2,n.message,t);break;case"startsWith":zt(r,RegExp(`^${iu(n.value,t)}`),n.message,t);break;case"endsWith":zt(r,RegExp(`${iu(n.value,t)}$`),n.message,t);break;case"datetime":Tr(r,"date-time",n.message,t);break;case"date":Tr(r,"date",n.message,t);break;case"time":Tr(r,"time",n.message,t);break;case"duration":Tr(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":{zt(r,RegExp(iu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Tr(r,"ipv4",n.message,t),n.version!=="v4"&&Tr(r,"ipv6",n.message,t);break}case"base64url":zt(r,kr.base64url,n.message,t);break;case"jwt":zt(r,kr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&zt(r,kr.ipv4Cidr,n.message,t),n.version!=="v4"&&zt(r,kr.ipv6Cidr,n.message,t);break}case"emoji":zt(r,kr.emoji(),n.message,t);break;case"ulid":{zt(r,kr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Tr(r,"binary",n.message,t);break}case"contentEncoding:base64":{Je(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{zt(r,kr.base64,n.message,t);break}}break}case"nanoid":zt(r,kr.nanoid,n.message,t)}return r}function iu(e,t){return t.patternStrategy==="escape"?LC(e):e}const qC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function LC(e){let t="";for(let r=0;r<e.length;r++)qC.has(e[r])||(t+="\\"),t+=e[r];return t}function Tr(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 zt(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:Km(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Je(e,"pattern",Km(t,n),r,n)}function Km(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 Hm(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]:Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Gt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ve(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}=Fm(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}=zm(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function MC(e,t){if(t.mapStrategy==="record")return Hm(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(t),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function OC(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 NC(e){return e.target==="openAi"?void 0:{not:Gt({...e,currentPath:[...e.currentPath,"not"]})}}function AC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ji={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qC(e,t){if(t.target==="openApi3")return Bm(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in ji&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=ji[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 Bm(e,t)}const Bm=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ve(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 LC(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:ji[e.innerType._def.typeName],nullable:!0}:{type:[ji[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jC(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",Dm(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 DC(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=zC(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Ve(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=UC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function UC(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ve(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 zC(e){try{return e.isOptional()}catch{return!0}}const ZC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ve(e.innerType._def,t);const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Gt(t)},r]}:Gt(t)},FC=(e,t)=>{if(t.pipeStrategy==="input")return Ve(e.in._def,t);if(t.pipeStrategy==="output")return Ve(e.out._def,t);const r=Ve(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ve(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function VC(e,t){return Ve(e.type._def,t)}function HC(e,t){const n={type:"array",uniqueItems:!0,items:Ve(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 BC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ve(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function JC(e){return{not:Gt(e)}}function GC(e){return Gt(e)}const WC=(e,t)=>Ve(e.innerType._def,t),KC=(e,t,r)=>{switch(t){case B.ZodString:return Fm(e,r);case B.ZodNumber:return jC(e,r);case B.ZodObject:return DC(e,r);case B.ZodBigInt:return wC(e,r);case B.ZodBoolean:return bC();case B.ZodDate:return Zm(e,r);case B.ZodUndefined:return JC(r);case B.ZodNull:return AC(r);case B.ZodArray:return _C(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return qC(e,r);case B.ZodIntersection:return xC(e,r);case B.ZodTuple:return BC(e,r);case B.ZodRecord:return Hm(e,r);case B.ZodLiteral:return $C(e,r);case B.ZodEnum:return IC(e);case B.ZodNativeEnum:return OC(e);case B.ZodNullable:return LC(e,r);case B.ZodOptional:return ZC(e,r);case B.ZodMap:return MC(e,r);case B.ZodSet:return HC(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return VC(e,r);case B.ZodNaN:case B.ZodNever:return NC(r);case B.ZodEffects:return SC(e,r);case B.ZodAny:return Gt(r);case B.ZodUnknown:return GC(r);case B.ZodDefault:return CC(e,r);case B.ZodBranded:return zm(e,r);case B.ZodReadonly:return WC(e,r);case B.ZodCatch:return kC(e,r);case B.ZodPipeline:return FC(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}};function Ve(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==gC)return i}if(n&&!r){const i=YC(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=KC(e,e.typeName,t),a=typeof s=="function"?Ve(s(),t):s;if(a&&QC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const YC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Um(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)):t.$refStrategy==="seen"?Gt(t):void 0}},QC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),XC=(e,t)=>{const r=vC(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:Ve(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Gt(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Ve(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Gt(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 eS(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 wr(e)?Hh(e,{target:eS(t?.target),io:t?.pipeStrategy??"input"}):XC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Gm(e){const r=To(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Lm(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wm(e,t){const r=br(e,t);if(!r.success)throw r.error;return r.data}const tS=6e4;class Km{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(kc,r=>{this._oncancel(r)}),this.setNotificationHandler(Sc,r=>{this._onprogress(r)}),this.setRequestHandler(Cc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ic,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new le(de.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(xc,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 le(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 le(de.InvalidParams,`Task not found: ${s}`);if(!Hn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Hn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[Vn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler($c,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 le(de.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Pc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new le(de.InvalidParams,`Task not found: ${r.params.taskId}`);if(Hn(o.status))throw new le(de.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new le(de.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof le?o:new le(de.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),le.fromError(de.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),ks(s)||eT(s)?this._onresponse(s):_c(s)?this._onrequest(s,a):Xk(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=le.fromError(de.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[Vn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:de.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=Qk(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const h={relatedRequestId:t.id};s&&(h.relatedTask={taskId:s}),await this.notification(u,h)},sendRequest:async(u,h,p)=>{const f={...p,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});const g=f.relatedTask?.taskId??s;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(u,h,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async u=>{if(a.signal.aborted)return;const h={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:de.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ks(t))n(t);else{const a=new le(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(ks(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),ks(t))o(t);else{const a=le.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 le?a:new le(de.InternalError,String(a))}}return}let s;try{const a=await this.request(t,_o,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new le(de.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Hn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new le(de.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new le(de.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof le?a:new le(de.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const h=_=>{u(_)};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(_){h(_);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||{},[Vn]:l}});const g=_=>{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(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));const m=_ instanceof le?_:new le(de.RequestTimeout,String(_));u(m)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const m=br(r,_.result);m.success?c(m.data):u(m.error)}catch(m){u(m)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});const v=n?.timeout??tS,y=()=>g(le.fromError(de.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=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,_),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(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ec,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},Rc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},gT,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||{},[Vn]: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||{},[Vn]: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||{},[Vn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=Gm(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Wm(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=Gm(t);this._notificationHandlers.set(n,o=>{const s=Wm(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"&&_c(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new le(de.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new le(de.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new le(de.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new le(de.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Pi.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Hn(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 le(de.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Hn(i.status))throw new le(de.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Pi.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Hn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function Ym(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qm(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];Ym(a)&&Ym(s)?r[o]={...a,...s}:r[o]=s}return r}var Di={exports:{}},tu={},Xm;function rS(){return Xm||(Xm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,U){return{validate:O,compare:U}}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:j,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:m,int32:{type:"number",validate:k},int64:{type:"number",validate:S},float:{type:"number",validate:I},double:{type:"number",validate:I},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(O){const U=n.exec(O);if(!U)return!1;const A=+U[1],N=+U[2],G=+U[3];return N>=1&&N<=12&&G>=1&&G<=(N===2&&r(A)?29:o[N])}function a(O,U){if(O&&U)return O>U?1:O<U?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(A){const N=i.exec(A);if(!N)return!1;const G=+N[1],X=+N[2],Q=+N[3],K=N[4],he=N[5]==="-"?-1:1,V=+(N[6]||0),P=+(N[7]||0);if(V>23||P>59||O&&!K)return!1;if(G<=23&&X<=59&&Q<60)return!0;const H=X-P*he,Z=G-V*he-(H<0?1:0);return(Z===23||Z===-1)&&(H===59||H===-1)&&Q<61}}function c(O,U){if(!(O&&U))return;const A=new Date("2020-01-01T"+O).valueOf(),N=new Date("2020-01-01T"+U).valueOf();if(A&&N)return A-N}function u(O,U){if(!(O&&U))return;const A=i.exec(O),N=i.exec(U);if(A&&N)return O=A[1]+A[2]+A[3],U=N[1]+N[2]+N[3],O>U?1:O<U?-1:0}const h=/t|\s/i;function p(O){const U=l(O);return function(N){const G=N.split(h);return G.length===2&&s(G[0])&&U(G[1])}}function f(O,U){if(!(O&&U))return;const A=new Date(O).valueOf(),N=new Date(U).valueOf();if(A&&N)return A-N}function g(O,U){if(!(O&&U))return;const[A,N]=O.split(h),[G,X]=U.split(h),Q=a(A,G);if(Q!==void 0)return Q||c(N,X)}const v=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w(O){return v.test(O)&&y.test(O)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(O){return _.lastIndex=0,_.test(O)}const C=-2147483648,b=2**31-1;function k(O){return Number.isInteger(O)&&O<=b&&O>=C}function S(O){return Number.isInteger(O)}function I(){return!0}const E=/[^\\]\\Z/;function j(O){if(E.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(tu)),tu}var ru={},e0;function nS(){return e0||(e0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Hf(),r=Oe(),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 v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?y():w();function y(){const m=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),C=l.const("fmt",(0,r._)`${m}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${C} != "object"`,(0,r._)`${C} instanceof RegExp`,(0,r._)`typeof ${C}.compare != "function"`,_(C)))}function w(){const m=v.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 b=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(_(b))}function _(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})(ru)),ru}var t0;function oS(){return t0||(t0=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=rS(),n=nS(),o=Oe(),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 v of u)c.addFormat(v,h[v])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(Di,Di.exports)),Di.exports}var sS=oS();const aS=Nn(sS);function iS(){const e=new Bf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return aS(e),e}class r0{constructor(t){this._ajv=t??iS()}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 lS{constructor(t){this._client=t}async*callToolStream(t,r=bo,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 le(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new le(de.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof le){yield{type:"error",error:u};return}yield{type:"error",error:new le(de.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function n0(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 o0(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 Ui(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&&Ui(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Ui(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Ui(r,t)}}function cS(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 Rs extends Km{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 r0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Hc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Fc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",qc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new lS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qm(this._capabilities,t)}setRequestHandler(t,r){const o=To(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(wr(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=br(Gc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=cS(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new le(de.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!f)throw new le(de.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(h.task){const _=br(_o,g);if(!_.success){const m=_.error instanceof Error?_.error.message:String(_.error);throw new le(de.InvalidParams,`Invalid task creation result: ${m}`)}return _.data}const v=br(xs,g);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new le(de.InvalidParams,`Invalid elicitation result: ${_}`)}const y=v.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{Ui(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=br(Bc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid sampling request: ${y}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const y=br(_o,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new le(de.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=h.tools||h.toolChoice?Jc:Li,v=br(g,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new le(de.InvalidParams,`Invalid sampling result: ${y}`)}return v.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:ws,capabilities:this._capabilities,clientInfo:this._clientInfo}},ym,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!um.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){n0(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&o0(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},bn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Om,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},bn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},$m,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},xm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},km,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Tm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Cm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},bn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},bn,r)}async callTool(t,r=bo,n){if(this.isToolTaskRequired(t.name))throw new le(de.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new le(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new le(de.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof le?a:new le(de.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},Pm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=MT.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 s0 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 nu(e){}function a0(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=nu,onError:r=nu,onRetry:n=nu,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=uS(`${s}${y}`);for(const m of w)h(m);s=_,a=!1}function h(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const w=v.slice(0,y),_=v[y+1]===" "?2:1,m=v.slice(y+_);p(w,m,v);return}p(v,"",v)}function p(v,y,w){switch(v){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
|
|
41
|
-
`)?l.slice(0,-1):l}),i=void 0,l="",c=""}function
|
|
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 Ym(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]:Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Gt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ve(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}=Wm(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}=Jm(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function jC(e,t){if(t.mapStrategy==="record")return Ym(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(t),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function DC(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function UC(e){return e.target==="openAi"?void 0:{not:Gt({...e,currentPath:[...e.currentPath,"not"]})}}function zC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const zi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ZC(e,t){if(t.target==="openApi3")return Qm(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in zi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=zi[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Qm(e,t)}const Qm=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ve(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 FC(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:zi[e.innerType._def.typeName],nullable:!0}:{type:[zi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Ve(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",Hm(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 HC(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=JC(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Ve(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=BC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function BC(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ve(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 JC(e){try{return e.isOptional()}catch{return!0}}const GC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ve(e.innerType._def,t);const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Gt(t)},r]}:Gt(t)},WC=(e,t)=>{if(t.pipeStrategy==="input")return Ve(e.in._def,t);if(t.pipeStrategy==="output")return Ve(e.out._def,t);const r=Ve(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ve(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function KC(e,t){return Ve(e.type._def,t)}function YC(e,t){const n={type:"array",uniqueItems:!0,items:Ve(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 QC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ve(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function XC(e){return{not:Gt(e)}}function eS(e){return Gt(e)}const tS=(e,t)=>Ve(e.innerType._def,t),rS=(e,t,r)=>{switch(t){case B.ZodString:return Wm(e,r);case B.ZodNumber:return VC(e,r);case B.ZodObject:return HC(e,r);case B.ZodBigInt:return IC(e,r);case B.ZodBoolean:return xC();case B.ZodDate:return Gm(e,r);case B.ZodUndefined:return XC(r);case B.ZodNull:return zC(r);case B.ZodArray:return SC(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return ZC(e,r);case B.ZodIntersection:return NC(e,r);case B.ZodTuple:return QC(e,r);case B.ZodRecord:return Ym(e,r);case B.ZodLiteral:return AC(e,r);case B.ZodEnum:return MC(e);case B.ZodNativeEnum:return DC(e);case B.ZodNullable:return FC(e,r);case B.ZodOptional:return GC(e,r);case B.ZodMap:return jC(e,r);case B.ZodSet:return YC(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return KC(e,r);case B.ZodNaN:case B.ZodNever:return UC(r);case B.ZodEffects:return PC(e,r);case B.ZodAny:return Gt(r);case B.ZodUnknown:return eS(r);case B.ZodDefault:return RC(e,r);case B.ZodBranded:return Jm(e,r);case B.ZodReadonly:return tS(e,r);case B.ZodCatch:return EC(e,r);case B.ZodPipeline:return WC(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}};function Ve(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==kC)return i}if(n&&!r){const i=nS(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=rS(e,e.typeName,t),a=typeof s=="function"?Ve(s(),t):s;if(a&&oS(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const nS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bm(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)):t.$refStrategy==="seen"?Gt(t):void 0}},oS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),sS=(e,t)=>{const r=CC(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:Ve(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Gt(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Ve(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Gt(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 aS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Xm(e,t){return wr(e)?Yh(e,{target:aS(t?.target),io:t?.pipeStrategy??"input"}):sS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function e0(e){const r=Co(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Fm(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function t0(e,t){const r=br(e,t);if(!r.success)throw r.error;return r.data}const iS=6e4;class r0{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($c,r=>{this._oncancel(r)}),this.setNotificationHandler(Mc,r=>{this._onprogress(r)}),this.setRequestHandler(Pc,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 le(de.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 h=l,p=new le(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 le(de.InvalidParams,`Task not found: ${s}`);if(!Bn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Bn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[Hn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(qc,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 le(de.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(jc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new le(de.InvalidParams,`Task not found: ${r.params.taskId}`);if(Bn(o.status))throw new le(de.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new le(de.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof le?o:new le(de.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),le.fromError(de.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),Cs(s)||aT(s)?this._onresponse(s):Ic(s)?this._onrequest(s,a):sT(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=le.fromError(de.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[Hn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:de.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=oT(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 m=f.relatedTask?.taskId??s;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,h,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async u=>{if(a.signal.aborted)return;const h={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:de.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Cs(t))n(t);else{const a=new le(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=le.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 le?a:new le(de.InternalError,String(a))}}return}let s;try{const a=await this.request(t,wo,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new le(de.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Bn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new le(de.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new le(de.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof le?a:new le(de.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const h=_=>{u(_)};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(_){h(_);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||{},[Hn]:l}});const m=_=>{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(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));const g=_ instanceof le?_:new le(de.RequestTimeout,String(_));u(g)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const g=br(r,_.result);g.success?c(g.data):u(g.error)}catch(g){u(g)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});const v=n?.timeout??iS,y=()=>m(le.fromError(de.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=g=>{const C=this._responseHandlers.get(p);C?C(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),u(g)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Nc,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},kT,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||{},[Hn]: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||{},[Hn]: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||{},[Hn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=e0(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=t0(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=e0(t);this._notificationHandlers.set(n,o=>{const s=t0(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"&&Ic(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new le(de.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new le(de.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new le(de.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new le(de.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Ni.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Bn(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 le(de.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Bn(i.status))throw new le(de.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Ni.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Bn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function n0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function o0(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];n0(a)&&n0(s)?r[o]={...a,...s}:r[o]=s}return r}var Zi={exports:{}},lu={},s0;function lS(){return s0||(s0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,U){return{validate:O,compare:U}}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(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:j,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:g,int32:{type:"number",validate:k},int64:{type:"number",validate:S},float:{type:"number",validate:I},double:{type:"number",validate:I},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,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(O){const U=n.exec(O);if(!U)return!1;const A=+U[1],N=+U[2],G=+U[3];return N>=1&&N<=12&&G>=1&&G<=(N===2&&r(A)?29:o[N])}function a(O,U){if(O&&U)return O>U?1:O<U?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(A){const N=i.exec(A);if(!N)return!1;const G=+N[1],X=+N[2],Q=+N[3],K=N[4],he=N[5]==="-"?-1:1,V=+(N[6]||0),P=+(N[7]||0);if(V>23||P>59||O&&!K)return!1;if(G<=23&&X<=59&&Q<60)return!0;const H=X-P*he,Z=G-V*he-(H<0?1:0);return(Z===23||Z===-1)&&(H===59||H===-1)&&Q<61}}function c(O,U){if(!(O&&U))return;const A=new Date("2020-01-01T"+O).valueOf(),N=new Date("2020-01-01T"+U).valueOf();if(A&&N)return A-N}function u(O,U){if(!(O&&U))return;const A=i.exec(O),N=i.exec(U);if(A&&N)return O=A[1]+A[2]+A[3],U=N[1]+N[2]+N[3],O>U?1:O<U?-1:0}const h=/t|\s/i;function p(O){const U=l(O);return function(N){const G=N.split(h);return G.length===2&&s(G[0])&&U(G[1])}}function f(O,U){if(!(O&&U))return;const A=new Date(O).valueOf(),N=new Date(U).valueOf();if(A&&N)return A-N}function m(O,U){if(!(O&&U))return;const[A,N]=O.split(h),[G,X]=U.split(h),Q=a(A,G);if(Q!==void 0)return Q||c(N,X)}const v=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w(O){return v.test(O)&&y.test(O)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(O){return _.lastIndex=0,_.test(O)}const C=-2147483648,b=2**31-1;function k(O){return Number.isInteger(O)&&O<=b&&O>=C}function S(O){return Number.isInteger(O)}function I(){return!0}const x=/[^\\]\\Z/;function j(O){if(x.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(lu)),lu}var cu={},a0;function cS(){return a0||(a0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Yf(),r=Oe(),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:m}=p;if(!f.validateFormats)return;const v=new t.KeywordCxt(p,m.RULES.all.format.definition,"format");v.$data?y():w();function y(){const g=l.scopeValue("formats",{ref:m.formats,code:f.code.formats}),C=l.const("fmt",(0,r._)`${g}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${C} != "object"`,(0,r._)`${C} instanceof RegExp`,(0,r._)`typeof ${C}.compare != "function"`,_(C)))}function w(){const g=v.schema,C=m.formats[g];if(!C||C===!0)return;if(typeof C!="object"||C instanceof RegExp||typeof C.compare!="function")throw new Error(`"${h}": format "${g}" does not define "compare" function`);const b=l.scopeValue("formats",{key:g,ref:C,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(g)}`:void 0});i.fail$data(_(b))}function _(g){return(0,r._)`${g}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(cu)),cu}var i0;function uS(){return i0||(i0=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=lS(),n=cS(),o=Oe(),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,m;(f=(m=c.opts.code).formats)!==null&&f!==void 0||(m.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const v of u)c.addFormat(v,h[v])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(Zi,Zi.exports)),Zi.exports}var dS=uS();const pS=An(dS);function fS(){const e=new Qf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return pS(e),e}class l0{constructor(t){this._ajv=t??fS()}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 hS{constructor(t){this._client=t}async*callToolStream(t,r=ko,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 le(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new le(de.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof le){yield{type:"error",error:u};return}yield{type:"error",error:new le(de.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function c0(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 u0(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 Fi(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&&Fi(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Fi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Fi(r,t)}}function mS(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 Ms extends r0{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 l0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Qc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Kc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Fc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new hS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=o0(this._capabilities,t)}setRequestHandler(t,r){const o=Co(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(wr(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=br(tu,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=mS(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new le(de.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!f)throw new le(de.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(r(l,c));if(h.task){const _=br(wo,m);if(!_.success){const g=_.error instanceof Error?_.error.message:String(_.error);throw new le(de.InvalidParams,`Invalid task creation result: ${g}`)}return _.data}const v=br(Rs,m);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new le(de.InvalidParams,`Invalid elicitation result: ${_}`)}const y=v.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{Fi(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=br(Xc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid sampling request: ${y}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const y=br(wo,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new le(de.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const m=h.tools||h.toolChoice?eu:Ui,v=br(m,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new le(de.InvalidParams,`Invalid sampling result: ${y}`)}return v.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:ks,capabilities:this._capabilities,clientInfo:this._clientInfo}},Tm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!gm.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){c0(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&u0(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},kn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Dm,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},kn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Am,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Nm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Em,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},$m,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Rm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},kn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},kn,r)}async callTool(t,r=ko,n){if(this.isToolTaskRequired(t.name))throw new le(de.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new le(de.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new le(de.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof le?a:new le(de.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},Lm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=jT.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 d0 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 uu(e){}function p0(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=uu,onError:r=uu,onRetry:n=uu,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=gS(`${s}${y}`);for(const g of w)h(g);s=_,a=!1}function h(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const w=v.slice(0,y),_=v[y+1]===" "?2:1,g=v.slice(y+_);p(w,g,v);return}p(v,"",v)}function p(v,y,w){switch(v){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 d0(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new d0(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,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 m(v={}){s&&v.consume&&h(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:m}}function gS(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 i0 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(l0(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(l0(this),r)}}function dS(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function ou(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(ou).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${ou(e.cause)}`:e.message:`${e}`}function l0(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var c0=e=>{throw TypeError(e)},su=(e,t,r)=>t.has(e)||c0("Cannot "+r),qe=(e,t,r)=>(su(e,t,"read from private field"),r?r.call(e):t.get(e)),kt=(e,t,r)=>t.has(e)?c0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),nt=(e,t,r,n)=>(su(e,t,"write to private field"),t.set(e,r),r),tn=(e,t,r)=>(su(e,t,"access private method"),r),Wt,Bn,Co,zi,Zi,Ps,So,Ms,kn,Io,Eo,xo,Os,Cr,au,iu,lu,u0,cu,uu,Ns,du,pu;class Fi extends EventTarget{constructor(t,r){var n,o;super(),kt(this,Cr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,kt(this,Wt),kt(this,Bn),kt(this,Co),kt(this,zi),kt(this,Zi),kt(this,Ps),kt(this,So),kt(this,Ms,null),kt(this,kn),kt(this,Io),kt(this,Eo,null),kt(this,xo,null),kt(this,Os,null),kt(this,iu,async s=>{var a;qe(this,Io).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){tn(this,Cr,Ns).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?nt(this,Co,new URL(s.url)):nt(this,Co,void 0),c!==200){tn(this,Cr,Ns).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){tn(this,Cr,Ns).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,Wt)===this.CLOSED)return;nt(this,Wt,this.OPEN);const h=new Event("open");if((a=qe(this,Os))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){tn(this,Cr,Ns).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:v,value:y}=await f.read();y&&qe(this,Io).feed(p.decode(y,{stream:!v})),v&&(g=!1,qe(this,Io).reset(),tn(this,Cr,du).call(this))}while(g)}),kt(this,lu,s=>{nt(this,kn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&tn(this,Cr,du).call(this,ou(s))}),kt(this,cu,s=>{typeof s.id=="string"&&nt(this,Ms,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:qe(this,Co)?qe(this,Co).origin:qe(this,Bn).origin,lastEventId:s.id||""});qe(this,xo)&&(!s.event||s.event==="message")&&qe(this,xo).call(this,a),this.dispatchEvent(a)}),kt(this,uu,s=>{nt(this,Ps,s)}),kt(this,pu,()=>{nt(this,So,void 0),qe(this,Wt)===this.CONNECTING&&tn(this,Cr,au).call(this)});try{if(t instanceof URL)nt(this,Bn,t);else if(typeof t=="string")nt(this,Bn,new URL(t,pS()));else throw new Error("Invalid URL")}catch{throw dS("An invalid or illegal string was specified")}nt(this,Io,a0({onEvent:qe(this,cu),onRetry:qe(this,uu)})),nt(this,Wt,this.CONNECTING),nt(this,Ps,3e3),nt(this,Zi,(n=r?.fetch)!=null?n:globalThis.fetch),nt(this,zi,(o=r?.withCredentials)!=null?o:!1),tn(this,Cr,au).call(this)}get readyState(){return qe(this,Wt)}get url(){return qe(this,Bn).href}get withCredentials(){return qe(this,zi)}get onerror(){return qe(this,Eo)}set onerror(t){nt(this,Eo,t)}get onmessage(){return qe(this,xo)}set onmessage(t){nt(this,xo,t)}get onopen(){return qe(this,Os)}set onopen(t){nt(this,Os,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(){qe(this,So)&&clearTimeout(qe(this,So)),qe(this,Wt)!==this.CLOSED&&(qe(this,kn)&&qe(this,kn).abort(),nt(this,Wt,this.CLOSED),nt(this,kn,void 0))}}Wt=new WeakMap,Bn=new WeakMap,Co=new WeakMap,zi=new WeakMap,Zi=new WeakMap,Ps=new WeakMap,So=new WeakMap,Ms=new WeakMap,kn=new WeakMap,Io=new WeakMap,Eo=new WeakMap,xo=new WeakMap,Os=new WeakMap,Cr=new WeakSet,au=function(){nt(this,Wt,this.CONNECTING),nt(this,kn,new AbortController),qe(this,Zi)(qe(this,Bn),tn(this,Cr,u0).call(this)).then(qe(this,iu)).catch(qe(this,lu))},iu=new WeakMap,lu=new WeakMap,u0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,Ms)?{"Last-Event-ID":qe(this,Ms)}:void 0},cache:"no-store",signal:(e=qe(this,kn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},cu=new WeakMap,uu=new WeakMap,Ns=function(e,t){var r;qe(this,Wt)!==this.CLOSED&&nt(this,Wt,this.CLOSED);const n=new i0("error",{code:t,message:e});(r=qe(this,Eo))==null||r.call(this,n),this.dispatchEvent(n)},du=function(e,t){var r;if(qe(this,Wt)===this.CLOSED)return;nt(this,Wt,this.CONNECTING);const n=new i0("error",{code:t,message:e});(r=qe(this,Eo))==null||r.call(this,n),this.dispatchEvent(n),nt(this,So,setTimeout(qe(this,pu),qe(this,Ps)))},pu=new WeakMap,Fi.CONNECTING=0,Fi.OPEN=1,Fi.CLOSED=2;function pS(){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 Vi(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function d0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Vi(t.headers),...Vi(n.headers)}:t.headers};return e(r,o)}:e}let fu;fu=globalThis.crypto;async function fS(e){return(await fu).getRandomValues(new Uint8Array(e))}async function hS(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await fS(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function mS(e){return await hS(e)}async function gS(e){const t=await(await fu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function p0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await mS(e),r=await gS(t);return{code_verifier:t,code_challenge:r}}const Ot=ik().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:lm.custom,message:"URL must be parseable",fatal:!0}),sh}).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"}),yS=lt({resource:d().url(),authorization_servers:q(Ot).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:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}),f0=lt({issuer:d(),authorization_endpoint:Ot,token_endpoint:Ot,registration_endpoint:Ot.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:Ot.optional(),revocation_endpoint:Ot.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:ge().optional()}),vS=lt({issuer:d(),authorization_endpoint:Ot,token_endpoint:Ot,userinfo_endpoint:Ot.optional(),jwks_uri:Ot,registration_endpoint:Ot.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:ge().optional(),request_parameter_supported:ge().optional(),request_uri_parameter_supported:ge().optional(),require_request_uri_registration:ge().optional(),op_policy_uri:Ot.optional(),op_tos_uri:Ot.optional(),client_id_metadata_document_supported:ge().optional()}),_S=T({...vS.shape,...f0.pick({code_challenge_methods_supported:!0}).shape}),wS=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:cm().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),bS=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),h0=Ot.optional().or(R("").transform(()=>{})),kS=T({redirect_uris:q(Ot),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Ot.optional(),logo_uri:h0,scope:d().optional(),contacts:q(d()).optional(),tos_uri:h0,policy_uri:d().optional(),jwks_uri:Ot.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),TS=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:D().optional(),client_secret_expires_at:D().optional()}).strip(),CS=kS.merge(TS);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 IS({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 Ct 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 hu extends Ct{}hu.errorCode="invalid_request";let Hi=class extends Ct{};Hi.errorCode="invalid_client";let Bi=class extends Ct{};Bi.errorCode="invalid_grant";let Ji=class extends Ct{};Ji.errorCode="unauthorized_client";class mu extends Ct{}mu.errorCode="unsupported_grant_type";class gu extends Ct{}gu.errorCode="invalid_scope";class yu extends Ct{}yu.errorCode="access_denied";let $o=class extends Ct{};$o.errorCode="server_error";class vu extends Ct{}vu.errorCode="temporarily_unavailable";class _u extends Ct{}_u.errorCode="unsupported_response_type";class wu extends Ct{}wu.errorCode="unsupported_token_type";class bu extends Ct{}bu.errorCode="invalid_token";class ku extends Ct{}ku.errorCode="method_not_allowed";class Tu extends Ct{}Tu.errorCode="too_many_requests";class Gi extends Ct{}Gi.errorCode="invalid_client_metadata";class Cu extends Ct{}Cu.errorCode="insufficient_scope";class Su extends Ct{}Su.errorCode="invalid_target";const ES={[hu.errorCode]:hu,[Hi.errorCode]:Hi,[Bi.errorCode]:Bi,[Ji.errorCode]:Ji,[mu.errorCode]:mu,[gu.errorCode]:gu,[yu.errorCode]:yu,[$o.errorCode]:$o,[vu.errorCode]:vu,[_u.errorCode]:_u,[wu.errorCode]:wu,[bu.errorCode]:bu,[ku.errorCode]:ku,[Tu.errorCode]:Tu,[Gi.errorCode]:Gi,[Cu.errorCode]:Cu,[Su.errorCode]:Su};let ur=class extends Error{constructor(t){super(t??"Unauthorized")}};function xS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Iu="code",Eu="S256";function $S(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&&xS(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 RS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":PS(o,s,r);return;case"client_secret_post":MS(o,s,n);return;case"none":OS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function PS(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 MS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function OS(e,t){t.set("client_id",e)}async function m0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=bS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=ES[o]||$o;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new $o(o)}}async function Jn(e,t){try{return await xu(e,t)}catch(r){if(r instanceof Hi||r instanceof Ji)return await e.invalidateCredentials?.("all"),await xu(e,t);if(r instanceof Bi)return await e.invalidateCredentials?.("tokens"),await xu(e,t);throw r}}async function xu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await qS(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 AS(t,e,a),c=await zS(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&&!NS(w))throw new Gi(`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 BS(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 HS(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 VS(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 Ct)||y instanceof $o))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await ZS(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(v),await e.redirectToAuthorization(g),"REDIRECT"}function NS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function AS(e,t,r){const n=SS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!IS({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 Wi(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=$u(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=$u(e,"scope")||void 0,i=$u(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function $u(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 qS(e,t,r=fetch){const n=await DS(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 yS.parse(await n.json())}async function Ru(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ru(e,void 0,r):void 0;throw n}}function LS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function g0(e,t,r=fetch){return await Ru(e,{"MCP-Protocol-Version":t},r)}function jS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function DS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ws;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=LS(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await g0(a,s,r);if(!n?.metadataUrl&&jS(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await g0(l,s,r)}return i}function US(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 zS(e,{fetchFn:t=fetch,protocolVersion:r=ws}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=US(e);for(const{url:s,type:a}of o){const i=await Ru(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"?f0.parse(await i.json()):_S.parse(await i.json())}}}async function ZS(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(Iu))throw new Error(`Incompatible auth server: does not support response type ${Iu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Eu))throw new Error(`Incompatible auth server: does not support code challenge method ${Eu}`)}else i=new URL("/authorize",e);const l=await p0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Iu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Eu),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 FS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function y0(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=$S(n,u);RS(h,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await m0(c);return wS.parse(await c.json())}async function VS(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 y0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function HS(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=FS(o,c,e.redirectUrl)}const l=await e.clientInformation();return y0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function BS(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 m0(s);return CS.parse(await s.json())}class JS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class As{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=d0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new ur("No auth provider");let t;try{t=await Jn(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 ur;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=Vi(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 Fi(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}=Wi(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 JS(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=en.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 ur("No auth provider");if(await Jn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur("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}=Wi(o);if(this._resourceMetadataUrl=a,this._scope=i,await Jn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur;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 Ro extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=a0({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 GS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Po extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class qs{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=d0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??GS}async _authThenStart(){if(!this._authProvider)throw new ur("No auth provider");let t;try{t=await Jn(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 ur;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=Vi(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 Po(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 Ro({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 v=en.parse(JSON.parse(f.data));ks(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(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 ur("No auth provider");if(await Jn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur("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:_c(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 Po(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=Wi(i);if(this._resourceMetadataUrl=f,this._scope=g,await Jn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:v}=Wi(i);if(v==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Po(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await Jn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ur;return this.send(t)}}throw new Po(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),uT(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=>en.parse(g)):[en.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await i.body?.cancel(),new Po(-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 Po(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 WS="mcp";class v0{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,WS),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=en.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 Tn=nr;(function(e,t){const r=nr,n=nr,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())}})(Ki,-118057+3521*-35+-2099*-233);const _0=()=>{const e=nr,t=nr,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}},KS=(e,t,r)=>{const n=nr,o=nr,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)},YS=(e,t)=>{const r=nr,n=nr,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 Ls{constructor(t){this._port=t}async[Tn(401)](){const t=Tn,r=Tn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=en.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=nr,l=nr;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=Tn,o=Tn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class Pu extends Ls{constructor(t,r=_0()){const n=Tn,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)](KS,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class Mu extends Ls{constructor(t,r=_0()){const n=Tn,o=Tn,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)](YS,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 Ki(){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 Ki=function(){return e},Ki()}function nr(e,t){const r=Ki();return nr=function(n,o){return n=n-(17227+1*-16844),r[n]},nr(e,t)}const QS=()=>{const e=new MessageChannel;return[new Ls(e.port1),new Ls(e.port2)]};(function(e,t){const r=Ye,n=Ye,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Yi,-411935*1+228107+208149*2);const XS=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case i.VRyiJ:h=await t.listTools(u);break;case i.VkPYu:h=await t.callTool(u);break;case i.fgMSD:h=await t.listResources(u);break;case i[s(466)]:h=await t.listResourceTemplates(u);break;case i.sthgI:h=await t[o(455)](u);break;case s(486):h=await t.subscribeResource(u);break;case o(410):h=await t.unsubscribeResource(u);break;case i[s(461)]:h=await t[s(414)](u);break;case i[o(412)]:h=await t[o(491)](u);break;case i[o(436)]:h=await t[o(478)]();break;case i.kkNqg:h=await t.complete(u);break;case o(464):h=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=h,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},e6=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,h=await t[o(469)](f,Kc);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,h=await t.request(g,Li);break;case i[o(487)]:const v={};v.method=c,v[s(446)]=u,h=await t.request(v,xs);break;case i.ypHTC:const y={};y.method=c,h=await t.request(y,bn);break}const p={};return p.result=h,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),h};function Ye(e,t){const r=Yi();return Ye=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ye(e,t)}const t6=(e,t)=>{const r=Ye,n=Ye,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,h,p;const f=n,g=r,{id:v,method:y}=a;try{o[f(451)](y,o.DhPFX)?await s.call(e,a,i):await o[g(474)](XS,e,t,a)}catch(w){const{code:_,message:m,data:C}=w;try{if(_){const b={};b[g(485)]=_,b[f(422)]=m,b.data=C;const k={};k[g(448)]=b,k.jsonrpc=o[f(417)],k.id=v,await((l=e?.transport)==null?void 0:l[g(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(h=e?.transport)==null?void 0:h.onerror)==null||p.call(h,b)}}}},r6=(e,t)=>{const r=Ye,n=Ye,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:h,params:p}=a;if(h!==s[c(476)]&&(s.QWYMz(h,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},n6=(e,t)=>async r=>{var n,o,s,a,i;const l=Ye,c=Ye,u={TJhyV:function(h,p,f,g){return h(p,f,g)},MMNTY:l(465)};try{return await u.TJhyV(e6,e,t,r)}catch(h){const{code:p,message:f,data:g}=h;try{if(p){const v={};v.code=p,v[l(422)]=f,v[c(419)]=g;const y={};y[l(448)]=v,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(v){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},o6=(e,t)=>async r=>{var n,o,s;const a=Ye,i=Ye,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:h}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||h?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Yi(){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 Yi=function(){return e},Yi()}const s6=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Ye,u=Ye,h={};h.kSvAZ=c(465);const p=h;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:g,message:v,data:y}=f;try{if(g){const w={};w.code=g,w.message=v,w.data=y;const _={};_.error=w,_[u(424)]=p.kSvAZ,_.id=r.id,await((o=e?.transport)==null?void 0:o.send(_))}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)}}},Ou=()=>{const e=Ye,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ye;if(c){const h=[];for(const p of r)try{h.push(p(l,c))}catch{}for(const p of h)if(t.rgPZO(p,null))return p}else for(const h of r)try{t[u(427)](h,l)}catch{}},o=l=>{const c=Ye,u=Ye;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ye,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Ye;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},a6=e=>{const t=Ye,r=Ye,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](Ou);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)](Ou);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(Ou);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},i6=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ye,o=Ye,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(a6,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)})},l6=rn;(function(e,t){const r=rn,n=rn,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())}})(Qi,995159+-6*-266138+-1619768);const c6=()=>{const e=rn,t=rn,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)})},u6=e=>{const t=rn,r=rn,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)]("")},Cn={};Cn[l6(211)]=c6,Cn.randomBytes=u6;function rn(e,t){const r=Qi();return rn=function(n,o){return n=n-(-7373+7187*1+395),r[n]},rn(e,t)}function Qi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Qi=function(){return e},Qi()}function nn(e,t){const r=Xi();return nn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},nn(e,t)}const Sr=nn,js=nn;(function(e,t){const r=nn,n=nn,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())}})(Xi,-4*308317+753182*2+658196);const d6=(e,t)=>{const r=nn,n=nn,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)](t6,e,t),r6(e,t);const s=o[n(283)](n6,t,e),a=o[n(294)](s6,t,e),i=o[r(277)](o6,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)}},Nu=(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,As)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[nn(295)])==null||i.close()})),n.Qalmc(d6,e,t)},s={};s.afterInit=o,n.Qalmc(i6,t,s)},w0=(e,t=Cn[Sr(299)]())=>{const r=Sr,n=Sr,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 v={...h};return v.headers=g,o[f(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},b0=(e,t=Cn[Sr(299)]())=>{const r=js,n=Sr,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},Au=async(e,t,r)=>{const n=Sr,o=Sr,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,ur)){const l=await t();return await a[n(257)](l),await Au(e,t,r)}else throw i}},k0=(e,t)=>{const r=js,n=js,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 Xi(){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 Xi=function(){return e},Xi()}const p6=async e=>{const t=js,r=Sr,n={GKDjq:function(E,j,O){return E(j,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(E){return E()},kdowC:function(E,j,O,U){return E(j,O,U)},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||Cn[r(299)](),v=n[t(289)](w0,a,g);if(c){const E={...v.requestInit,...c};E[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=E}else f.requestInit=v[t(280)];if(u){const E={...v[t(270)],...u};f.eventSourceInit=E}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,m={};m.name=n[r(261)],m[t(288)]=n.mcbiU;const C={};C[t(251)]=_;const b=new Rs(m,C),k=()=>new As(new URL(s),f);let S=n[t(282)](k);if(l){const E=k0(l,h);S=await n[t(263)](Au,b,E,k)}else await b.connect(S);Nu(b,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=S,I.sessionId=S[r(286)],I},f6=async e=>{const t=js,r=Sr,n={wfHUn:function(E,j,O){return E(j,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(E){return E()},PdsSn:function(E,j,O,U){return E(j,O,U)}},{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||Cn.randomUUID(),v=n[r(272)](b0,a,g);if(c){const E={...v[t(280)],...c};E.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=E}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,m={};m.name=n[t(262)],m.version=n.omKPe;const C={};C.capabilities=_;const b=new Rs(m,C),k=()=>new qs(new URL(s),f);let S=n.rSiEq(k);if(l){const E=n[t(272)](k0,l,h);S=await n[t(296)](Au,b,E,k)}else await b[t(260)](S);n.PdsSn(Nu,b,o,S);const I={};return I.transport=S,I[r(286)]=S[r(286)],I},h6=async e=>{const t=Sr,r=Sr,n={eZwNI:function(w,_,m,C){return w(_,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 Rs(h,p),g=i||Cn[r(299)](),v=new v0(new URL(s+"?sessionId="+g+r(265)+a));await f.connect(v),n[t(259)](Nu,f,o,v);const y={};return y.transport=v,y[r(286)]=g,y},Sn=Ir,Ds=Ir;(function(e,t){const r=Ir,n=Ir,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())}})(el,1297719+-42747*-22+-1289197);function Ir(e,t){const r=el();return Ir=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Ir(e,t)}const m6=()=>Cn.randomBytes(-8746+-382*-23);class g6{constructor(t){const r=Ir,n=Ir,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(m6),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=Ir,c=Ir,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[Sn(191)](t,r){const n=Sn,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=Ir;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Sn(206)]}get[Ds(190)](){return this._clientMetadata}[Sn(213)](){return this[Sn(197)]}[Ds(218)](){return this[Ds(200)]}[Sn(194)](t){this._clientInformation=t}tokens(){return this[Ds(210)]}saveTokens(t){const r=Ds;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Sn(212)](){const t=Sn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function el(){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 el=function(){return e},el()}(function(e,t){for(var r=rl,n=rl,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())}})(tl,262*-2438+1346066*-1+2*1373311);function tl(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return tl=function(){return e},tl()}function rl(e,t){var r=tl();return rl=function(n,o){n=n-287;var s=r[n];return s},rl(e,t)}class y6{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 v6 extends Km{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ni.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 r0,this.setRequestHandler(gm,n=>this._oninitialize(n)),this.setNotificationHandler(Tc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ai,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=Ni.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new y6(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qm(this._capabilities,t)}setRequestHandler(t,r){const o=To(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(wr(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=br(Oi,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid tools/call request: ${g}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const g=br(_o,p);if(!g.success){const v=g.error instanceof Error?g.error.message:String(g.error);throw new le(de.InvalidParams,`Invalid task creation result: ${v}`)}return g.data}const f=br(bo,p);if(!f.success){const g=f.error instanceof Error?f.error.message:String(f.error);throw new le(de.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){o0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&n0(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:um.includes(r)?r:ws,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"},bn)}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},Jc,r):this.request({method:"sampling/createMessage",params:t},Li,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},xs,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},xs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new le(de.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof le?a:new le(de.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return s}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Kc,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 qu=Symbol.for("mcp.completable");function _6(e,t){return Object.defineProperty(e,qu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function T0(e){return!!e&&typeof e=="object"&&qu in e}function w6(e){return e[qu]?.complete}var C0;(function(e){e.Completable="McpCompletable"})(C0||(C0={}));const S0=1e6,Lu=1e6,I0=1e4,b6=1e6;class on{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){on.validateLength(t,S0,"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>I0)throw new Error(`Template contains too many expressions (max ${I0})`);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)on.validateLength(p,Lu,"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 on.validateLength(t,Lu,"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)on.validateLength(s,Lu,"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){on.validateLength(t,S0,"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+="$",on.validateLength(r,b6,"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 k6=/^[A-Za-z0-9._-]{1,128}$/;function T6(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!k6.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 C6(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 E0(e){const t=T6(e);return C6(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 x0{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 v6(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(In(Vc)),this.server.assertCanSetRequestHandler(In(Oi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Vc,()=>({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=$s(r.inputSchema);return o?Jm(o,{strictUnions:!0,pipeStrategy:"input"}):E6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=$s(r.outputSchema);o&&(n.outputSchema=Jm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Oi,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new le(de.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if((s==="required"||s==="optional")&&!a)throw new le(de.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new le(de.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof le&&n.code===de.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const s=$s(t.inputSchema)??t.inputSchema,a=await Yc(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Qc(i);throw new le(de.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new le(de.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=$s(t.outputSchema),s=await Yc(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Qc(a);throw new le(de.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,a))}else{const i=o;return await Promise.resolve(i.createTask(a))}}if(t.inputSchema){const a=o;return await Promise.resolve(a(r,n))}else{const a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,a={...n,taskStore:n.taskStore},i=o?await Promise.resolve(s.createTask(o,a)):await Promise.resolve(s.createTask(a)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const h=await n.taskStore.getTask(l);if(!h)throw new le(de.InternalError,`Task ${l} not found during polling`);c=h}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(In(Wc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Wc,async t=>{switch(t.params.ref.type){case"ref/prompt":return lC(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return cC(t),this.handleResourceCompletion(t,t.params.ref);default:throw new le(de.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new le(de.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Us;const s=To(n.argsSchema)?.[t.params.argument.name];if(!T0(s))return Us;const a=w6(s);if(!a)return Us;const i=await a(t.params.argument.value,t.params.context);return P0(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 Us;throw new le(de.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Us;const s=await o(t.params.argument.value,t.params.context);return P0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(In(Mi)),this.server.assertCanSetRequestHandler(In(Oc)),this.server.assertCanSetRequestHandler(In(Ac)),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(Oc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ac,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new le(de.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(n.toString());if(a)return s.readCallback(n,a,r)}throw new le(de.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(In(Lc)),this.server.assertCanSetRequestHandler(In(jc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Lc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?$6(r.argsSchema):void 0}))})),this.server.setRequestHandler(jc,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new le(de.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=$s(n.argsSchema),s=await Yc(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Qc(l);throw new le(de.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const a=s.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){const a={name:t,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(t,r,n,o,s){const a={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,n,o,s){const a={title:r,description:n,argsSchema:o===void 0?void 0:ko(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=ko(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 _r?l._def?.innerType:l;return T0(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){E0(t);const u={title:r,description:n,inputSchema:R0(o),outputSchema:R0(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"&&E0(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=ko(h.paramsSchema)),typeof h.outputSchema<"u"&&(u.outputSchema=ko(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];ju(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ju(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 I6{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new on(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const E6={type:"object",properties:{}};function $0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function x6(e){return"_def"in e||"_zod"in e||$0(e)}function ju(e){return typeof e!="object"||e===null||x6(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some($0)}function R0(e){if(e)return ju(e)?ko(e):e}function $6(e){const t=To(e);return t?Object.entries(t).map(([r,n])=>{const o=hC(n),s=mC(n);return{name:r,description:o,required:!s}}):[]}function In(e){const r=To(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Lm(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function P0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Us={completion:{values:[],hasMore:!1}};function R6(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class zs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new zs,r=new zs;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 P6{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 x0(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(Ai,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 Mu(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(Sm,t)}onUnsubscribe(t){this.server.server.setRequestHandler(Im,t)}onSetLogLevel(t){this.server.server.setRequestHandler(Ai,t)}onListResources(t){this.server.server.setRequestHandler(Mi,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(Am,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const M6=(e,t)=>new Mu(e,t),O6=()=>QS(),N6=e=>e instanceof Mu,A6=e=>e instanceof x0;class M0{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Rs(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 p6(u):s==="socket"?await h6(u):await f6(u);f.onerror=async v=>{i?.(v)},h={transport:f,sessionId:g}})(),h}const l=new URL(r);let c;if(s==="channel"&&(c=new Pu(r),await this.client.connect(c)),s==="sse"){const u=w0(n,o);c=new As(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new v0(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=b0(n,o);c=new qs(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,bo,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(Gc,t)}onCreateMessage(t){this.client.setRequestHandler(Bc,t)}onListRoots(t){this.client.setRequestHandler(Nm,t)}onToolListChanged(t){this.client.setNotificationHandler(Hc,t)}onPromptListChanged(t){this.client.setNotificationHandler(Fc,t)}onResourceListChanged(t){this.client.setNotificationHandler(qc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Em,t)}onLoggingMessage(t){this.client.setNotificationHandler(Mm,t)}async onPagehide(t){t.persisted||(O0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const q6=(e,t)=>new As(e,t),L6=(e,t)=>new qs(e,t),j6=(e,t)=>new Pu(e,t),D6=e=>e instanceof As,O0=e=>e instanceof qs,U6=e=>e instanceof Pu,z6=e=>e instanceof Rs,Mo=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},N0=(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)},Du=(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})},Uu=(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 A0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Uu("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=en.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];Du("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 zu=()=>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 Z6{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||zu(),this._messageListener1=N0("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=N0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=en.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Mo("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】 已关闭,无法发送消息"),Mo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&Mo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{Mo("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 F6{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||zu(),this.tabId=r,Uu("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】 已关闭,无法重新启动");Uu("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=en.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&Mo("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),Du("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&t.result?.content&&Mo("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,Du("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 Oo={},Zu,q0;function V6(){return q0||(q0=1,Zu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Zu}var Fu={},En={},L0;function Gn(){if(L0)return En;L0=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 En.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},En.getSymbolTotalCodewords=function(n){return t[n]},En.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},En.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},En.isKanjiModeEnabled=function(){return typeof e<"u"},En.toSJIS=function(n){return e(n)},En}var Vu={},j0;function Hu(){return j0||(j0=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}}})(Vu)),Vu}var Bu,D0;function H6(){if(D0)return Bu;D0=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++}},Bu=e,Bu}var Ju,U0;function B6(){if(U0)return Ju;U0=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]},Ju=e,Ju}var Gu={},z0;function J6(){return z0||(z0=1,(function(e){const t=Gn().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}})(Gu)),Gu}var Wu={},Z0;function G6(){if(Z0)return Wu;Z0=1;const e=Gn().getSymbolSize,t=7;return Wu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Wu}var Ku={},F0;function W6(){return F0||(F0=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}})(Ku)),Ku}var nl={},V0;function H0(){if(V0)return nl;V0=1;const e=Hu(),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 nl.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}},nl.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}},nl}var Yu={},Zs={},B0;function K6(){if(B0)return Zs;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]})(),Zs.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Zs.exp=function(n){return e[n]},Zs.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Zs}var J0;function Y6(){return J0||(J0=1,(function(e){const t=K6();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}})(Yu)),Yu}var Qu,G0;function Q6(){if(G0)return Qu;G0=1;const e=Y6();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},Qu=t,Qu}var Xu={},ed={},td={},W0;function K0(){return W0||(W0=1,td.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),td}var Dr={},Y0;function Q0(){if(Y0)return Dr;Y0=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
|
-
]))+`;Dr.KANJI=new RegExp(r,"g"),Dr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Dr.BYTE=new RegExp(n,"g"),Dr.NUMERIC=new RegExp(e,"g"),Dr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Dr.testKanji=function(l){return o.test(l)},Dr.testNumeric=function(l){return s.test(l)},Dr.testAlphanumeric=function(l){return a.test(l)},Dr}var
|
|
45
|
-
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},
|
|
46
|
-
Suggested mode is: `+t.toString(C));switch(
|
|
43
|
+
`&&n++}}return[t,r]}class f0 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(h0(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(h0(this),r)}}function yS(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function du(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(du).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${du(e.cause)}`:e.message:`${e}`}function h0(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var m0=e=>{throw TypeError(e)},pu=(e,t,r)=>t.has(e)||m0("Cannot "+r),qe=(e,t,r)=>(pu(e,t,"read from private field"),r?r.call(e):t.get(e)),kt=(e,t,r)=>t.has(e)?m0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),nt=(e,t,r,n)=>(pu(e,t,"write to private field"),t.set(e,r),r),tn=(e,t,r)=>(pu(e,t,"access private method"),r),Wt,Jn,So,Vi,Hi,Os,Io,Ns,Tn,xo,Eo,$o,As,Cr,fu,hu,mu,g0,gu,yu,qs,vu,_u;class Bi extends EventTarget{constructor(t,r){var n,o;super(),kt(this,Cr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,kt(this,Wt),kt(this,Jn),kt(this,So),kt(this,Vi),kt(this,Hi),kt(this,Os),kt(this,Io),kt(this,Ns,null),kt(this,Tn),kt(this,xo),kt(this,Eo,null),kt(this,$o,null),kt(this,As,null),kt(this,hu,async s=>{var a;qe(this,xo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){tn(this,Cr,qs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?nt(this,So,new URL(s.url)):nt(this,So,void 0),c!==200){tn(this,Cr,qs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){tn(this,Cr,qs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,Wt)===this.CLOSED)return;nt(this,Wt,this.OPEN);const h=new Event("open");if((a=qe(this,As))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){tn(this,Cr,qs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=i.getReader();let m=!0;do{const{done:v,value:y}=await f.read();y&&qe(this,xo).feed(p.decode(y,{stream:!v})),v&&(m=!1,qe(this,xo).reset(),tn(this,Cr,vu).call(this))}while(m)}),kt(this,mu,s=>{nt(this,Tn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&tn(this,Cr,vu).call(this,du(s))}),kt(this,gu,s=>{typeof s.id=="string"&&nt(this,Ns,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:qe(this,So)?qe(this,So).origin:qe(this,Jn).origin,lastEventId:s.id||""});qe(this,$o)&&(!s.event||s.event==="message")&&qe(this,$o).call(this,a),this.dispatchEvent(a)}),kt(this,yu,s=>{nt(this,Os,s)}),kt(this,_u,()=>{nt(this,Io,void 0),qe(this,Wt)===this.CONNECTING&&tn(this,Cr,fu).call(this)});try{if(t instanceof URL)nt(this,Jn,t);else if(typeof t=="string")nt(this,Jn,new URL(t,vS()));else throw new Error("Invalid URL")}catch{throw yS("An invalid or illegal string was specified")}nt(this,xo,p0({onEvent:qe(this,gu),onRetry:qe(this,yu)})),nt(this,Wt,this.CONNECTING),nt(this,Os,3e3),nt(this,Hi,(n=r?.fetch)!=null?n:globalThis.fetch),nt(this,Vi,(o=r?.withCredentials)!=null?o:!1),tn(this,Cr,fu).call(this)}get readyState(){return qe(this,Wt)}get url(){return qe(this,Jn).href}get withCredentials(){return qe(this,Vi)}get onerror(){return qe(this,Eo)}set onerror(t){nt(this,Eo,t)}get onmessage(){return qe(this,$o)}set onmessage(t){nt(this,$o,t)}get onopen(){return qe(this,As)}set onopen(t){nt(this,As,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(){qe(this,Io)&&clearTimeout(qe(this,Io)),qe(this,Wt)!==this.CLOSED&&(qe(this,Tn)&&qe(this,Tn).abort(),nt(this,Wt,this.CLOSED),nt(this,Tn,void 0))}}Wt=new WeakMap,Jn=new WeakMap,So=new WeakMap,Vi=new WeakMap,Hi=new WeakMap,Os=new WeakMap,Io=new WeakMap,Ns=new WeakMap,Tn=new WeakMap,xo=new WeakMap,Eo=new WeakMap,$o=new WeakMap,As=new WeakMap,Cr=new WeakSet,fu=function(){nt(this,Wt,this.CONNECTING),nt(this,Tn,new AbortController),qe(this,Hi)(qe(this,Jn),tn(this,Cr,g0).call(this)).then(qe(this,hu)).catch(qe(this,mu))},hu=new WeakMap,mu=new WeakMap,g0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,Ns)?{"Last-Event-ID":qe(this,Ns)}:void 0},cache:"no-store",signal:(e=qe(this,Tn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},gu=new WeakMap,yu=new WeakMap,qs=function(e,t){var r;qe(this,Wt)!==this.CLOSED&&nt(this,Wt,this.CLOSED);const n=new f0("error",{code:t,message:e});(r=qe(this,Eo))==null||r.call(this,n),this.dispatchEvent(n)},vu=function(e,t){var r;if(qe(this,Wt)===this.CLOSED)return;nt(this,Wt,this.CONNECTING);const n=new f0("error",{code:t,message:e});(r=qe(this,Eo))==null||r.call(this,n),this.dispatchEvent(n),nt(this,Io,setTimeout(qe(this,_u),qe(this,Os)))},_u=new WeakMap,Bi.CONNECTING=0,Bi.OPEN=1,Bi.CLOSED=2;function vS(){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 Ji(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function y0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ji(t.headers),...Ji(n.headers)}:t.headers};return e(r,o)}:e}let wu;wu=globalThis.crypto;async function _S(e){return(await wu).getRandomValues(new Uint8Array(e))}async function wS(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await _S(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function bS(e){return await wS(e)}async function kS(e){const t=await(await wu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function v0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await bS(e),r=await kS(t);return{code_verifier:t,code_challenge:r}}const Ot=f4().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hm.custom,message:"URL must be parseable",fatal:!0}),dh}).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"}),TS=lt({resource:d().url(),authorization_servers:q(Ot).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:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}),_0=lt({issuer:d(),authorization_endpoint:Ot,token_endpoint:Ot,registration_endpoint:Ot.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:Ot.optional(),revocation_endpoint:Ot.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:ge().optional()}),CS=lt({issuer:d(),authorization_endpoint:Ot,token_endpoint:Ot,userinfo_endpoint:Ot.optional(),jwks_uri:Ot,registration_endpoint:Ot.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:ge().optional(),request_parameter_supported:ge().optional(),request_uri_parameter_supported:ge().optional(),require_request_uri_registration:ge().optional(),op_policy_uri:Ot.optional(),op_tos_uri:Ot.optional(),client_id_metadata_document_supported:ge().optional()}),SS=T({...CS.shape,..._0.pick({code_challenge_methods_supported:!0}).shape}),IS=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:mm().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),xS=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),w0=Ot.optional().or(R("").transform(()=>{})),ES=T({redirect_uris:q(Ot),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Ot.optional(),logo_uri:w0,scope:d().optional(),contacts:q(d()).optional(),tos_uri:w0,policy_uri:d().optional(),jwks_uri:Ot.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),$S=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:D().optional(),client_secret_expires_at:D().optional()}).strip(),RS=ES.merge($S);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function PS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function MS({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 Ct 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 bu extends Ct{}bu.errorCode="invalid_request";let Gi=class extends Ct{};Gi.errorCode="invalid_client";let Wi=class extends Ct{};Wi.errorCode="invalid_grant";let Ki=class extends Ct{};Ki.errorCode="unauthorized_client";class ku extends Ct{}ku.errorCode="unsupported_grant_type";class Tu extends Ct{}Tu.errorCode="invalid_scope";class Cu extends Ct{}Cu.errorCode="access_denied";let Ro=class extends Ct{};Ro.errorCode="server_error";class Su extends Ct{}Su.errorCode="temporarily_unavailable";class Iu extends Ct{}Iu.errorCode="unsupported_response_type";class xu extends Ct{}xu.errorCode="unsupported_token_type";class Eu extends Ct{}Eu.errorCode="invalid_token";class $u extends Ct{}$u.errorCode="method_not_allowed";class Ru extends Ct{}Ru.errorCode="too_many_requests";class Yi extends Ct{}Yi.errorCode="invalid_client_metadata";class Pu extends Ct{}Pu.errorCode="insufficient_scope";class Mu extends Ct{}Mu.errorCode="invalid_target";const OS={[bu.errorCode]:bu,[Gi.errorCode]:Gi,[Wi.errorCode]:Wi,[Ki.errorCode]:Ki,[ku.errorCode]:ku,[Tu.errorCode]:Tu,[Cu.errorCode]:Cu,[Ro.errorCode]:Ro,[Su.errorCode]:Su,[Iu.errorCode]:Iu,[xu.errorCode]:xu,[Eu.errorCode]:Eu,[$u.errorCode]:$u,[Ru.errorCode]:Ru,[Yi.errorCode]:Yi,[Pu.errorCode]:Pu,[Mu.errorCode]:Mu};let ur=class extends Error{constructor(t){super(t??"Unauthorized")}};function NS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Ou="code",Nu="S256";function AS(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&&NS(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 qS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":LS(o,s,r);return;case"client_secret_post":jS(o,s,n);return;case"none":DS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function LS(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 jS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function DS(e,t){t.set("client_id",e)}async function b0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=xS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=OS[o]||Ro;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Ro(o)}}async function Gn(e,t){try{return await Au(e,t)}catch(r){if(r instanceof Gi||r instanceof Ki)return await e.invalidateCredentials?.("all"),await Au(e,t);if(r instanceof Wi)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 ZS(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 zS(t,e,a),c=await JS(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&&!US(w))throw new Yi(`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 g=await QS(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(g),u=g}}const h=!e.redirectUrl;if(r!==void 0||h){const y=await YS(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await KS(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof Ct)||y instanceof Ro))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:v}=await GS(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(v),await e.redirectToAuthorization(m),"REDIRECT"}function US(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function zS(e,t,r){const n=PS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!MS({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 Qi(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=qu(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=qu(e,"scope")||void 0,i=qu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function qu(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 ZS(e,t,r=fetch){const n=await HS(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 TS.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 FS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function k0(e,t,r=fetch){return await Lu(e,{"MCP-Protocol-Version":t},r)}function VS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function HS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ks;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=FS(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await k0(a,s,r);if(!n?.metadataUrl&&VS(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await k0(l,s,r)}return i}function BS(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 JS(e,{fetchFn:t=fetch,protocolVersion:r=ks}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=BS(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"?_0.parse(await i.json()):SS.parse(await i.json())}}}async function GS(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(Nu))throw new Error(`Incompatible auth server: does not support code challenge method ${Nu}`)}else i=new URL("/authorize",e);const l=await v0(),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",Nu),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 WS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function T0(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=AS(n,u);qS(h,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await b0(c);return IS.parse(await c.json())}async function KS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await T0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function YS(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=WS(o,c,e.redirectUrl)}const l=await e.clientInformation();return T0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function QS(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 b0(s);return RS.parse(await s.json())}class XS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ls{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=y0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new ur("No auth provider");let t;try{t=await Gn(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 ur;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=Ji(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 Bi(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}=Qi(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=en.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 ur("No auth provider");if(await Gn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur("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}=Qi(o);if(this._resourceMetadataUrl=a,this._scope=i,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur;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 Po extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=p0({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 e6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Mo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class js{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=y0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??e6}async _authThenStart(){if(!this._authProvider)throw new ur("No auth provider");let t;try{t=await Gn(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 ur;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=Ji(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 Mo(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 Po({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:m}=await u.read();if(m)break;if(f.id&&(a=f.id,i=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=en.parse(JSON.parse(f.data));Cs(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(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 ur("No auth provider");if(await Gn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur("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:Ic(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 Mo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:m}=Qi(i);if(this._resourceMetadataUrl=f,this._scope=m,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ur;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:m,error:v}=Qi(i);if(v==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Mo(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ur;return this.send(t)}}throw new Mo(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),gT(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(m=>en.parse(m)):[en.parse(p)];for(const m of f)this.onmessage?.(m)}else throw await i.body?.cancel(),new Mo(-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 Mo(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 t6="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,t6),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=en.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 Cn=nr;(function(e,t){const r=nr,n=nr,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())}})(Xi,-118057+3521*-35+-2099*-233);const S0=()=>{const e=nr,t=nr,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}},r6=(e,t,r)=>{const n=nr,o=nr,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)},n6=(e,t)=>{const r=nr,n=nr,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 Ds{constructor(t){this._port=t}async[Cn(401)](){const t=Cn,r=Cn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=en.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=nr,l=nr;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=Cn,o=Cn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class ju extends Ds{constructor(t,r=S0()){const n=Cn,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)](r6,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class Du extends Ds{constructor(t,r=S0()){const n=Cn,o=Cn,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)](n6,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 Xi(){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 Xi=function(){return e},Xi()}function nr(e,t){const r=Xi();return nr=function(n,o){return n=n-(17227+1*-16844),r[n]},nr(e,t)}const o6=()=>{const e=new MessageChannel;return[new Ds(e.port1),new Ds(e.port2)]};(function(e,t){const r=Ye,n=Ye,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(el,-411935*1+228107+208149*2);const s6=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case i.VRyiJ:h=await t.listTools(u);break;case i.VkPYu:h=await t.callTool(u);break;case i.fgMSD:h=await t.listResources(u);break;case i[s(466)]:h=await t.listResourceTemplates(u);break;case i.sthgI:h=await t[o(455)](u);break;case s(486):h=await t.subscribeResource(u);break;case o(410):h=await t.unsubscribeResource(u);break;case i[s(461)]:h=await t[s(414)](u);break;case i[o(412)]:h=await t[o(491)](u);break;case i[o(436)]:h=await t[o(478)]();break;case i.kkNqg:h=await t.complete(u);break;case o(464):h=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=h,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},a6=async(e,t,r)=>{var n;const o=Ye,s=Ye,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let h={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,h=await t[o(469)](f,nu);break;case"sampling/createMessage":const m={};m[o(481)]=c,m[o(446)]=u,h=await t.request(m,Ui);break;case i[o(487)]:const v={};v.method=c,v[s(446)]=u,h=await t.request(v,Rs);break;case i.ypHTC:const y={};y.method=c,h=await t.request(y,kn);break}const p={};return p.result=h,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),h};function Ye(e,t){const r=el();return Ye=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ye(e,t)}const i6=(e,t)=>{const r=Ye,n=Ye,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,h,p;const f=n,m=r,{id:v,method:y}=a;try{o[f(451)](y,o.DhPFX)?await s.call(e,a,i):await o[m(474)](s6,e,t,a)}catch(w){const{code:_,message:g,data:C}=w;try{if(_){const b={};b[m(485)]=_,b[f(422)]=g,b.data=C;const k={};k[m(448)]=b,k.jsonrpc=o[f(417)],k.id=v,await((l=e?.transport)==null?void 0:l[m(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(h=e?.transport)==null?void 0:h.onerror)==null||p.call(h,b)}}}},l6=(e,t)=>{const r=Ye,n=Ye,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:h,params:p}=a;if(h!==s[c(476)]&&(s.QWYMz(h,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},c6=(e,t)=>async r=>{var n,o,s,a,i;const l=Ye,c=Ye,u={TJhyV:function(h,p,f,m){return h(p,f,m)},MMNTY:l(465)};try{return await u.TJhyV(a6,e,t,r)}catch(h){const{code:p,message:f,data:m}=h;try{if(p){const v={};v.code=p,v[l(422)]=f,v[c(419)]=m;const y={};y[l(448)]=v,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(v){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},u6=(e,t)=>async r=>{var n,o,s;const a=Ye,i=Ye,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:h}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||h?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function el(){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 el=function(){return e},el()}const d6=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Ye,u=Ye,h={};h.kSvAZ=c(465);const p=h;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:m,message:v,data:y}=f;try{if(m){const w={};w.code=m,w.message=v,w.data=y;const _={};_.error=w,_[u(424)]=p.kSvAZ,_.id=r.id,await((o=e?.transport)==null?void 0:o.send(_))}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)}}},Uu=()=>{const e=Ye,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ye;if(c){const h=[];for(const p of r)try{h.push(p(l,c))}catch{}for(const p of h)if(t.rgPZO(p,null))return p}else for(const h of r)try{t[u(427)](h,l)}catch{}},o=l=>{const c=Ye,u=Ye;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ye,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Ye;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},p6=e=>{const t=Ye,r=Ye,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](Uu);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)](Uu);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(Uu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},f6=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ye,o=Ye,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(p6,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)})},h6=rn;(function(e,t){const r=rn,n=rn,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())}})(tl,995159+-6*-266138+-1619768);const m6=()=>{const e=rn,t=rn,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)})},g6=e=>{const t=rn,r=rn,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)]("")},Sn={};Sn[h6(211)]=m6,Sn.randomBytes=g6;function rn(e,t){const r=tl();return rn=function(n,o){return n=n-(-7373+7187*1+395),r[n]},rn(e,t)}function tl(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return tl=function(){return e},tl()}function nn(e,t){const r=rl();return nn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},nn(e,t)}const Sr=nn,Us=nn;(function(e,t){const r=nn,n=nn,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())}})(rl,-4*308317+753182*2+658196);const y6=(e,t)=>{const r=nn,n=nn,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)](i6,e,t),l6(e,t);const s=o[n(283)](c6,t,e),a=o[n(294)](d6,t,e),i=o[r(277)](u6,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)}},zu=(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,Ls)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[nn(295)])==null||i.close()})),n.Qalmc(y6,e,t)},s={};s.afterInit=o,n.Qalmc(f6,t,s)},I0=(e,t=Sn[Sr(299)]())=>{const r=Sr,n=Sr,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,m=new Headers(h?.[p(268)]||{});Object.entries(a).forEach(([y,w])=>{m.set(y,w)});const v={...h};return v.headers=m,o[f(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},x0=(e,t=Sn[Sr(299)]())=>{const r=Us,n=Sr,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},Zu=async(e,t,r)=>{const n=Sr,o=Sr,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,ur)){const l=await t();return await a[n(257)](l),await Zu(e,t,r)}else throw i}},E0=(e,t)=>{const r=Us,n=Us,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 rl(){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 rl=function(){return e},rl()}const v6=async e=>{const t=Us,r=Sr,n={GKDjq:function(x,j,O){return x(j,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(x){return x()},kdowC:function(x,j,O,U){return x(j,O,U)},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,m=i||Sn[r(299)](),v=n[t(289)](I0,a,m);if(c){const x={...v.requestInit,...c};x[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=x}else f.requestInit=v[t(280)];if(u){const x={...v[t(270)],...u};f.eventSourceInit=x}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,g={};g.name=n[r(261)],g[t(288)]=n.mcbiU;const C={};C[t(251)]=_;const b=new Ms(g,C),k=()=>new Ls(new URL(s),f);let S=n[t(282)](k);if(l){const x=E0(l,h);S=await n[t(263)](Zu,b,x,k)}else await b.connect(S);zu(b,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=S,I.sessionId=S[r(286)],I},_6=async e=>{const t=Us,r=Sr,n={wfHUn:function(x,j,O){return x(j,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(x){return x()},PdsSn:function(x,j,O,U){return x(j,O,U)}},{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,m=i||Sn.randomUUID(),v=n[r(272)](x0,a,m);if(c){const x={...v[t(280)],...c};x.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=x}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,g={};g.name=n[t(262)],g.version=n.omKPe;const C={};C.capabilities=_;const b=new Ms(g,C),k=()=>new js(new URL(s),f);let S=n.rSiEq(k);if(l){const x=n[t(272)](E0,l,h);S=await n[t(296)](Zu,b,x,k)}else await b[t(260)](S);n.PdsSn(zu,b,o,S);const I={};return I.transport=S,I[r(286)]=S[r(286)],I},w6=async e=>{const t=Sr,r=Sr,n={eZwNI:function(w,_,g,C){return w(_,g,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 Ms(h,p),m=i||Sn[r(299)](),v=new C0(new URL(s+"?sessionId="+m+r(265)+a));await f.connect(v),n[t(259)](zu,f,o,v);const y={};return y.transport=v,y[r(286)]=m,y},In=Ir,zs=Ir;(function(e,t){const r=Ir,n=Ir,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())}})(nl,1297719+-42747*-22+-1289197);function Ir(e,t){const r=nl();return Ir=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Ir(e,t)}const b6=()=>Sn.randomBytes(-8746+-382*-23);class k6{constructor(t){const r=Ir,n=Ir,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(b6),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=Ir,c=Ir,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[In(191)](t,r){const n=In,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=Ir;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[In(206)]}get[zs(190)](){return this._clientMetadata}[In(213)](){return this[In(197)]}[zs(218)](){return this[zs(200)]}[In(194)](t){this._clientInformation=t}tokens(){return this[zs(210)]}saveTokens(t){const r=zs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[In(212)](){const t=In,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function nl(){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 nl=function(){return e},nl()}(function(e,t){for(var r=sl,n=sl,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())}})(ol,262*-2438+1346066*-1+2*1373311);function ol(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return ol=function(){return e},ol()}function sl(e,t){var r=ol();return sl=function(n,o){n=n-287;var s=r[n];return s},sl(e,t)}class T6{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 C6 extends r0{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Li.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 l0,this.setRequestHandler(km,n=>this._oninitialize(n)),this.setNotificationHandler(Rc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ji,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=Li.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new T6(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=o0(this._capabilities,t)}setRequestHandler(t,r){const o=Co(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(wr(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=br(qi,l);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new le(de.InvalidParams,`Invalid tools/call request: ${m}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const m=br(wo,p);if(!m.success){const v=m.error instanceof Error?m.error.message:String(m.error);throw new le(de.InvalidParams,`Invalid task creation result: ${v}`)}return m.data}const f=br(ko,p);if(!f.success){const m=f.error instanceof Error?f.error.message:String(f.error);throw new le(de.InvalidParams,`Invalid tools/call result: ${m}`)}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){u0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&c0(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:gm.includes(r)?r:ks,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"},kn)}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},eu,r):this.request({method:"sampling/createMessage",params:t},Ui,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},Rs,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},Rs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new le(de.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof le?a:new le(de.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return s}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},nu,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 Fu=Symbol.for("mcp.completable");function S6(e,t){return Object.defineProperty(e,Fu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function $0(e){return!!e&&typeof e=="object"&&Fu in e}function I6(e){return e[Fu]?.complete}var R0;(function(e){e.Completable="McpCompletable"})(R0||(R0={}));const P0=1e6,Vu=1e6,M0=1e4,x6=1e6;class on{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){on.validateLength(t,P0,"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>M0)throw new Error(`Template contains too many expressions (max ${M0})`);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)on.validateLength(p,Vu,"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 on.validateLength(t,Vu,"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)on.validateLength(s,Vu,"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){on.validateLength(t,P0,"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+="$",on.validateLength(r,x6,"Generated regex pattern");const o=new RegExp(r),s=t.match(o);if(!s)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=s[i+1],h=l.replace("*","");c&&u.includes(",")?a[h]=u.split(","):a[h]=u}return a}}const E6=/^[A-Za-z0-9._-]{1,128}$/;function $6(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!E6.test(e)){const r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function R6(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function O0(e){const t=$6(e);return R6(e,t.warnings),t.isValid}class P6{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 N0{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 C6(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new P6(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(Yc)),this.server.assertCanSetRequestHandler(xn(qi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Yc,()=>({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=Ps(r.inputSchema);return o?Xm(o,{strictUnions:!0,pipeStrategy:"input"}):O6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=Ps(r.outputSchema);o&&(n.outputSchema=Xm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(qi,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new le(de.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if((s==="required"||s==="optional")&&!a)throw new le(de.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new le(de.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof le&&n.code===de.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const s=Ps(t.inputSchema)??t.inputSchema,a=await ou(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=su(i);throw new le(de.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new le(de.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=Ps(t.outputSchema),s=await ou(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=su(a);throw new le(de.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,a))}else{const i=o;return await Promise.resolve(i.createTask(a))}}if(t.inputSchema){const a=o;return await Promise.resolve(a(r,n))}else{const a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,a={...n,taskStore:n.taskStore},i=o?await Promise.resolve(s.createTask(o,a)):await Promise.resolve(s.createTask(a)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const h=await n.taskStore.getTask(l);if(!h)throw new le(de.InternalError,`Task ${l} not found during polling`);c=h}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(xn(ru)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ru,async t=>{switch(t.params.ref.type){case"ref/prompt":return hC(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return mC(t),this.handleResourceCompletion(t,t.params.ref);default:throw new le(de.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new le(de.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Zs;const s=Co(n.argsSchema)?.[t.params.argument.name];if(!$0(s))return Zs;const a=I6(s);if(!a)return Zs;const i=await a(t.params.argument.value,t.params.context);return L0(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 Zs;throw new le(de.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Zs;const s=await o(t.params.argument.value,t.params.context);return L0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(Ai)),this.server.assertCanSetRequestHandler(xn(Uc)),this.server.assertCanSetRequestHandler(xn(Zc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ai,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(Uc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Zc,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new le(de.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(n.toString());if(a)return s.readCallback(n,a,r)}throw new le(de.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(Vc)),this.server.assertCanSetRequestHandler(xn(Hc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Vc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?A6(r.argsSchema):void 0}))})),this.server.setRequestHandler(Hc,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new le(de.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new le(de.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=Ps(n.argsSchema),s=await ou(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=su(l);throw new le(de.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const a=s.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){const a={name:t,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(t,r,n,o,s){const a={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,n,o,s){const a={title:r,description:n,argsSchema:o===void 0?void 0:To(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=To(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 _r?l._def?.innerType:l;return $0(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){O0(t);const u={title:r,description:n,inputSchema:q0(o),outputSchema:q0(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"&&O0(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=To(h.paramsSchema)),typeof h.outputSchema<"u"&&(u.outputSchema=To(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];Hu(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Hu(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 M6{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new on(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const O6={type:"object",properties:{}};function A0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function N6(e){return"_def"in e||"_zod"in e||A0(e)}function Hu(e){return typeof e!="object"||e===null||N6(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(A0)}function q0(e){if(e)return Hu(e)?To(e):e}function A6(e){const t=Co(e);return t?Object.entries(t).map(([r,n])=>{const o=wC(n),s=bC(n);return{name:r,description:o,required:!s}}):[]}function xn(e){const r=Co(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Fm(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function L0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Zs={completion:{values:[],hasMore:!1}};function q6(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class Fs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Fs,r=new Fs;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 L6{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 N0(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(ji,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 Du(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(Pm,t)}onUnsubscribe(t){this.server.server.setRequestHandler(Mm,t)}onSetLogLevel(t){this.server.server.setRequestHandler(ji,t)}onListResources(t){this.server.server.setRequestHandler(Ai,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(zm,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const j6=(e,t)=>new Du(e,t),D6=()=>o6(),U6=e=>e instanceof Du,z6=e=>e instanceof N0;class j0{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ms(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:m}=s==="sse"?await v6(u):s==="socket"?await w6(u):await _6(u);f.onerror=async v=>{i?.(v)},h={transport:f,sessionId:m}})(),h}const l=new URL(r);let c;if(s==="channel"&&(c=new ju(r),await this.client.connect(c)),s==="sse"){const u=I0(n,o);c=new Ls(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=x0(n,o);c=new js(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,ko,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(tu,t)}onCreateMessage(t){this.client.setRequestHandler(Xc,t)}onListRoots(t){this.client.setRequestHandler(Um,t)}onToolListChanged(t){this.client.setNotificationHandler(Qc,t)}onPromptListChanged(t){this.client.setNotificationHandler(Kc,t)}onResourceListChanged(t){this.client.setNotificationHandler(Fc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Om,t)}onLoggingMessage(t){this.client.setNotificationHandler(jm,t)}async onPagehide(t){t.persisted||(D0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const Z6=(e,t)=>new Ls(e,t),F6=(e,t)=>new js(e,t),V6=(e,t)=>new ju(e,t),H6=e=>e instanceof Ls,D0=e=>e instanceof js,B6=e=>e instanceof ju,J6=e=>e instanceof Ms,Oo=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},U0=(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)},Bu=(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})},Ju=(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 z0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Ju("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=en.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];Bu("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 Gu=()=>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 G6{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||Gu(),this._messageListener1=U0("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=U0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=en.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Oo("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】 已关闭,无法发送消息"),Oo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&Oo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{Oo("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 W6{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||Gu(),this.tabId=r,Ju("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】 已关闭,无法重新启动");Ju("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=en.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&Oo("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),Bu("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&t.result?.content&&Oo("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,Bu("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 No={},Wu,Z0;function K6(){return Z0||(Z0=1,Wu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Wu}var Ku={},En={},F0;function Wn(){if(F0)return En;F0=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 En.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},En.getSymbolTotalCodewords=function(n){return t[n]},En.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},En.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},En.isKanjiModeEnabled=function(){return typeof e<"u"},En.toSJIS=function(n){return e(n)},En}var Yu={},V0;function Qu(){return V0||(V0=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}}})(Yu)),Yu}var Xu,H0;function Y6(){if(H0)return Xu;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++}},Xu=e,Xu}var ed,B0;function Q6(){if(B0)return ed;B0=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]},ed=e,ed}var td={},J0;function X6(){return J0||(J0=1,(function(e){const t=Wn().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}})(td)),td}var rd={},G0;function e5(){if(G0)return rd;G0=1;const e=Wn().getSymbolSize,t=7;return rd.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},rd}var nd={},W0;function t5(){return W0||(W0=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}})(nd)),nd}var al={},K0;function Y0(){if(K0)return al;K0=1;const e=Qu(),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 al.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}},al.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}},al}var od={},Vs={},Q0;function r5(){if(Q0)return Vs;Q0=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]})(),Vs.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Vs.exp=function(n){return e[n]},Vs.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Vs}var X0;function n5(){return X0||(X0=1,(function(e){const t=r5();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}})(od)),od}var sd,e2;function o5(){if(e2)return sd;e2=1;const e=n5();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},sd=t,sd}var ad={},id={},ld={},t2;function r2(){return t2||(t2=1,ld.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),ld}var Dr={},n2;function o2(){if(n2)return Dr;n2=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
|
+
]))+`;Dr.KANJI=new RegExp(r,"g"),Dr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Dr.BYTE=new RegExp(n,"g"),Dr.NUMERIC=new RegExp(e,"g"),Dr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Dr.testKanji=function(l){return o.test(l)},Dr.testNumeric=function(l){return s.test(l)},Dr.testAlphanumeric=function(l){return a.test(l)},Dr}var s2;function Kn(){return s2||(s2=1,(function(e){const t=r2(),r=o2();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}}})(id)),id}var a2;function s5(){return a2||(a2=1,(function(e){const t=Wn(),r=Y0(),n=Qu(),o=Kn(),s=r2(),a=7973,i=t.getBCHDigit(a);function l(p,f,m){for(let v=1;v<=40;v++)if(f<=e.getCapacity(v,m,p))return v}function c(p,f){return o.getCharCountIndicator(p,f)+4}function u(p,f){let m=0;return p.forEach(function(v){const y=c(v.mode,f);m+=y+v.getBitsLength()}),m}function h(p,f){for(let m=1;m<=40;m++)if(u(p,m)<=e.getCapacity(m,f,o.MIXED))return m}e.from=function(f,m){return s.isValid(f)?parseInt(f,10):m},e.getCapacity=function(f,m,v){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const y=t.getSymbolTotalCodewords(f),w=r.getTotalCodewordsCount(f,m),_=(y-w)*8;if(v===o.MIXED)return _;const g=_-c(v,f);switch(v){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(f,m){let v;const y=n.from(m,n.M);if(Array.isArray(f)){if(f.length>1)return h(f,y);if(f.length===0)return 1;v=f[0]}else v=f;return l(v.mode,v.getLength(),y)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let m=f<<12;for(;t.getBCHDigit(m)-i>=0;)m^=a<<t.getBCHDigit(m)-i;return f<<12|m}})(ad)),ad}var cd={},i2;function a5(){if(i2)return cd;i2=1;const e=Wn(),t=1335,r=21522,n=e.getBCHDigit(t);return cd.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},cd}var ud={},dd,l2;function i5(){if(l2)return dd;l2=1;const e=Kn();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))},dd=t,dd}var pd,c2;function l5(){if(c2)return pd;c2=1;const e=Kn(),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)},pd=r,pd}var fd,u2;function c5(){if(u2)return fd;u2=1;const e=Kn();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)},fd=t,fd}var hd,d2;function u5(){if(d2)return hd;d2=1;const e=Kn(),t=Wn();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)}},hd=r,hd}var md={exports:{}},p2;function d5(){return p2||(p2=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,m,v,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],m=h+f,v=a[u],y=typeof a[u]>"u",(y||v>m)&&(a[u]=m,i.push(u,m),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})(md)),md.exports}var f2;function p5(){return f2||(f2=1,(function(e){const t=Kn(),r=i5(),n=l5(),o=c5(),s=u5(),a=o2(),i=Wn(),l=d5();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,_,g){const C=[];let b;for(;(b=w.exec(g))!==null;)C.push({data:b[0],index:b.index,mode:_,length:b[0].length});return C}function h(w){const _=u(a.NUMERIC,t.NUMERIC,w),g=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let C,b;return i.isKanjiModeEnabled()?(C=u(a.BYTE,t.BYTE,w),b=u(a.KANJI,t.KANJI,w)):(C=u(a.BYTE_KANJI,t.BYTE,w),b=[]),_.concat(g,C,b).sort(function(S,I){return S.index-I.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function p(w,_){switch(_){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(_,g){const C=_.length-1>=0?_[_.length-1]:null;return C&&C.mode===g.mode?(_[_.length-1].data+=g.data,_):(_.push(g),_)},[])}function m(w){const _=[];for(let g=0;g<w.length;g++){const C=w[g];switch(C.mode){case t.NUMERIC:_.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:_.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:_.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:_.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return _}function v(w,_){const g={},C={start:{}};let b=["start"];for(let k=0;k<w.length;k++){const S=w[k],I=[];for(let x=0;x<S.length;x++){const j=S[x],O=""+k+x;I.push(O),g[O]={node:j,lastCount:0},C[O]={};for(let U=0;U<b.length;U++){const A=b[U];g[A]&&g[A].node.mode===j.mode?(C[A][O]=p(g[A].lastCount+j.length,j.mode)-p(g[A].lastCount,j.mode),g[A].lastCount+=j.length):(g[A]&&(g[A].lastCount=j.length),C[A][O]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,_))}}b=I}for(let k=0;k<b.length;k++)C[b[k]].end=0;return{map:C,table:g}}function y(w,_){let g;const C=t.getBestModeForData(w);if(g=t.from(_,C),g!==t.BYTE&&g.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(g)+`.
|
|
46
|
+
Suggested mode is: `+t.toString(C));switch(g===t.KANJI&&!i.isKanjiModeEnabled()&&(g=t.BYTE),g){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(_){return _.reduce(function(g,C){return typeof C=="string"?g.push(y(C,null)):C.data&&g.push(y(C.data,C.mode)),g},[])},e.fromString=function(_,g){const C=h(_,i.isKanjiModeEnabled()),b=m(C),k=v(b,g),S=l.find_path(k.map,"start","end"),I=[];for(let x=1;x<S.length-1;x++)I.push(k.table[S[x]].node);return e.fromArray(f(I))},e.rawSplit=function(_){return e.fromArray(h(_,i.isKanjiModeEnabled()))}})(ud)),ud}var h2;function f5(){if(h2)return Ku;h2=1;const e=Wn(),t=Qu(),r=Y6(),n=Q6(),o=X6(),s=e5(),a=t5(),i=Y0(),l=o5(),c=s5(),u=a5(),h=Kn(),p=p5();function f(k,S){const I=k.size,x=s.getPositions(S);for(let j=0;j<x.length;j++){const O=x[j][0],U=x[j][1];for(let A=-1;A<=7;A++)if(!(O+A<=-1||I<=O+A))for(let N=-1;N<=7;N++)U+N<=-1||I<=U+N||(A>=0&&A<=6&&(N===0||N===6)||N>=0&&N<=6&&(A===0||A===6)||A>=2&&A<=4&&N>=2&&N<=4?k.set(O+A,U+N,!0,!0):k.set(O+A,U+N,!1,!0))}}function m(k){const S=k.size;for(let I=8;I<S-8;I++){const x=I%2===0;k.set(I,6,x,!0),k.set(6,I,x,!0)}}function v(k,S){const I=o.getPositions(S);for(let x=0;x<I.length;x++){const j=I[x][0],O=I[x][1];for(let U=-2;U<=2;U++)for(let A=-2;A<=2;A++)U===-2||U===2||A===-2||A===2||U===0&&A===0?k.set(j+U,O+A,!0,!0):k.set(j+U,O+A,!1,!0)}}function y(k,S){const I=k.size,x=c.getEncodedBits(S);let j,O,U;for(let A=0;A<18;A++)j=Math.floor(A/3),O=A%3+I-8-3,U=(x>>A&1)===1,k.set(j,O,U,!0),k.set(O,j,U,!0)}function w(k,S,I){const x=k.size,j=u.getEncodedBits(S,I);let O,U;for(O=0;O<15;O++)U=(j>>O&1)===1,O<6?k.set(O,8,U,!0):O<8?k.set(O+1,8,U,!0):k.set(x-15+O,8,U,!0),O<8?k.set(8,x-O-1,U,!0):O<9?k.set(8,15-O-1+1,U,!0):k.set(8,15-O-1,U,!0);k.set(x-8,8,1,!0)}function _(k,S){const I=k.size;let x=-1,j=I-1,O=7,U=0;for(let A=I-1;A>0;A-=2)for(A===6&&A--;;){for(let N=0;N<2;N++)if(!k.isReserved(j,A-N)){let G=!1;U<S.length&&(G=(S[U]>>>O&1)===1),k.set(j,A-N,G),O--,O===-1&&(U++,O=7)}if(j+=x,j<0||I<=j){j-=x,x=-x;break}}}function g(k,S,I){const x=new r;I.forEach(function(N){x.put(N.mode.bit,4),x.put(N.getLength(),h.getCharCountIndicator(N.mode,k)),N.write(x)});const j=e.getSymbolTotalCodewords(k),O=i.getTotalCodewordsCount(k,S),U=(j-O)*8;for(x.getLengthInBits()+4<=U&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const A=(U-x.getLengthInBits())/8;for(let N=0;N<A;N++)x.put(N%2?17:236,8);return C(x,k,S)}function C(k,S,I){const x=e.getSymbolTotalCodewords(S),j=i.getTotalCodewordsCount(S,I),O=x-j,U=i.getBlocksCount(S,I),A=x%U,N=U-A,G=Math.floor(x/U),X=Math.floor(O/U),Q=X+1,K=G-X,he=new l(K);let V=0;const P=new Array(U),H=new Array(U);let Z=0;const E=new Uint8Array(k.buffer);for(let se=0;se<U;se++){const Se=se<N?X:Q;P[se]=E.slice(V,V+Se),H[se]=he.encode(P[se]),V+=Se,Z=Math.max(Z,Se)}const M=new Uint8Array(x);let L=0,W,te;for(W=0;W<Z;W++)for(te=0;te<U;te++)W<P[te].length&&(M[L++]=P[te][W]);for(W=0;W<K;W++)for(te=0;te<U;te++)M[L++]=H[te][W];return M}function b(k,S,I,x){let j;if(Array.isArray(k))j=p.fromArray(k);else if(typeof k=="string"){let G=S;if(!G){const X=p.rawSplit(k);G=c.getBestVersionForData(X,I)}j=p.fromString(k,G||40)}else throw new Error("Invalid data");const O=c.getBestVersionForData(j,I);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=O;else if(S<O)throw new Error(`
|
|
47
47
|
The chosen QR Code version cannot contain this amount of data.
|
|
48
48
|
Minimum version required to store current data is: `+O+`.
|
|
49
|
-
`);const U=
|
|
50
|
-
`;return typeof i=="function"&&i(null,y),y},
|
|
49
|
+
`);const U=g(S,I,j),A=e.getSymbolSize(S),N=new n(A);return f(N,S),m(N),v(N,S),w(N,I,0),S>=7&&y(N,S),_(N,U),isNaN(x)&&(x=a.getBestMask(N,w.bind(null,N,I))),a.applyMask(x,N),w(N,I,x),{modules:N,version:S,errorCorrectionLevel:I,maskPattern:x,segments:j}}return Ku.create=function(S,I){if(typeof S>"u"||S==="")throw new Error("No input text");let x=t.M,j,O;return typeof I<"u"&&(x=t.from(I.errorCorrectionLevel,t.M),j=c.from(I.version),O=a.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),b(S,j,x,O)},Ku}var gd={},yd={},m2;function g2(){return m2||(m2=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 m=(p*c+f)*4,v=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);v=h[i[y*a+w]?1:0]}n[m++]=v.r,n[m++]=v.g,n[m++]=v.b,n[m]=v.a}}})(yd)),yd}var y2;function h5(){return y2||(y2=1,(function(e){const t=g2();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)}})(gd)),gd}var vd={},v2;function m5(){if(v2)return vd;v2=1;const e=g2();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 vd.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)+'"/>',m='viewBox="0 0 '+h+" "+h+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+m+' shape-rendering="crispEdges">'+p+f+`</svg>
|
|
50
|
+
`;return typeof i=="function"&&i(null,y),y},vd}var _2;function g5(){if(_2)return No;_2=1;const e=K6(),t=f5(),r=h5(),n=m5();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,m){try{const v=t.create(i,l);f(s(v,a,l))}catch(v){m(v)}})}try{const f=t.create(i,l);c(null,s(f,a,l))}catch(f){c(f)}}return No.create=t.create,No.toCanvas=o.bind(null,r.render),No.toDataURL=o.bind(null,r.renderToDataURL),No.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),No}var y5=g5();const w2=An(y5);class b2{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 w2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return w2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const v5={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class _5{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={...v5,...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
|
|
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 k2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(k2))return;const e=document.createElement("style");e.id=k2,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: `+O+`.
|
|
|
97
97
|
transform: translateY(-50%);
|
|
98
98
|
border-right-color: rgba(0,0,0,.75);
|
|
99
99
|
}
|
|
100
|
-
`,document.head.appendChild(e)})();const hI="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",mI="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",gI="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",yI="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",vI="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",_I="https://chat.opentiny.design",wI="https://ai.opentiny.design/next-remoter",bI="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",y2=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:yI},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:hI},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:gI},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:mI}]};class kI{constructor(t){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 fI(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||wI,remoteUrl:t.remoteUrl||_I,logoUrl:t.logoUrl||bI},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 this.options.sessionId?t?y2(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}):y2(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 w5="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",b5="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",k5="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",T5="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",C5="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",S5="https://chat.opentiny.design",I5="https://ai.opentiny.design/next-remoter",x5="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",T2=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:T5},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:w5},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:k5},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:b5}]};class E5{constructor(t){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 _5(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||I5,remoteUrl:t.remoteUrl||S5,logoUrl:t.logoUrl||x5},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 this.options.sessionId?t?T2(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}):T2(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: `+O+`.
|
|
|
112
112
|
<div>
|
|
113
113
|
${r.showCopyIcon?`
|
|
114
114
|
<div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
|
|
115
|
-
<img src="${
|
|
115
|
+
<img src="${C5}"/>
|
|
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.options.sessionId&&this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.options.sessionId&&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(){if(!this.options.sessionId)return;const r=await new
|
|
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.options.sessionId&&this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.options.sessionId&&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(){if(!this.options.sessionId)return;const r=await new b2((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: `+O+`.
|
|
|
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
|
|
549
|
-
Error message: ${
|
|
550
|
-
Error message: ${Kn(r)}`,cause:r}),this[rg]=!0,this.value=t,this.context=n}static isInstance(t){return _e.hasMarker(t,tg)}static wrap({value:t,cause:r,context:n}){var o,s,a;return kp.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 kp({value:t,cause:r,context:n})}},og="AI_UnsupportedFunctionalityError",sg=`vercel.ai.error.${og}`,qI=Symbol.for(sg),ag,ig,Ur=class extends(ig=_e,ag=qI,ig){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:og,message:r}),this[ag]=!0,this.functionality=t}static isInstance(t){return _e.hasMarker(t,sg)}};function qt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function LI({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const a of e)if(a.type==="provider"){const i=(n=r?.(a))!=null?n:a.id in t?t[a.id]:void 0;if(i==null)continue;o[a.name]=i,s[i]=a.name}return{toProviderToolName:a=>{var i;return(i=o[a])!=null?i:a},toCustomToolName:a=>{var i;return(i=s[a])!=null?i:a}}}async function jI(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(lg());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(lg())};r?.addEventListener("abort",i)})}function lg(){return new DOMException("Delay was aborted","AbortError")}var Fs=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 No(e){return Object.fromEntries([...e.headers])}var{btoa:DI,atob:UI}=globalThis;function Ao(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=UI(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function qo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return DI(t)}function Lo(e){return e instanceof Uint8Array?qo(e):e}function zI(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 cg="AI_DownloadError",ug=`vercel.ai.error.${cg}`,ZI=Symbol.for(ug),dg,pg,Kt=class extends(pg=_e,dg=ZI,pg){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:cg,message:o,cause:n}),this[dg]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return _e.hasMarker(e,ug)}},fd=2*1024*1024*1024;async function fg({response:e,url:t,maxBytes:r=fd}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Kt({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 Kt({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}function hg(e){let t;try{t=new URL(e)}catch{throw new Kt({url:e,message:`Invalid URL: ${e}`})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Kt({url:e,message:`URL scheme must be http or https, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Kt({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Kt({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(FI(n))throw new Kt({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(mg(r)){if(hd(r))throw new Kt({url:e,message:`URL with IP address ${r} is not allowed`});return}}function mg(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function hd(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function FI(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(mg(r))return hd(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const a=o>>8&255,i=o&255,l=s>>8&255,c=s&255;return hd(`${a}.${i}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function gg(e,t){var r,n;hg(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Kt({url:e,statusCode:o.status,statusText:o.statusText});const s=await fg({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:fd}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw Kt.isInstance(o)?o:new Kt({url:e,cause:o})}}var Vs=({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 O2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Zt=Vs();function md(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Xn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var VI=["fetch failed","failed to fetch"],HI=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function BI(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&HI.includes(t))}function yg({error:e,url:t,requestBodyValues:r}){if(Xn(e))return e;if(e instanceof TypeError&&VI.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ct({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return BI(e)?new ct({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Hs(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 JI(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(JI(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var vg="4.0.19",GI=()=>globalThis.fetch,_g=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=GI()})=>{try{const a=await s(e,{method:"GET",headers:xn(t,`ai-sdk/provider-utils/${vg}`,Hs()),signal:o}),i=No(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw Xn(c)||ct.isInstance(c)?c:new ct({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&&(Xn(l)||ct.isInstance(l))?l:new ct({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw yg({error:a,url:e,requestBodyValues:{}})}};function wg(e){return e!=null}function WI({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 KI({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new sl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new sl({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 sl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new sl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function jo({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 YI(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 QI=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,XI=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function bg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||QI.test(e)===!1&&XI.test(e)===!1?t:e5(t)}function e5(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")&&n.constructor!==null&&typeof n.constructor=="object"&&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 gd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return bg(e)}try{return bg(e)}finally{Error.stackTraceLimit=t}}function yd(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]=eo(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(eo):eo(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(eo)),e.allOf!=null&&(e.allOf=e.allOf.map(eo)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(eo));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=eo(t[r]);return e}function eo(e){return typeof e=="boolean"?e:yd(e)}var t5=Symbol("Let zodToJsonSchema decide on which parser to use"),kg={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"},r5=e=>typeof e=="string"?{...kg,name:e}:{...kg,...e};function or(){return{}}function n5(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=Ge(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 o5(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 s5(){return{type:"boolean"}}function Tg(e,t){return Ge(e.type._def,t)}var a5=(e,t)=>Ge(e.innerType._def,t);function Cg(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Cg(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 i5(e)}}var i5=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 l5(e,t){return{...Ge(e.innerType._def,t),default:e.defaultValue()}}function c5(e,t){return t.effectStrategy==="input"?Ge(e.schema._def,t):or()}function u5(e){return{type:"string",enum:Array.from(e.values)}}var d5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function p5(e,t){const r=[Ge(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ge(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(d5(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 f5(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 vd=void 0,Er={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:()=>(vd===void 0&&(vd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vd),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 Sg(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":xr(r,"email",n.message,t);break;case"format:idn-email":xr(r,"idn-email",n.message,t);break;case"pattern:zod":Ft(r,Er.email,n.message,t);break}break;case"url":xr(r,"uri",n.message,t);break;case"uuid":xr(r,"uuid",n.message,t);break;case"regex":Ft(r,n.regex,n.message,t);break;case"cuid":Ft(r,Er.cuid,n.message,t);break;case"cuid2":Ft(r,Er.cuid2,n.message,t);break;case"startsWith":Ft(r,RegExp(`^${_d(n.value,t)}`),n.message,t);break;case"endsWith":Ft(r,RegExp(`${_d(n.value,t)}$`),n.message,t);break;case"datetime":xr(r,"date-time",n.message,t);break;case"date":xr(r,"date",n.message,t);break;case"time":xr(r,"time",n.message,t);break;case"duration":xr(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":{Ft(r,RegExp(_d(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&xr(r,"ipv4",n.message,t),n.version!=="v4"&&xr(r,"ipv6",n.message,t);break}case"base64url":Ft(r,Er.base64url,n.message,t);break;case"jwt":Ft(r,Er.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ft(r,Er.ipv4Cidr,n.message,t),n.version!=="v4"&&Ft(r,Er.ipv6Cidr,n.message,t);break}case"emoji":Ft(r,Er.emoji(),n.message,t);break;case"ulid":{Ft(r,Er.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{xr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Ft(r,Er.base64,n.message,t);break}}break}case"nanoid":Ft(r,Er.nanoid,n.message,t)}return r}function _d(e,t){return t.patternStrategy==="escape"?m5(e):e}var h5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function m5(e){let t="";for(let r=0;r<e.length;r++)h5.has(e[r])||(t+="\\"),t+=e[r];return t}function xr(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 Ft(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:Ig(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Ig(t,n)}function Ig(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)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const $5=(e={})=>new E5(e);var C2="vercel.ai.error",R5=Symbol.for(C2),S2,I2,_e=class fw extends(I2=Error,S2=R5,I2){constructor({name:t,message:r,cause:n}){super(r),this[S2]=!0,this.name=t,this.cause=n}static isInstance(t){return fw.hasMarker(t,C2)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},x2="AI_APICallError",E2=`vercel.ai.error.${x2}`,P5=Symbol.for(E2),$2,R2,ct=class extends(R2=_e,$2=P5,R2){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:x2,message:t,cause:i}),this[$2]=!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 _e.hasMarker(t,E2)}},P2="AI_EmptyResponseBodyError",M2=`vercel.ai.error.${P2}`,M5=Symbol.for(M2),O2,N2,O5=class extends(N2=_e,O2=M5,N2){constructor({message:t="Empty response body"}={}){super({name:P2,message:t}),this[O2]=!0}static isInstance(t){return _e.hasMarker(t,M2)}};function Yn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var A2="AI_InvalidArgumentError",q2=`vercel.ai.error.${A2}`,N5=Symbol.for(q2),L2,j2,D2=class extends(j2=_e,L2=N5,j2){constructor({message:t,cause:r,argument:n}){super({name:A2,message:t,cause:r}),this[L2]=!0,this.argument=n}static isInstance(t){return _e.hasMarker(t,q2)}},U2="AI_InvalidPromptError",z2=`vercel.ai.error.${U2}`,A5=Symbol.for(z2),Z2,F2,Qn=class extends(F2=_e,Z2=A5,F2){constructor({prompt:e,message:t,cause:r}){super({name:U2,message:`Invalid prompt: ${t}`,cause:r}),this[Z2]=!0,this.prompt=e}static isInstance(e){return _e.hasMarker(e,z2)}},V2="AI_InvalidResponseDataError",H2=`vercel.ai.error.${V2}`,q5=Symbol.for(H2),B2,J2,_d=class extends(J2=_e,B2=q5,J2){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:V2,message:r}),this[B2]=!0,this.data=t}static isInstance(t){return _e.hasMarker(t,H2)}},G2="AI_JSONParseError",W2=`vercel.ai.error.${G2}`,L5=Symbol.for(W2),K2,Y2,il=class extends(Y2=_e,K2=L5,Y2){constructor({text:t,cause:r}){super({name:G2,message:`JSON parsing failed: Text: ${t}.
|
|
549
|
+
Error message: ${Yn(r)}`,cause:r}),this[K2]=!0,this.text=t}static isInstance(t){return _e.hasMarker(t,W2)}},Q2="AI_LoadAPIKeyError",X2=`vercel.ai.error.${Q2}`,j5=Symbol.for(X2),eg,tg,ll=class extends(tg=_e,eg=j5,tg){constructor({message:t}){super({name:Q2,message:t}),this[eg]=!0}static isInstance(t){return _e.hasMarker(t,X2)}},rg="AI_TooManyEmbeddingValuesForCallError",ng=`vercel.ai.error.${rg}`,D5=Symbol.for(ng),og,sg,U5=class extends(sg=_e,og=D5,sg){constructor(e){super({name:rg,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[og]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return _e.hasMarker(e,ng)}},ag="AI_TypeValidationError",ig=`vercel.ai.error.${ag}`,z5=Symbol.for(ig),lg,cg,Xn=class Ep extends(cg=_e,lg=z5,cg){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:ag,message:`${o}: Value: ${JSON.stringify(t)}.
|
|
550
|
+
Error message: ${Yn(r)}`,cause:r}),this[lg]=!0,this.value=t,this.context=n}static isInstance(t){return _e.hasMarker(t,ig)}static wrap({value:t,cause:r,context:n}){var o,s,a;return Ep.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 Ep({value:t,cause:r,context:n})}},ug="AI_UnsupportedFunctionalityError",dg=`vercel.ai.error.${ug}`,Z5=Symbol.for(dg),pg,fg,Ur=class extends(fg=_e,pg=Z5,fg){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:ug,message:r}),this[pg]=!0,this.functionality=t}static isInstance(t){return _e.hasMarker(t,dg)}};function qt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function F5({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const a of e)if(a.type==="provider"){const i=(n=r?.(a))!=null?n:a.id in t?t[a.id]:void 0;if(i==null)continue;o[a.name]=i,s[i]=a.name}return{toProviderToolName:a=>{var i;return(i=o[a])!=null?i:a},toCustomToolName:a=>{var i;return(i=s[a])!=null?i:a}}}async function V5(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(hg());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(hg())};r?.addEventListener("abort",i)})}function hg(){return new DOMException("Delay was aborted","AbortError")}var Hs=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 Ao(e){return Object.fromEntries([...e.headers])}var{btoa:H5,atob:B5}=globalThis;function qo(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=B5(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Lo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return H5(t)}function jo(e){return e instanceof Uint8Array?Lo(e):e}function J5(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 mg="AI_DownloadError",gg=`vercel.ai.error.${mg}`,G5=Symbol.for(gg),yg,vg,Kt=class extends(vg=_e,yg=G5,vg){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:mg,message:o,cause:n}),this[yg]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return _e.hasMarker(e,gg)}},wd=2*1024*1024*1024;async function _g({response:e,url:t,maxBytes:r=wd}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Kt({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 Kt({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}function wg(e){let t;try{t=new URL(e)}catch{throw new Kt({url:e,message:`Invalid URL: ${e}`})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Kt({url:e,message:`URL scheme must be http or https, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Kt({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Kt({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(W5(n))throw new Kt({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(bg(r)){if(bd(r))throw new Kt({url:e,message:`URL with IP address ${r} is not allowed`});return}}function bg(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function bd(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function W5(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(bg(r))return bd(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const a=o>>8&255,i=o&255,l=s>>8&255,c=s&255;return bd(`${a}.${i}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function kg(e,t){var r,n;wg(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Kt({url:e,statusCode:o.status,statusText:o.statusText});const s=await _g({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:wd}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw Kt.isInstance(o)?o:new Kt({url:e,cause:o})}}var Bs=({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 D2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Zt=Bs();function kd(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function eo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var K5=["fetch failed","failed to fetch"],Y5=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function Q5(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&Y5.includes(t))}function Tg({error:e,url:t,requestBodyValues:r}){if(eo(e))return e;if(e instanceof TypeError&&K5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ct({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return Q5(e)?new ct({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Js(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 X5(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 $n(e,...t){const r=new Headers(X5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Cg="4.0.19",eI=()=>globalThis.fetch,Sg=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=eI()})=>{try{const a=await s(e,{method:"GET",headers:$n(t,`ai-sdk/provider-utils/${Cg}`,Js()),signal:o}),i=Ao(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw eo(c)||ct.isInstance(c)?c:new ct({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&&(eo(l)||ct.isInstance(l))?l:new ct({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Tg({error:a,url:e,requestBodyValues:{}})}};function Ig(e){return e!=null}function tI({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 rI({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ll({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ll({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 ll({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ll({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Do({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 nI(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 oI=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,sI=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function xg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||oI.test(e)===!1&&sI.test(e)===!1?t:aI(t)}function aI(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")&&n.constructor!==null&&typeof n.constructor=="object"&&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 Td(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return xg(e)}try{return xg(e)}finally{Error.stackTraceLimit=t}}function Cd(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]=to(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(to):to(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(to)),e.allOf!=null&&(e.allOf=e.allOf.map(to)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(to));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=to(t[r]);return e}function to(e){return typeof e=="boolean"?e:Cd(e)}var iI=Symbol("Let zodToJsonSchema decide on which parser to use"),Eg={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"},lI=e=>typeof e=="string"?{...Eg,name:e}:{...Eg,...e};function or(){return{}}function cI(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=Ge(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 uI(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 dI(){return{type:"boolean"}}function $g(e,t){return Ge(e.type._def,t)}var pI=(e,t)=>Ge(e.innerType._def,t);function Rg(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Rg(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 fI(e)}}var fI=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 hI(e,t){return{...Ge(e.innerType._def,t),default:e.defaultValue()}}function mI(e,t){return t.effectStrategy==="input"?Ge(e.schema._def,t):or()}function gI(e){return{type:"string",enum:Array.from(e.values)}}var yI=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function vI(e,t){const r=[Ge(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ge(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(yI(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 _I(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 Sd=void 0,xr={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:()=>(Sd===void 0&&(Sd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sd),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 Pg(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":Er(r,"email",n.message,t);break;case"format:idn-email":Er(r,"idn-email",n.message,t);break;case"pattern:zod":Ft(r,xr.email,n.message,t);break}break;case"url":Er(r,"uri",n.message,t);break;case"uuid":Er(r,"uuid",n.message,t);break;case"regex":Ft(r,n.regex,n.message,t);break;case"cuid":Ft(r,xr.cuid,n.message,t);break;case"cuid2":Ft(r,xr.cuid2,n.message,t);break;case"startsWith":Ft(r,RegExp(`^${Id(n.value,t)}`),n.message,t);break;case"endsWith":Ft(r,RegExp(`${Id(n.value,t)}$`),n.message,t);break;case"datetime":Er(r,"date-time",n.message,t);break;case"date":Er(r,"date",n.message,t);break;case"time":Er(r,"time",n.message,t);break;case"duration":Er(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":{Ft(r,RegExp(Id(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Er(r,"ipv4",n.message,t),n.version!=="v4"&&Er(r,"ipv6",n.message,t);break}case"base64url":Ft(r,xr.base64url,n.message,t);break;case"jwt":Ft(r,xr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ft(r,xr.ipv4Cidr,n.message,t),n.version!=="v4"&&Ft(r,xr.ipv6Cidr,n.message,t);break}case"emoji":Ft(r,xr.emoji(),n.message,t);break;case"ulid":{Ft(r,xr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Er(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Ft(r,xr.base64,n.message,t);break}}break}case"nanoid":Ft(r,xr.nanoid,n.message,t)}return r}function Id(e,t){return t.patternStrategy==="escape"?bI(e):e}var wI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function bI(e){let t="";for(let r=0;r<e.length;r++)wI.has(e[r])||(t+="\\"),t+=e[r];return t}function Er(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 Ft(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 Eg(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ge(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}=Sg(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}=Tg(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function g5(e,t){if(t.mapStrategy==="record")return Eg(e,t);const r=Ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||or(),n=Ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||or();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 v5(){return{not:or()}}function _5(){return{type:"null"}}var wd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function w5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in wd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=wd[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 b5(e,t)}var b5=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ge(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 k5(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[wd[e.innerType._def.typeName],"null"]};const r=Ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function T5(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 C5(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=I5(i),c=Ge(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=S5(e,t);return s!==void 0&&(r.additionalProperties=s),r}function S5(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ge(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 I5(e){try{return e.isOptional()}catch{return!0}}var E5=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ge(e.innerType._def,t);const n=Ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:or()},n]}:or()},x5=(e,t)=>{if(t.pipeStrategy==="input")return Ge(e.in._def,t);if(t.pipeStrategy==="output")return Ge(e.out._def,t);const r=Ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function $5(e,t){return Ge(e.type._def,t)}function R5(e,t){const n={type:"array",uniqueItems:!0,items:Ge(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 P5(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function M5(){return{not:or()}}function O5(){return or()}var N5=(e,t)=>Ge(e.innerType._def,t),A5=(e,t,r)=>{switch(t){case B.ZodString:return Sg(e,r);case B.ZodNumber:return T5(e);case B.ZodObject:return C5(e,r);case B.ZodBigInt:return o5(e);case B.ZodBoolean:return s5();case B.ZodDate:return Cg(e,r);case B.ZodUndefined:return M5();case B.ZodNull:return _5();case B.ZodArray:return n5(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return w5(e,r);case B.ZodIntersection:return p5(e,r);case B.ZodTuple:return P5(e,r);case B.ZodRecord:return Eg(e,r);case B.ZodLiteral:return f5(e);case B.ZodEnum:return u5(e);case B.ZodNativeEnum:return y5(e);case B.ZodNullable:return k5(e,r);case B.ZodOptional:return E5(e,r);case B.ZodMap:return g5(e,r);case B.ZodSet:return R5(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return $5(e,r);case B.ZodNaN:case B.ZodNever:return v5();case B.ZodEffects:return c5(e,r);case B.ZodAny:return or();case B.ZodUnknown:return O5();case B.ZodDefault:return l5(e,r);case B.ZodBranded:return Tg(e,r);case B.ZodReadonly:return N5(e,r);case B.ZodCatch:return a5(e,r);case B.ZodPipeline:return x5(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}},q5=(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 Ge(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!==t5)return l}if(o&&!r){const l=L5(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=A5(e,e.typeName,t),i=typeof a=="function"?Ge(a(),t):a;if(i&&j5(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var L5=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:q5(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`),or()):t.$refStrategy==="seen"?or():void 0}},j5=(e,t,r)=>(e.description&&(r.description=e.description),r),D5=e=>{const t=r5(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}]))}},U5=(e,t)=>{var r;const n=D5(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var p;return{...c,[u]:(p=Ge(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:or()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ge(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:or(),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},bd=Symbol.for("vercel.ai.schema");function be(e){let t;return()=>(t==null&&(t=e()),t)}function Do(e,{validate:t}={}){return{[bd]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function z5(e){return typeof e=="object"&&e!==null&&bd in e&&e[bd]===!0&&"jsonSchema"in e&&"validate"in e}function to(e){return e==null?Do({properties:{},additionalProperties:!1}):z5(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?we(e):Z5(e):e()}function Z5(e){return Do(()=>yd(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 Qn({value:t,cause:r.issues})}}})}function F5(e,t){var r;const n=(r=void 0)!=null?r:!1;return Do(()=>U5(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 V5(e,t){var r;const n=(r=void 0)!=null?r:!1;return Do(()=>yd(Hh(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 H5(e){return"_zod"in e}function we(e,t){return H5(e)?V5(e):F5(e)}async function St({value:e,schema:t,context:r}){const n=await dr({value:e,schema:t,context:r});if(!n.success)throw Qn.wrap({value:e,cause:n.error,context:r});return n.value}async function dr({value:e,schema:t,context:r}){const n=to(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:Qn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Qn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function B5({text:e,schema:t}){try{const r=gd(e);return t==null?r:St({value:r,schema:t})}catch(r){throw ol.isInstance(r)||Qn.isInstance(r)?r:new ol({text:e,cause:r})}}async function pr({text:e,schema:t}){try{const r=gd(e);return t==null?{success:!0,value:r,rawValue:r}:await dr({value:r,schema:t})}catch(r){return{success:!1,error:ol.isInstance(r)?r:new ol({text:e,cause:r}),rawValue:void 0}}}function xg(e){try{return gd(e),!0}catch{return!1}}function $g({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ro).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await pr({text:r,schema:t}))}}))}async function sn({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await dr({value:t[e],schema:r});if(!n.success)throw new O2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var J5=()=>globalThis.fetch,Yt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Pg({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Rg=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Pg({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Pg=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=J5()})=>{try{const i=await a(e,{method:"POST",headers:xn(t,`ai-sdk/provider-utils/${vg}`,Hs()),body:r.content,signal:s}),l=No(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Xn(u)||ct.isInstance(u)?u:new ct({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&&(Xn(c)||ct.isInstance(c))?c:new ct({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw yg({error:i,url:e,requestBodyValues:r.values})}};function FM(e){return e}function Mg(e){return{...e,type:"dynamic"}}function G5({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}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 Qt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var $n=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=No(n);if(a.trim()==="")return{responseHeaders:i,value:new ct({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await B5({text:a,schema:e});return{responseHeaders:i,value:new ct({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 ct({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},al=e=>async({response:t})=>{const r=No(t);if(t.body==null)throw new EI({});return{responseHeaders:r,value:$g({stream:t.body,schema:e})}},fr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await pr({text:o,schema:e}),a=No(t);if(!s.success)throw new ct({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}},W5=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=No(e);if(!e.body)throw new ct({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 ct({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 K5(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Y5({execute:e,input:t,options:r}){const n=e(t,r);if(K5(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 kd,Ng;function Q5(){if(Ng)return kd;Ng=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}),kd=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return kd}var Td,Ag;function X5(){if(Ag)return Td;Ag=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 v of r(p))!n.call(h,v)&&v!==f&&e(h,v,{get:()=>p[v],enumerable:!(g=t(p,v))||g.enumerable});return h},a=h=>s(e({},"__esModule",{value:!0}),h),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Td=a(i);var l=Q5();async function c(){return""}function u(){return""}return Td}var qg=X5(),eE="vercel.ai.gateway.error",Cd=Symbol.for(eE),Lg,jg,Vt=class lw extends(jg=Error,Lg=Cd,jg){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 lw.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Cd in t&&t[Cd]===!0}},Dg="GatewayAuthenticationError",tE=`vercel.ai.gateway.error.${Dg}`,Ug=Symbol.for(tE),zg,Zg,Sd=class cw extends(Zg=Vt,zg=Ug,Zg){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[zg]=!0,this.name=Dg,this.type="authentication_error"}static isInstance(t){return Vt.hasMarker(t)&&Ug 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 Og(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ge(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}=Pg(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}=$g(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function kI(e,t){if(t.mapStrategy==="record")return Og(e,t);const r=Ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||or(),n=Ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||or();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function TI(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 CI(){return{not:or()}}function SI(){return{type:"null"}}var xd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function II(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in xd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=xd[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 xI(e,t)}var xI=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ge(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function EI(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[xd[e.innerType._def.typeName],"null"]};const r=Ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function $I(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function RI(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=MI(i),c=Ge(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=PI(e,t);return s!==void 0&&(r.additionalProperties=s),r}function PI(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ge(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 MI(e){try{return e.isOptional()}catch{return!0}}var OI=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ge(e.innerType._def,t);const n=Ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:or()},n]}:or()},NI=(e,t)=>{if(t.pipeStrategy==="input")return Ge(e.in._def,t);if(t.pipeStrategy==="output")return Ge(e.out._def,t);const r=Ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function AI(e,t){return Ge(e.type._def,t)}function qI(e,t){const n={type:"array",uniqueItems:!0,items:Ge(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 LI(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function jI(){return{not:or()}}function DI(){return or()}var UI=(e,t)=>Ge(e.innerType._def,t),zI=(e,t,r)=>{switch(t){case B.ZodString:return Pg(e,r);case B.ZodNumber:return $I(e);case B.ZodObject:return RI(e,r);case B.ZodBigInt:return uI(e);case B.ZodBoolean:return dI();case B.ZodDate:return Rg(e,r);case B.ZodUndefined:return jI();case B.ZodNull:return SI();case B.ZodArray:return cI(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return II(e,r);case B.ZodIntersection:return vI(e,r);case B.ZodTuple:return LI(e,r);case B.ZodRecord:return Og(e,r);case B.ZodLiteral:return _I(e);case B.ZodEnum:return gI(e);case B.ZodNativeEnum:return TI(e);case B.ZodNullable:return EI(e,r);case B.ZodOptional:return OI(e,r);case B.ZodMap:return kI(e,r);case B.ZodSet:return qI(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return AI(e,r);case B.ZodNaN:case B.ZodNever:return CI();case B.ZodEffects:return mI(e,r);case B.ZodAny:return or();case B.ZodUnknown:return DI();case B.ZodDefault:return hI(e,r);case B.ZodBranded:return $g(e,r);case B.ZodReadonly:return UI(e,r);case B.ZodCatch:return pI(e,r);case B.ZodPipeline:return NI(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}},ZI=(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 Ge(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!==iI)return l}if(o&&!r){const l=FI(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=zI(e,e.typeName,t),i=typeof a=="function"?Ge(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 FI=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ZI(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`),or()):t.$refStrategy==="seen"?or():void 0}},VI=(e,t,r)=>(e.description&&(r.description=e.description),r),HI=e=>{const t=lI(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}]))}},BI=(e,t)=>{var r;const n=HI(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var p;return{...c,[u]:(p=Ge(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:or()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ge(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:or(),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},Ed=Symbol.for("vercel.ai.schema");function be(e){let t;return()=>(t==null&&(t=e()),t)}function Uo(e,{validate:t}={}){return{[Ed]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function JI(e){return typeof e=="object"&&e!==null&&Ed in e&&e[Ed]===!0&&"jsonSchema"in e&&"validate"in e}function ro(e){return e==null?Uo({properties:{},additionalProperties:!1}):JI(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?we(e):GI(e):e()}function GI(e){return Uo(()=>Cd(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 Xn({value:t,cause:r.issues})}}})}function WI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Uo(()=>BI(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function KI(e,t){var r;const n=(r=void 0)!=null?r:!1;return Uo(()=>Cd(Yh(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Xh(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function YI(e){return"_zod"in e}function we(e,t){return YI(e)?KI(e):WI(e)}async function St({value:e,schema:t,context:r}){const n=await dr({value:e,schema:t,context:r});if(!n.success)throw Xn.wrap({value:e,cause:n.error,context:r});return n.value}async function dr({value:e,schema:t,context:r}){const n=ro(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:Xn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Xn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function QI({text:e,schema:t}){try{const r=Td(e);return t==null?r:St({value:r,schema:t})}catch(r){throw il.isInstance(r)||Xn.isInstance(r)?r:new il({text:e,cause:r})}}async function pr({text:e,schema:t}){try{const r=Td(e);return t==null?{success:!0,value:r,rawValue:r}:await dr({value:r,schema:t})}catch(r){return{success:!1,error:il.isInstance(r)?r:new il({text:e,cause:r}),rawValue:void 0}}}function Ng(e){try{return Td(e),!0}catch{return!1}}function Ag({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Po).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await pr({text:r,schema:t}))}}))}async function sn({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await dr({value:t[e],schema:r});if(!n.success)throw new D2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var XI=()=>globalThis.fetch,Yt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Lg({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),qg=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Lg({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Lg=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:$n(t,`ai-sdk/provider-utils/${Cg}`,Js()),body:r.content,signal:s}),l=Ao(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw eo(u)||ct.isInstance(u)?u:new ct({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&&(eo(c)||ct.isInstance(c))?c:new ct({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Tg({error:i,url:e,requestBodyValues:r.values})}};function sO(e){return e}function jg(e){return{...e,type:"dynamic"}}function ex({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}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 Qt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Rn=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Ao(n);if(a.trim()==="")return{responseHeaders:i,value:new ct({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await QI({text:a,schema:e});return{responseHeaders:i,value:new ct({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 ct({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},cl=e=>async({response:t})=>{const r=Ao(t);if(t.body==null)throw new O5({});return{responseHeaders:r,value:Ag({stream:t.body,schema:e})}},fr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await pr({text:o,schema:e}),a=Ao(t);if(!s.success)throw new ct({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}},tx=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Ao(e);if(!e.body)throw new ct({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 ct({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Dg(e){return e?.replace(/\/$/,"")}function rx(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*nx({execute:e,input:t,options:r}){const n=e(t,r);if(rx(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 $d,Ug;function ox(){if(Ug)return $d;Ug=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 m of r(h))!n.call(u,m)&&m!==p&&e(u,m,{get:()=>h[m],enumerable:!(f=t(h,m))||f.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),$d=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return $d}var Rd,zg;function sx(){if(zg)return Rd;zg=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,m)=>{if(p&&typeof p=="object"||typeof p=="function")for(let v of r(p))!n.call(h,v)&&v!==f&&e(h,v,{get:()=>p[v],enumerable:!(m=t(p,v))||m.enumerable});return h},a=h=>s(e({},"__esModule",{value:!0}),h),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Rd=a(i);var l=ox();async function c(){return""}function u(){return""}return Rd}var Zg=sx(),ax="vercel.ai.gateway.error",Pd=Symbol.for(ax),Fg,Vg,Vt=class hw extends(Vg=Error,Fg=Pd,Vg){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Fg]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return hw.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Pd in t&&t[Pd]===!0}},Hg="GatewayAuthenticationError",ix=`vercel.ai.gateway.error.${Hg}`,Bg=Symbol.for(ix),Jg,Gg,Md=class mw extends(Gg=Vt,Jg=Bg,Gg){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Jg]=!0,this.name=Hg,this.type="authentication_error"}static isInstance(t){return Vt.hasMarker(t)&&Bg 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
|
|
569
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new mw({message:i,statusCode:o,cause:s,generationId:a})}},Wg="GatewayInvalidRequestError",lx=`vercel.ai.gateway.error.${Wg}`,Kg=Symbol.for(lx),Yg,Qg,cx=class extends(Qg=Vt,Yg=Kg,Qg){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Yg]=!0,this.name=Wg,this.type="invalid_request_error"}static isInstance(e){return Vt.hasMarker(e)&&Kg in e}},Xg="GatewayRateLimitError",ux=`vercel.ai.gateway.error.${Xg}`,ey=Symbol.for(ux),ty,ry,dx=class extends(ry=Vt,ty=ey,ry){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[ty]=!0,this.name=Xg,this.type="rate_limit_exceeded"}static isInstance(e){return Vt.hasMarker(e)&&ey in e}},ny="GatewayModelNotFoundError",px=`vercel.ai.gateway.error.${ny}`,oy=Symbol.for(px),fx=be(()=>we(T({modelId:d()}))),sy,ay,hx=class extends(ay=Vt,sy=oy,ay){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[sy]=!0,this.name=ny,this.type="model_not_found",this.modelId=r}static isInstance(e){return Vt.hasMarker(e)&&oy in e}},iy="GatewayInternalServerError",mx=`vercel.ai.gateway.error.${iy}`,ly=Symbol.for(mx),cy,uy,dy=class extends(uy=Vt,cy=ly,uy){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[cy]=!0,this.name=iy,this.type="internal_server_error"}static isInstance(e){return Vt.hasMarker(e)&&ly in e}},py="GatewayResponseError",gx=`vercel.ai.gateway.error.${py}`,fy=Symbol.for(gx),hy,my,yx=class extends(my=Vt,hy=fy,my){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[hy]=!0,this.name=py,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Vt.hasMarker(e)&&fy in e}};async function gy({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await dr({value:e,schema:vx});if(!a.success){const h=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new yx({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 Md.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new cx({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new dx({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const h=await dr({value:i.error.param,schema:fx});return new hx({message:c,statusCode:t,modelId:h.success?h.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new dy({message:c,statusCode:t,cause:n,generationId:u});default:return new dy({message:c,statusCode:t,cause:n,generationId:u})}}var vx=be(()=>we(T({error:T({message:d(),type:d().nullish(),param:Me().nullish(),code:ae([d(),D()]).nullish()}),generationId:d().nullish()}))),yy="GatewayTimeoutError",_x=`vercel.ai.gateway.error.${yy}`,vy=Symbol.for(_x),_y,wy,by=class gw extends(wy=Vt,_y=vy,wy){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[_y]=!0,this.name=yy,this.type="timeout_error"}static isInstance(t){return Vt.hasMarker(t)&&vy 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 uw({message:s,statusCode:r,cause:n,generationId:o})}};function gy(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 an(e,t){var r;return Vt.isInstance(e)?e:gy(e)?my.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ct.isInstance(e)?e.cause&&gy(e.cause)?my.createTimeoutError({originalMessage:e.message,cause:e}):await uy({response:hE(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await uy({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function hE(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 yy="ai-gateway-auth-method";async function ro(e){const t=await dr({value:e[yy],schema:mE});return t.success?t.value:void 0}var mE=be(()=>we(ae([R("api-key"),R("oidc")]))),vy=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await _g({url:`${this.config.baseURL}/config`,headers:await Qt(this.config.headers()),successfulResponseHandler:fr(gE),failedResponseHandler:$n({errorSchema:Tt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await an(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await _g({url:`${e.origin}/v1/credits`,headers:await Qt(this.config.headers()),successfulResponseHandler:fr(yE),failedResponseHandler:$n({errorSchema:Tt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await an(e)}}},gE=be(()=>we(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:ye(["embedding","image","language","video"]).nullish()}))}))),yE=be(()=>we(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),vE=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 Qt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Yt({url:this.getUrl(),headers:qt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:fr(Tt()),failedResponseHandler:$n({errorSchema:Tt(),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 an(s,await ro(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Qt(this.config.headers());try{const{value:s,responseHeaders:a}=await Yt({url:this.getUrl(),headers:qt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:al(Tt()),failedResponseHandler:$n({errorSchema:Tt(),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 an(s,await ro(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)}}},_E=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 Qt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Yt({url:this.getUrl(),headers:qt(s,t??{},this.getModelConfigHeaders(),await Qt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:fr(wE),failedResponseHandler:$n({errorSchema:Tt(),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 an(a,await ro(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},wE=be(()=>we(T({embeddings:q(q(D())),usage:T({tokens:D()}).nullish(),providerMetadata:ve(d(),ve(d(),Me())).optional()}))),bE=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 Qt(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Yt({url:this.getUrl(),headers:qt(g,l??{},this.getModelConfigHeaders(),await Qt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(_=>_y(_))},...a&&{mask:_y(a)}},successfulResponseHandler:fr(SE),failedResponseHandler:$n({errorSchema:Tt(),errorToMessage:_=>_}),...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:v},...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(v){throw await an(v,await ro(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function _y(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qo(e.data)}:e}var kE=T({images:q(Me()).optional()}).catchall(Me()),TE=Ue("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()})]),CE=T({inputTokens:D().nullish(),outputTokens:D().nullish(),totalTokens:D().nullish()}),SE=T({images:q(d()),warnings:q(TE).optional(),providerMetadata:ve(d(),kE).optional(),usage:CE.optional()}),IE=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 Qt(this.config.headers());try{const{responseHeaders:f,value:g}=await Yt({url:this.getUrl(),headers:qt(p,c??{},this.getModelConfigHeaders(),await Qt(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:EE(i)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new ct({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const m=$g({stream:v.body,schema:PE}).getReader(),{done:C,value:b}=await m.read();if(m.releaseLock(),C||!b)throw new ct({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new ct({message:"Failed to parse video SSE event",cause:b.error,url:y,requestBodyValues:w,statusCode:v.status});const k=b.value;if(k.type==="error")throw new ct({message:k.message,statusCode:k.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:$n({errorSchema:Tt(),errorToMessage:v=>v}),...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 an(f,await ro(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function EE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qo(e.data)}:e}var xE=T({videos:q(Me()).optional()}).catchall(Me()),$E=ae([T({type:R("url"),url:d(),mediaType:d()}),T({type:R("base64"),data:d(),mediaType:d()})]),RE=Ue("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()})]),PE=Ue("type",[T({type:R("result"),videos:q($E),warnings:q(RE).optional(),providerMetadata:ve(d(),xE).optional()}),T({type:R("error"),message:d(),errorType:d(),statusCode:D(),param:Me().nullable()})]),ME=be(()=>we(Bt({objective:Ze().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:Xr(Ze()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:ds(["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:ir().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Bt({include_domains:Xr(Ze()).optional().describe("List of domains to include in search results."),exclude_domains:Xr(Ze()).optional().describe("List of domains to exclude from search results."),after_date:Ze().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:Bt({max_chars_per_result:ir().optional().describe("Maximum characters per result."),max_chars_total:ir().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Bt({max_age_seconds:ir().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.")}))),OE=be(()=>we(yi([Bt({searchId:Ze(),results:Xr(Bt({url:Ze(),title:Ze(),excerpt:Ze(),publishDate:Ze().nullable().optional(),relevanceScore:ir().optional()}))}),Bt({error:ds(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:ir().optional(),message:Ze()})]))),NE=$r({id:"gateway.parallel_search",inputSchema:ME,outputSchema:OE}),AE=(e={})=>NE(e),qE=be(()=>we(Bt({query:yi([Ze(),Xr(Ze())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:ir().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:ir().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:ir().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ze().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Xr(Ze()).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:Xr(Ze()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ze().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:Ze().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:Ze().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:Ze().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:ds(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),LE=be(()=>we(yi([Bt({results:Xr(Bt({title:Ze(),url:Ze(),snippet:Ze(),date:Ze().optional(),lastUpdated:Ze().optional()})),id:Ze()}),Bt({error:ds(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:ir().optional(),message:Ze()})]))),jE=$r({id:"gateway.perplexity_search",inputSchema:qE,outputSchema:LE}),DE=(e={})=>jE(e),UE={parallelSearch:AE,perplexitySearch:DE};async function zE(){var e;return(e=qg.getContext().headers)==null?void 0:e["x-vercel-id"]}var ZE="3.0.66",FE="0.0.1";function VE(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 v=await BE(e);return xn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":FE,[yy]:v.authMethod,...e.headers},`ai-sdk/gateway/${ZE}`)}catch(v){throw Sd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=jo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=jo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=jo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=jo({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const m=await zE();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...w&&{"ai-o11y-region":w},...m&&{"ai-o11y-request-id":m},..._&&{"ai-o11y-project-id":_}}}},u=v=>new vE(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var v,y,w;const _=(w=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?w:Date.now();return(!n||_-a>s)&&(a=_,n=new vy({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(m=>(o=m,m)).catch(async m=>{throw await an(m,await ro(await l()))})),o?Promise.resolve(o):n},p=async()=>new vy({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await an(v,await ro(await l()))}),f=function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(v)};f.specificationVersion="v3",f.getAvailableModels=h,f.getCredits=p,f.imageModel=v=>new bE(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=v=>new _E(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=v=>new IE(v,{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=UE,f}var HE=VE();async function BE(e){const t=jo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await qg.getVercelOidcToken(),authMethod:"oidc"}}var JE=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},no="1.9.0",wy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function GE(e){var t=new Set([e]),r=new Set,n=e.match(wy);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(wy);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 WE=GE(no),KE=no.split(".")[0],Bs=Symbol.for("opentelemetry.js.api."+KE),Js=JE;function Gs(e,t,r,n){var o;n===void 0&&(n=!1);var s=Js[Bs]=(o=Js[Bs])!==null&&o!==void 0?o:{version:no};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!==no){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+no);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+no+"."),!0}function oo(e){var t,r,n=(t=Js[Bs])===null||t===void 0?void 0:t.version;if(!(!n||!WE(n)))return(r=Js[Bs])===null||r===void 0?void 0:r[e]}function Ws(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+no+".");var r=Js[Bs];r&&delete r[e]}var YE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},QE=function(e,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))},XE=(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 Ks("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ks("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ks("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ks("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ks("verbose",this._namespace,t)},e})();function Ks(e,t,r){var n=oo("diag");if(n)return r.unshift(t),n[e].apply(n,QE([],YE(r),!1))}var sr;(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"})(sr||(sr={}));function ex(e,t){e<sr.NONE?e=sr.NONE:e>sr.ALL&&(e=sr.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",sr.ERROR),warn:r("warn",sr.WARN),info:r("info",sr.INFO),debug:r("debug",sr.DEBUG),verbose:r("verbose",sr.VERBOSE)}}var tx=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},rx=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))},nx="diag",zr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=oo("diag");if(i)return i[o].apply(i,rx([],tx(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:sr.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=oo("diag"),h=ex((i=s.logLevel)!==null&&i!==void 0?i:sr.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 Gs("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Ws(nx,r)},r.createComponentLogger=function(o){return new XE(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})(),ox=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},sx=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.")},ax=(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=ox(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=sx(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})();zr.instance();function ix(e){return e===void 0&&(e={}),new ax(new Map(Object.entries(e)))}function by(e){return Symbol.for(e)}var lx=(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})(),cx=new lx,so=(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)}})(),ux=(function(){function e(){}return e.prototype.createGauge=function(t,r){return wx},e.prototype.createHistogram=function(t,r){return bx},e.prototype.createCounter=function(t,r){return _x},e.prototype.createUpDownCounter=function(t,r){return kx},e.prototype.createObservableGauge=function(t,r){return Cx},e.prototype.createObservableCounter=function(t,r){return Tx},e.prototype.createObservableUpDownCounter=function(t,r){return Sx},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),il=(function(){function e(){}return e})(),dx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(il),px=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(il),fx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(il),hx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(il),Id=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),mx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Id),gx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Id),yx=(function(e){so(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Id),vx=new ux,_x=new dx,wx=new fx,bx=new hx,kx=new px,Tx=new mx,Cx=new gx,Sx=new yx,Ix={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},Ex={set:function(e,t,r){e!=null&&(e[t]=r)}},xx=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},$x=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))},Rx=(function(){function e(){}return e.prototype.active=function(){return cx},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,$x([n],xx(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),Px=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},Mx=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))},Ed="context",Ox=new Rx,ll=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Gs(Ed,t,zr.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,Mx([t,r,n],Px(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return oo(Ed)||Ox},e.prototype.disable=function(){this._getContextManager().disable(),Ws(Ed,zr.instance())},e})(),xd;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(xd||(xd={}));var ky="0000000000000000",Ty="00000000000000000000000000000000",Nx={traceId:Ty,spanId:ky,traceFlags:xd.NONE},Ys=(function(){function e(t){t===void 0&&(t=Nx),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})(),$d=by("OpenTelemetry Context Key SPAN");function Rd(e){return e.getValue($d)||void 0}function Ax(){return Rd(ll.getInstance().active())}function Pd(e,t){return e.setValue($d,t)}function qx(e){return e.deleteValue($d)}function Lx(e,t){return Pd(e,new Ys(t))}function Cy(e){var t;return(t=Rd(e))===null||t===void 0?void 0:t.spanContext()}var jx=/^([0-9a-f]{32})$/i,Dx=/^[0-9a-f]{16}$/i;function Ux(e){return jx.test(e)&&e!==Ty}function zx(e){return Dx.test(e)&&e!==ky}function Sy(e){return Ux(e.traceId)&&zx(e.spanId)}function Zx(e){return new Ys(e)}var Md=ll.getInstance(),Iy=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Md.active());var o=!!r?.root;if(o)return new Ys;var s=n&&Cy(n);return Fx(s)&&Sy(s)?new Ys(s):new Ys},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??Md.active(),c=this.startSpan(t,s,l),u=Pd(l,c);return Md.with(u,i,void 0,c)}},e})();function Fx(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var Vx=new Iy,Hx=(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):Vx},e})(),Bx=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Iy},e})(),Jx=new Bx,Ey=(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 Hx(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Jx},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})(),cl;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(cl||(cl={}));var xy=ll.getInstance();zr.instance();var Gx=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return vx},e})(),Wx=new Gx,Od="metrics",Kx=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Gs(Od,t,zr.instance())},e.prototype.getMeterProvider=function(){return oo(Od)||Wx},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Ws(Od,zr.instance())},e})();Kx.getInstance();var Yx=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Nd=by("OpenTelemetry Baggage Key");function $y(e){return e.getValue(Nd)||void 0}function Qx(){return $y(ll.getInstance().active())}function Xx(e,t){return e.setValue(Nd,t)}function e8(e){return e.deleteValue(Nd)}var Ad="propagation",t8=new Yx,r8=(function(){function e(){this.createBaggage=ix,this.getBaggage=$y,this.getActiveBaggage=Qx,this.setBaggage=Xx,this.deleteBaggage=e8}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Gs(Ad,t,zr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=Ex),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=Ix),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Ws(Ad,zr.instance())},e.prototype._getGlobalPropagator=function(){return oo(Ad)||t8},e})();r8.getInstance();var qd="trace",n8=(function(){function e(){this._proxyTracerProvider=new Ey,this.wrapSpanContext=Zx,this.isSpanContextValid=Sy,this.deleteSpan=qx,this.getSpan=Rd,this.getActiveSpan=Ax,this.getSpanContext=Cy,this.setSpan=Pd,this.setSpanContext=Lx}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Gs(qd,this._proxyTracerProvider,zr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return oo(qd)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ws(qd,zr.instance()),this._proxyTracerProvider=new Ey},e})(),o8=n8.getInstance(),s8=Object.defineProperty,a8=(e,t)=>{for(var r in t)s8(e,r,{get:t[r],enumerable:!0})},Ry="AI_InvalidArgumentError",Py=`vercel.ai.error.${Ry}`,i8=Symbol.for(Py),My,Zr=class extends _e{constructor({parameter:t,value:r,message:n}){super({name:Ry,message:`Invalid argument for parameter ${t}: ${n}`}),this[My]=!0,this.parameter=t,this.value=r}static isInstance(t){return _e.hasMarker(t,Py)}};My=i8;var Oy="AI_InvalidToolApprovalError",Ny=`vercel.ai.error.${Oy}`,l8=Symbol.for(Ny),Ay,c8=class extends _e{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 _e.hasMarker(e,Ny)}};Ay=l8;var qy="AI_InvalidToolInputError",Ly=`vercel.ai.error.${qy}`,u8=Symbol.for(Ly),jy,Ld=class extends _e{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Kn(r)}`}){super({name:qy,message:n,cause:r}),this[jy]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return _e.hasMarker(e,Ly)}};jy=u8;var Dy="AI_ToolCallNotFoundForApprovalError",Uy=`vercel.ai.error.${Dy}`,d8=Symbol.for(Uy),zy,jd=class extends _e{constructor({toolCallId:e,approvalId:t}){super({name:Dy,message:`Tool call "${e}" not found for approval request "${t}".`}),this[zy]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return _e.hasMarker(e,Uy)}};zy=d8;var Zy="AI_MissingToolResultsError",Fy=`vercel.ai.error.${Zy}`,p8=Symbol.for(Fy),Vy,Hy=class extends _e{constructor({toolCallIds:e}){super({name:Zy,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Vy]=!0,this.toolCallIds=e}static isInstance(e){return _e.hasMarker(e,Fy)}};Vy=p8;var By="AI_NoObjectGeneratedError",Jy=`vercel.ai.error.${By}`,f8=Symbol.for(Jy),Gy,Rn=class extends _e{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:By,message:e,cause:t}),this[Gy]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return _e.hasMarker(e,Jy)}};Gy=f8;var Wy="AI_NoOutputGeneratedError",Ky=`vercel.ai.error.${Wy}`,h8=Symbol.for(Ky),Yy,Qy=class extends _e{constructor({message:e="No output generated.",cause:t}={}){super({name:Wy,message:e,cause:t}),this[Yy]=!0}static isInstance(e){return _e.hasMarker(e,Ky)}};Yy=h8;var Xy="AI_NoSuchToolError",ev=`vercel.ai.error.${Xy}`,m8=Symbol.for(ev),tv,Dd=class extends _e{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:Xy,message:r}),this[tv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return _e.hasMarker(e,ev)}};tv=m8;var rv="AI_ToolCallRepairError",nv=`vercel.ai.error.${rv}`,g8=Symbol.for(nv),ov,y8=class extends _e{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Kn(e)}`}){super({name:rv,message:r,cause:e}),this[ov]=!0,this.originalError=t}static isInstance(e){return _e.hasMarker(e,nv)}};ov=g8;var v8=class extends _e{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}},sv="AI_UIMessageStreamError",av=`vercel.ai.error.${sv}`,_8=Symbol.for(av),iv,Uo=class extends _e{constructor({chunkType:e,chunkId:t,message:r}){super({name:sv,message:r}),this[iv]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return _e.hasMarker(e,av)}};iv=_8;var lv="AI_InvalidMessageRoleError",cv=`vercel.ai.error.${lv}`,w8=Symbol.for(cv),uv,b8=class extends _e{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lv,message:t}),this[uv]=!0,this.role=e}static isInstance(e){return _e.hasMarker(e,cv)}};uv=w8;var dv="AI_RetryError",pv=`vercel.ai.error.${dv}`,k8=Symbol.for(pv),fv,hv=class extends _e{constructor({message:e,reason:t,errors:r}){super({name:dv,message:e}),this[fv]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return _e.hasMarker(e,pv)}};fv=k8;function ao(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Rr(e){for(const t of ao(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function T8({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 C8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",mv=!1,Ud=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}mv||(mv=!0,console.info(C8));for(const r of e.warnings)console.warn(T8({warning:r,provider:e.provider,model:e.model}))}};function S8({provider:e,modelId:t}){Ud({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function I8(e){return e.specificationVersion==="v3"?e:(S8({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:gv(o.finishReason),usage:yv(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:E8(o.stream)}};default:return t[r]}}}))}function E8(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:gv(t.finishReason),usage:yv(t.usage)});break;default:r.enqueue(t);break}}}))}function gv(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function yv(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 ul(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new v8({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return I8(e)}return x8().languageModel(e)}function x8(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:HE}function zd(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function vv(e){if(!(e==null||typeof e=="number"))return e.stepMs}function $8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var R8=[{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]}],P8=e=>{const t=typeof e=="string"?Ao(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function M8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?P8(e):e}function O8({data:e,signatures:t}){const r=M8(e),n=typeof r=="string"?Ao(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 _v="6.0.116",N8=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();hg(o);try{const s=await fetch(o,{headers:xn({},`ai-sdk/${_v}`,Hs()),signal:r});if(!s.ok)throw new Kt({url:o,statusCode:s.status,statusText:s.statusText});return{data:await fg({response:s,url:o,maxBytes:t??fd}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Kt.isInstance(s)?s:new Kt({url:o,cause:s})}},A8=(e=N8)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function q8(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 wv=ae([d(),xi(Uint8Array),xi(ArrayBuffer),am(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function bv(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}=q8(e.toString());if(t==null||r==null)throw new _e({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function L8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?qo(new Uint8Array(e)):qo(e)}async function kv({prompt:e,supportedUrls:t,download:r=A8()}){const n=await D8(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}]:ao(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>j8({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 Hy({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Hy({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function j8({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=>U8(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}=bv(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:Tv(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:Tv(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 b8({role:n})}}}async function D8(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&&WI({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 U8(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}=bv(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=O8({data:l,signatures:R8}))!=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 Tv(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 Qs({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Kn(r)}:o==="json"?{type:"error-json",value:Cv(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:Cv(r)}}function Cv(e){return e===void 0?null:e}function Zd({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 Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Zr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Zr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Zr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Zr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Zr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Zr({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 z8(e){return e!=null&&Object.keys(e).length>0}async function Sv({tools:e,toolChoice:t,activeTools:r}){if(!z8(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 to(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 Xs=gc(()=>ae([Ei(),d(),D(),ge(),ve(d(),Xs.optional()),q(Xs)])),ut=ve(d(),ve(d(),Xs.optional())),Iv=T({type:R("text"),text:d(),providerOptions:ut.optional()}),Z8=T({type:R("image"),image:ae([wv,xi(URL)]),mediaType:d().optional(),providerOptions:ut.optional()}),Ev=T({type:R("file"),data:ae([wv,xi(URL)]),filename:d().optional(),mediaType:d(),providerOptions:ut.optional()}),F8=T({type:R("reasoning"),text:d(),providerOptions:ut.optional()}),V8=T({type:R("tool-call"),toolCallId:d(),toolName:d(),input:Me(),providerOptions:ut.optional(),providerExecuted:ge().optional()}),H8=Ue("type",[T({type:R("text"),value:d(),providerOptions:ut.optional()}),T({type:R("json"),value:Xs,providerOptions:ut.optional()}),T({type:R("execution-denied"),reason:d().optional(),providerOptions:ut.optional()}),T({type:R("error-text"),value:d(),providerOptions:ut.optional()}),T({type:R("error-json"),value:Xs,providerOptions:ut.optional()}),T({type:R("content"),value:q(ae([T({type:R("text"),text:d(),providerOptions:ut.optional()}),T({type:R("media"),data:d(),mediaType:d()}),T({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:ut.optional()}),T({type:R("file-url"),url:d(),providerOptions:ut.optional()}),T({type:R("file-id"),fileId:ae([d(),ve(d(),d())]),providerOptions:ut.optional()}),T({type:R("image-data"),data:d(),mediaType:d(),providerOptions:ut.optional()}),T({type:R("image-url"),url:d(),providerOptions:ut.optional()}),T({type:R("image-file-id"),fileId:ae([d(),ve(d(),d())]),providerOptions:ut.optional()}),T({type:R("custom"),providerOptions:ut.optional()})]))})]),xv=T({type:R("tool-result"),toolCallId:d(),toolName:d(),output:H8,providerOptions:ut.optional()}),B8=T({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),J8=T({type:R("tool-approval-response"),approvalId:d(),approved:ge(),reason:d().optional()}),G8=T({role:R("system"),content:d(),providerOptions:ut.optional()}),W8=T({role:R("user"),content:ae([d(),q(ae([Iv,Z8,Ev]))]),providerOptions:ut.optional()}),K8=T({role:R("assistant"),content:ae([d(),q(ae([Iv,Ev,F8,V8,xv,B8]))]),providerOptions:ut.optional()}),Y8=T({role:R("tool"),content:q(ae([xv,J8])),providerOptions:ut.optional()}),Q8=ae([G8,W8,K8,Y8]);async function $v(e){if(e.prompt==null&&e.messages==null)throw new Yn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Yn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!ao(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Yn({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 Yn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Yn({prompt:e,message:"messages must not be empty"});const r=await dr({value:t,schema:q(Q8)});if(!r.success)throw new Yn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function Rv(e){if(!Sd.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 _e({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 gw({message:s,statusCode:r,cause:n,generationId:o})}};function ky(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 an(e,t){var r;return Vt.isInstance(e)?e:ky(e)?by.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ct.isInstance(e)?e.cause&&ky(e.cause)?by.createTimeoutError({originalMessage:e.message,cause:e}):await gy({response:wx(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await gy({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function wx(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 Ty="ai-gateway-auth-method";async function no(e){const t=await dr({value:e[Ty],schema:bx});return t.success?t.value:void 0}var bx=be(()=>we(ae([R("api-key"),R("oidc")]))),Cy=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Sg({url:`${this.config.baseURL}/config`,headers:await Qt(this.config.headers()),successfulResponseHandler:fr(kx),failedResponseHandler:Rn({errorSchema:Tt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await an(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Sg({url:`${e.origin}/v1/credits`,headers:await Qt(this.config.headers()),successfulResponseHandler:fr(Tx),failedResponseHandler:Rn({errorSchema:Tt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await an(e)}}},kx=be(()=>we(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:ye(["embedding","image","language","video"]).nullish()}))}))),Tx=be(()=>we(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),Cx=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 Qt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Yt({url:this.getUrl(),headers:qt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:fr(Tt()),failedResponseHandler:Rn({errorSchema:Tt(),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 an(s,await no(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Qt(this.config.headers());try{const{value:s,responseHeaders:a}=await Yt({url:this.getUrl(),headers:qt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:cl(Tt()),failedResponseHandler:Rn({errorSchema:Tt(),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 an(s,await no(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)}}},Sx=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 Qt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Yt({url:this.getUrl(),headers:qt(s,t??{},this.getModelConfigHeaders(),await Qt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:fr(Ix),failedResponseHandler:Rn({errorSchema:Tt(),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 an(a,await no(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},Ix=be(()=>we(T({embeddings:q(q(D())),usage:T({tokens:D()}).nullish(),providerMetadata:ve(d(),ve(d(),Me())).optional()}))),xx=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 m=await Qt(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Yt({url:this.getUrl(),headers:qt(m,l??{},this.getModelConfigHeaders(),await Qt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(_=>Sy(_))},...a&&{mask:Sy(a)}},successfulResponseHandler:fr(Px),failedResponseHandler:Rn({errorSchema:Tt(),errorToMessage:_=>_}),...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:v},...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(v){throw await an(v,await no(m))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function Sy(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Lo(e.data)}:e}var Ex=T({images:q(Me()).optional()}).catchall(Me()),$x=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()})]),Rx=T({inputTokens:D().nullish(),outputTokens:D().nullish(),totalTokens:D().nullish()}),Px=T({images:q(d()),warnings:q($x).optional(),providerMetadata:ve(d(),Ex).optional(),usage:Rx.optional()}),Mx=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 Qt(this.config.headers());try{const{responseHeaders:f,value:m}=await Yt({url:this.getUrl(),headers:qt(p,c??{},this.getModelConfigHeaders(),await Qt(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:Ox(i)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new ct({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const g=Ag({stream:v.body,schema:Lx}).getReader(),{done:C,value:b}=await g.read();if(g.releaseLock(),C||!b)throw new ct({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new ct({message:"Failed to parse video SSE event",cause:b.error,url:y,requestBodyValues:w,statusCode:v.status});const k=b.value;if(k.type==="error")throw new ct({message:k.message,statusCode:k.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:Rn({errorSchema:Tt(),errorToMessage:v=>v}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:m.videos,warnings:(h=m.warnings)!=null?h:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await an(f,await no(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function Ox(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Lo(e.data)}:e}var Nx=T({videos:q(Me()).optional()}).catchall(Me()),Ax=ae([T({type:R("url"),url:d(),mediaType:d()}),T({type:R("base64"),data:d(),mediaType:d()})]),qx=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()})]),Lx=ze("type",[T({type:R("result"),videos:q(Ax),warnings:q(qx).optional(),providerMetadata:ve(d(),Nx).optional()}),T({type:R("error"),message:d(),errorType:d(),statusCode:D(),param:Me().nullable()})]),jx=be(()=>we(Bt({objective:Ue().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:Xr(Ue()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:fs(["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:ir().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Bt({include_domains:Xr(Ue()).optional().describe("List of domains to include in search results."),exclude_domains:Xr(Ue()).optional().describe("List of domains to exclude from search results."),after_date:Ue().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:Bt({max_chars_per_result:ir().optional().describe("Maximum characters per result."),max_chars_total:ir().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Bt({max_age_seconds:ir().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.")}))),Dx=be(()=>we(wi([Bt({searchId:Ue(),results:Xr(Bt({url:Ue(),title:Ue(),excerpt:Ue(),publishDate:Ue().nullable().optional(),relevanceScore:ir().optional()}))}),Bt({error:fs(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:ir().optional(),message:Ue()})]))),Ux=$r({id:"gateway.parallel_search",inputSchema:jx,outputSchema:Dx}),zx=(e={})=>Ux(e),Zx=be(()=>we(Bt({query:wi([Ue(),Xr(Ue())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:ir().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:ir().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:ir().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ue().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Xr(Ue()).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:Xr(Ue()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ue().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:Ue().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:Ue().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:Ue().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:fs(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Fx=be(()=>we(wi([Bt({results:Xr(Bt({title:Ue(),url:Ue(),snippet:Ue(),date:Ue().optional(),lastUpdated:Ue().optional()})),id:Ue()}),Bt({error:fs(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:ir().optional(),message:Ue()})]))),Vx=$r({id:"gateway.perplexity_search",inputSchema:Zx,outputSchema:Fx}),Hx=(e={})=>Vx(e),Bx={parallelSearch:zx,perplexitySearch:Hx};async function Jx(){var e;return(e=Zg.getContext().headers)==null?void 0:e["x-vercel-id"]}var Gx="3.0.66",Wx="0.0.1";function Kx(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=Dg(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const v=await Qx(e);return $n({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":Wx,[Ty]:v.authMethod,...e.headers},`ai-sdk/gateway/${Gx}`)}catch(v){throw Md.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=Do({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Do({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=Do({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=Do({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const g=await Jx();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...w&&{"ai-o11y-region":w},...g&&{"ai-o11y-request-id":g},..._&&{"ai-o11y-project-id":_}}}},u=v=>new Cx(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var v,y,w;const _=(w=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?w:Date.now();return(!n||_-a>s)&&(a=_,n=new Cy({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(g=>(o=g,g)).catch(async g=>{throw await an(g,await no(await l()))})),o?Promise.resolve(o):n},p=async()=>new Cy({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await an(v,await no(await l()))}),f=function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(v)};f.specificationVersion="v3",f.getAvailableModels=h,f.getCredits=p,f.imageModel=v=>new xx(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const m=v=>new Sx(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=m,f.textEmbeddingModel=m,f.videoModel=v=>new Mx(v,{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=Bx,f}var Yx=Kx();async function Qx(e){const t=Do({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Zg.getVercelOidcToken(),authMethod:"oidc"}}var Xx=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},oo="1.9.0",Iy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function eE(e){var t=new Set([e]),r=new Set,n=e.match(Iy);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(Iy);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 tE=eE(oo),rE=oo.split(".")[0],Gs=Symbol.for("opentelemetry.js.api."+rE),Ws=Xx;function Ks(e,t,r,n){var o;n===void 0&&(n=!1);var s=Ws[Gs]=(o=Ws[Gs])!==null&&o!==void 0?o:{version:oo};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!==oo){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+oo);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+oo+"."),!0}function so(e){var t,r,n=(t=Ws[Gs])===null||t===void 0?void 0:t.version;if(!(!n||!tE(n)))return(r=Ws[Gs])===null||r===void 0?void 0:r[e]}function Ys(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+oo+".");var r=Ws[Gs];r&&delete r[e]}var nE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},oE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},sE=(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 Qs("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Qs("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Qs("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Qs("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Qs("verbose",this._namespace,t)},e})();function Qs(e,t,r){var n=so("diag");if(n)return r.unshift(t),n[e].apply(n,oE([],nE(r),!1))}var sr;(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"})(sr||(sr={}));function aE(e,t){e<sr.NONE?e=sr.NONE:e>sr.ALL&&(e=sr.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",sr.ERROR),warn:r("warn",sr.WARN),info:r("info",sr.INFO),debug:r("debug",sr.DEBUG),verbose:r("verbose",sr.VERBOSE)}}var 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="diag",zr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=so("diag");if(i)return i[o].apply(i,lE([],iE(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:sr.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=so("diag"),h=aE((i=s.logLevel)!==null&&i!==void 0?i:sr.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 Ks("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Ys(cE,r)},r.createComponentLogger=function(o){return new sE(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})(),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){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.")},pE=(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=uE(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=dE(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})();zr.instance();function fE(e){return e===void 0&&(e={}),new pE(new Map(Object.entries(e)))}function xy(e){return Symbol.for(e)}var hE=(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})(),mE=new hE,ao=(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)}})(),gE=(function(){function e(){}return e.prototype.createGauge=function(t,r){return IE},e.prototype.createHistogram=function(t,r){return xE},e.prototype.createCounter=function(t,r){return SE},e.prototype.createUpDownCounter=function(t,r){return EE},e.prototype.createObservableGauge=function(t,r){return RE},e.prototype.createObservableCounter=function(t,r){return $E},e.prototype.createObservableUpDownCounter=function(t,r){return PE},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),ul=(function(){function e(){}return e})(),yE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ul),vE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ul),_E=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ul),wE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ul),Od=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),bE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Od),kE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Od),TE=(function(e){ao(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Od),CE=new gE,SE=new yE,IE=new _E,xE=new wE,EE=new vE,$E=new bE,RE=new kE,PE=new TE,ME={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},OE={set:function(e,t,r){e!=null&&(e[t]=r)}},NE=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},AE=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))},qE=(function(){function e(){}return e.prototype.active=function(){return mE},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,AE([n],NE(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),LE=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},jE=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",DE=new qE,dl=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Ks(Nd,t,zr.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,jE([t,r,n],LE(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return so(Nd)||DE},e.prototype.disable=function(){this._getContextManager().disable(),Ys(Nd,zr.instance())},e})(),Ad;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ad||(Ad={}));var Ey="0000000000000000",$y="00000000000000000000000000000000",UE={traceId:$y,spanId:Ey,traceFlags:Ad.NONE},Xs=(function(){function e(t){t===void 0&&(t=UE),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})(),qd=xy("OpenTelemetry Context Key SPAN");function Ld(e){return e.getValue(qd)||void 0}function zE(){return Ld(dl.getInstance().active())}function jd(e,t){return e.setValue(qd,t)}function ZE(e){return e.deleteValue(qd)}function FE(e,t){return jd(e,new Xs(t))}function Ry(e){var t;return(t=Ld(e))===null||t===void 0?void 0:t.spanContext()}var VE=/^([0-9a-f]{32})$/i,HE=/^[0-9a-f]{16}$/i;function BE(e){return VE.test(e)&&e!==$y}function JE(e){return HE.test(e)&&e!==Ey}function Py(e){return BE(e.traceId)&&JE(e.spanId)}function GE(e){return new Xs(e)}var Dd=dl.getInstance(),My=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Dd.active());var o=!!r?.root;if(o)return new Xs;var s=n&&Ry(n);return WE(s)&&Py(s)?new Xs(s):new Xs},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??Dd.active(),c=this.startSpan(t,s,l),u=jd(l,c);return Dd.with(u,i,void 0,c)}},e})();function WE(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var KE=new My,YE=(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):KE},e})(),QE=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new My},e})(),XE=new QE,Oy=(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 YE(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:XE},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})(),pl;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(pl||(pl={}));var Ny=dl.getInstance();zr.instance();var e8=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return CE},e})(),t8=new e8,Ud="metrics",r8=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Ks(Ud,t,zr.instance())},e.prototype.getMeterProvider=function(){return so(Ud)||t8},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Ys(Ud,zr.instance())},e})();r8.getInstance();var n8=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),zd=xy("OpenTelemetry Baggage Key");function Ay(e){return e.getValue(zd)||void 0}function o8(){return Ay(dl.getInstance().active())}function s8(e,t){return e.setValue(zd,t)}function a8(e){return e.deleteValue(zd)}var Zd="propagation",i8=new n8,l8=(function(){function e(){this.createBaggage=fE,this.getBaggage=Ay,this.getActiveBaggage=o8,this.setBaggage=s8,this.deleteBaggage=a8}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Ks(Zd,t,zr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=OE),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=ME),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Ys(Zd,zr.instance())},e.prototype._getGlobalPropagator=function(){return so(Zd)||i8},e})();l8.getInstance();var Fd="trace",c8=(function(){function e(){this._proxyTracerProvider=new Oy,this.wrapSpanContext=GE,this.isSpanContextValid=Py,this.deleteSpan=ZE,this.getSpan=Ld,this.getActiveSpan=zE,this.getSpanContext=Ry,this.setSpan=jd,this.setSpanContext=FE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Ks(Fd,this._proxyTracerProvider,zr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return so(Fd)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ys(Fd,zr.instance()),this._proxyTracerProvider=new Oy},e})(),u8=c8.getInstance(),d8=Object.defineProperty,p8=(e,t)=>{for(var r in t)d8(e,r,{get:t[r],enumerable:!0})},qy="AI_InvalidArgumentError",Ly=`vercel.ai.error.${qy}`,f8=Symbol.for(Ly),jy,Zr=class extends _e{constructor({parameter:t,value:r,message:n}){super({name:qy,message:`Invalid argument for parameter ${t}: ${n}`}),this[jy]=!0,this.parameter=t,this.value=r}static isInstance(t){return _e.hasMarker(t,Ly)}};jy=f8;var Dy="AI_InvalidToolApprovalError",Uy=`vercel.ai.error.${Dy}`,h8=Symbol.for(Uy),zy,m8=class extends _e{constructor({approvalId:e}){super({name:Dy,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[zy]=!0,this.approvalId=e}static isInstance(e){return _e.hasMarker(e,Uy)}};zy=h8;var Zy="AI_InvalidToolInputError",Fy=`vercel.ai.error.${Zy}`,g8=Symbol.for(Fy),Vy,Vd=class extends _e{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Yn(r)}`}){super({name:Zy,message:n,cause:r}),this[Vy]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return _e.hasMarker(e,Fy)}};Vy=g8;var Hy="AI_ToolCallNotFoundForApprovalError",By=`vercel.ai.error.${Hy}`,y8=Symbol.for(By),Jy,Hd=class extends _e{constructor({toolCallId:e,approvalId:t}){super({name:Hy,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Jy]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return _e.hasMarker(e,By)}};Jy=y8;var Gy="AI_MissingToolResultsError",Wy=`vercel.ai.error.${Gy}`,v8=Symbol.for(Wy),Ky,Yy=class extends _e{constructor({toolCallIds:e}){super({name:Gy,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Ky]=!0,this.toolCallIds=e}static isInstance(e){return _e.hasMarker(e,Wy)}};Ky=v8;var Qy="AI_NoObjectGeneratedError",Xy=`vercel.ai.error.${Qy}`,_8=Symbol.for(Xy),ev,Pn=class extends _e{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Qy,message:e,cause:t}),this[ev]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return _e.hasMarker(e,Xy)}};ev=_8;var tv="AI_NoOutputGeneratedError",rv=`vercel.ai.error.${tv}`,w8=Symbol.for(rv),nv,ov=class extends _e{constructor({message:e="No output generated.",cause:t}={}){super({name:tv,message:e,cause:t}),this[nv]=!0}static isInstance(e){return _e.hasMarker(e,rv)}};nv=w8;var sv="AI_NoSuchToolError",av=`vercel.ai.error.${sv}`,b8=Symbol.for(av),iv,Bd=class extends _e{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:sv,message:r}),this[iv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return _e.hasMarker(e,av)}};iv=b8;var lv="AI_ToolCallRepairError",cv=`vercel.ai.error.${lv}`,k8=Symbol.for(cv),uv,T8=class extends _e{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Yn(e)}`}){super({name:lv,message:r,cause:e}),this[uv]=!0,this.originalError=t}static isInstance(e){return _e.hasMarker(e,cv)}};uv=k8;var C8=class extends _e{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}},dv="AI_UIMessageStreamError",pv=`vercel.ai.error.${dv}`,S8=Symbol.for(pv),fv,zo=class extends _e{constructor({chunkType:e,chunkId:t,message:r}){super({name:dv,message:r}),this[fv]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return _e.hasMarker(e,pv)}};fv=S8;var hv="AI_InvalidMessageRoleError",mv=`vercel.ai.error.${hv}`,I8=Symbol.for(mv),gv,x8=class extends _e{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:hv,message:t}),this[gv]=!0,this.role=e}static isInstance(e){return _e.hasMarker(e,mv)}};gv=I8;var yv="AI_RetryError",vv=`vercel.ai.error.${yv}`,E8=Symbol.for(vv),_v,wv=class extends _e{constructor({message:e,reason:t,errors:r}){super({name:yv,message:e}),this[_v]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return _e.hasMarker(e,vv)}};_v=E8;function io(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Rr(e){for(const t of io(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function $8({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 R8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",bv=!1,Jd=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}bv||(bv=!0,console.info(R8));for(const r of e.warnings)console.warn($8({warning:r,provider:e.provider,model:e.model}))}};function P8({provider:e,modelId:t}){Jd({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function M8(e){return e.specificationVersion==="v3"?e:(P8({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:kv(o.finishReason),usage:Tv(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:O8(o.stream)}};default:return t[r]}}}))}function O8(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:kv(t.finishReason),usage:Tv(t.usage)});break;default:r.enqueue(t);break}}}))}function kv(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function Tv(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 fl(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new C8({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return M8(e)}return N8().languageModel(e)}function N8(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Yx}function Gd(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function Cv(e){if(!(e==null||typeof e=="number"))return e.stepMs}function A8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var q8=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],L8=e=>{const t=typeof e=="string"?qo(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function j8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?L8(e):e}function D8({data:e,signatures:t}){const r=j8(e),n=typeof r=="string"?qo(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 Sv="6.0.116",U8=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();wg(o);try{const s=await fetch(o,{headers:$n({},`ai-sdk/${Sv}`,Js()),signal:r});if(!s.ok)throw new Kt({url:o,statusCode:s.status,statusText:s.statusText});return{data:await _g({response:s,url:o,maxBytes:t??wd}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Kt.isInstance(s)?s:new Kt({url:o,cause:s})}},z8=(e=U8)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Z8(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 Iv=ae([d(),Pi(Uint8Array),Pi(ArrayBuffer),pm(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function xv(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}=Z8(e.toString());if(t==null||r==null)throw new _e({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function F8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Lo(new Uint8Array(e)):Lo(e)}async function Ev({prompt:e,supportedUrls:t,download:r=z8()}){const n=await H8(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}]:io(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>V8({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 Yy({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Yy({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function V8({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=>B8(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}=xv(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:$v(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:$v(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 x8({role:n})}}}async function H8(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&&tI({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 B8(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}=xv(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=D8({data:l,signatures:q8}))!=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 $v(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 ea({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Yn(r)}:o==="json"?{type:"error-json",value:Rv(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:Rv(r)}}function Rv(e){return e===void 0?null:e}function Wd({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 Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Zr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Zr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Zr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Zr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Zr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Zr({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 J8(e){return e!=null&&Object.keys(e).length>0}async function Pv({tools:e,toolChoice:t,activeTools:r}){if(!J8(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 ro(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 ta=Tc(()=>ae([Ri(),d(),D(),ge(),ve(d(),ta.optional()),q(ta)])),ut=ve(d(),ve(d(),ta.optional())),Mv=T({type:R("text"),text:d(),providerOptions:ut.optional()}),G8=T({type:R("image"),image:ae([Iv,Pi(URL)]),mediaType:d().optional(),providerOptions:ut.optional()}),Ov=T({type:R("file"),data:ae([Iv,Pi(URL)]),filename:d().optional(),mediaType:d(),providerOptions:ut.optional()}),W8=T({type:R("reasoning"),text:d(),providerOptions:ut.optional()}),K8=T({type:R("tool-call"),toolCallId:d(),toolName:d(),input:Me(),providerOptions:ut.optional(),providerExecuted:ge().optional()}),Y8=ze("type",[T({type:R("text"),value:d(),providerOptions:ut.optional()}),T({type:R("json"),value:ta,providerOptions:ut.optional()}),T({type:R("execution-denied"),reason:d().optional(),providerOptions:ut.optional()}),T({type:R("error-text"),value:d(),providerOptions:ut.optional()}),T({type:R("error-json"),value:ta,providerOptions:ut.optional()}),T({type:R("content"),value:q(ae([T({type:R("text"),text:d(),providerOptions:ut.optional()}),T({type:R("media"),data:d(),mediaType:d()}),T({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:ut.optional()}),T({type:R("file-url"),url:d(),providerOptions:ut.optional()}),T({type:R("file-id"),fileId:ae([d(),ve(d(),d())]),providerOptions:ut.optional()}),T({type:R("image-data"),data:d(),mediaType:d(),providerOptions:ut.optional()}),T({type:R("image-url"),url:d(),providerOptions:ut.optional()}),T({type:R("image-file-id"),fileId:ae([d(),ve(d(),d())]),providerOptions:ut.optional()}),T({type:R("custom"),providerOptions:ut.optional()})]))})]),Nv=T({type:R("tool-result"),toolCallId:d(),toolName:d(),output:Y8,providerOptions:ut.optional()}),Q8=T({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),X8=T({type:R("tool-approval-response"),approvalId:d(),approved:ge(),reason:d().optional()}),e$=T({role:R("system"),content:d(),providerOptions:ut.optional()}),t$=T({role:R("user"),content:ae([d(),q(ae([Mv,G8,Ov]))]),providerOptions:ut.optional()}),r$=T({role:R("assistant"),content:ae([d(),q(ae([Mv,Ov,W8,K8,Nv,Q8]))]),providerOptions:ut.optional()}),n$=T({role:R("tool"),content:q(ae([Nv,X8])),providerOptions:ut.optional()}),o$=ae([e$,t$,r$,n$]);async function Av(e){if(e.prompt==null&&e.messages==null)throw new Qn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Qn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!io(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Qn({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 Qn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Qn({prompt:e,message:"messages must not be empty"});const r=await dr({value:t,schema:q(o$)});if(!r.success)throw new Qn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function qv(e){if(!Md.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 _e({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,15 +576,15 @@ 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
|
|
580
|
-
`)}function Zv(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=qo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Ao(this.base64Data)),this.uint8ArrayData}},o$=class extends Fv{constructor(e){super(e),this.type="file"}};async function Vv({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 s$={};a8(s$,{array:()=>l$,choice:()=>c$,json:()=>u$,object:()=>i$,text:()=>hl});function a$(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 ra(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await pr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await pr({text:a$(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var hl=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),i$=({schema:e,name:t,description:r})=>{const n=to(e);return{name:"object",responseFormat:Qt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await pr({text:o});if(!a.success)throw new Rn({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 dr({value:a.value,schema:n});if(!i.success)throw new Rn({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 ra(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},l$=({element:e,name:t,description:r})=>{const n=to(e);return{name:"array",responseFormat:Qt(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 pr({text:o});if(!a.success)throw new Rn({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 Rn({message:"No object generated: response did not match schema.",cause:new Qn({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 dr({value:l,schema:n});if(!c.success)throw new Rn({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 ra(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 dr({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])}})}}},c$=({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 pr({text:n});if(!s.success)throw new Rn({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 Rn({message:"No object generated: response did not match schema.",cause:new Qn({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 ra(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(){}}),u$=({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 pr({text:r});if(!o.success)throw new Rn({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 ra(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 Hv({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Bv(e);throw new Dd({toolName:e.toolName})}try{return await Jv({toolCall:e,tools:t})}catch(a){if(r==null||!(Dd.isInstance(a)||Ld.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 to(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new y8({cause:l,originalError:a})}if(i==null)throw a;return await Jv({toolCall:i,tools:t})}}catch(a){const i=await pr({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 Bv(e){const t=e.input.trim()===""?{success:!0,value:{}}:await pr({text:e.input});if(t.success===!1)throw new Ld({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 Jv({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await Bv(e);throw new Dd({toolName:e.toolName,availableTools:Object.keys(t)})}const o=to(n.inputSchema),s=e.input.trim()===""?await dr({value:{},schema:o}):await pr({text:e.input,schema:o});if(s.success===!1)throw new Ld({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 Gv=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 Hd(e){return({steps:t})=>t.length===e}async function Wv({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Bd({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 Qs({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 Qs({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 Qs({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 Kv(...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 d$=Vs({prefix:"aitxt",size:24});async function Yv({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Hd(1),experimental_output:h,output:p=h,experimental_telemetry:f,providerOptions:g,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:m,experimental_download:C,experimental_context:b,experimental_include:k,_internal:{generateId:S=d$}={},experimental_onStart:I,experimental_onStepStart:E,experimental_onToolCallStart:j,experimental_onToolCallFinish:O,onStepFinish:U,onFinish:A,...N}){const G=ul(e),X=Av(),Q=ao(u),K=zd(l),he=vv(l),V=he!=null?new AbortController:void 0,P=Kv(i,K!=null?AbortSignal.timeout(K):void 0,V?.signal),{maxRetries:H,retry:Z}=Dv({maxRetries:a,abortSignal:P}),x=Zd(N),M=xn(c??{},`ai/${_v}`),L=Pv({model:G,telemetry:f,headers:M,settings:{...x,maxRetries:H}}),W={provider:G.provider,modelId:G.modelId},te=await $v({system:n,prompt:o,messages:s}),se=X(f?.integrations);await Rr({event:{model:W,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:x.maxOutputTokens,temperature:x.temperature,topP:x.topP,topK:x.topK,presencePenalty:x.presencePenalty,frequencyPenalty:x.frequencyPenalty,stopSequences:x.stopSequences,seed:x.seed,maxRetries:H,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:i,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[I,se.onStart]});const Se=Mv(f);try{return await ta({name:"ai.generateText",attributes:Fr({telemetry:f,attributes:{...ea({operationId:"ai.generateText",telemetry:f}),...L,"ai.model.provider":G.provider,"ai.model.id":G.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:Se,fn:async z=>{var F,Y,ee,ue,Ee,He,ot,ft,et,$,ne,Le,_t;const Ht=te.messages,We=[],{approvedToolApprovals:un,deniedToolApprovals:ht}=Uv({messages:Ht}),hr=un.filter(at=>!at.toolCall.providerExecuted);if(ht.length>0||hr.length>0){const at=await Qv({toolCalls:hr.map(Ie=>Ie.toolCall),tools:t,tracer:Se,telemetry:f,messages:Ht,abortSignal:P,experimental_context:b,stepNumber:0,model:W,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[O,se.onToolCallFinish]}),Et=[];for(const Ie of at){const Lt=await Qs({toolCallId:Ie.toolCallId,input:Ie.input,tool:t?.[Ie.toolName],output:Ie.type==="tool-result"?Ie.output:Ie.error,errorMode:Ie.type==="tool-error"?"text":"none"});Et.push({type:"tool-result",toolCallId:Ie.toolCallId,toolName:Ie.toolName,output:Lt})}for(const Ie of ht)Et.push({type:"tool-result",toolCallId:Ie.toolCall.toolCallId,toolName:Ie.toolCall.toolName,output:{type:"execution-denied",reason:Ie.approvalResponse.reason,...Ie.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ie.approvalResponse.approvalId}}}}});We.push({role:"tool",content:Et})}const Pn=[...un,...ht].filter(at=>at.toolCall.providerExecuted);Pn.length>0&&We.push({role:"tool",content:Pn.map(at=>({type:"tool-approval-response",approvalId:at.approvalResponse.approvalId,approved:at.approvalResponse.approved,reason:at.approvalResponse.reason,providerExecuted:!0}))});const mt=Zd(N);let $e,st=[],xe=[];const Qe=[],Or=new Map;do{const at=he!=null?setTimeout(()=>V.abort(),he):void 0;try{const Et=[...Ht,...We],Ie=await _?.({model:G,steps:Qe,stepNumber:Qe.length,messages:Et,experimental_context:b}),Lt=ul((F=Ie?.model)!=null?F:G),gt={provider:Lt.provider,modelId:Lt.modelId},xt=await kv({prompt:{system:(Y=Ie?.system)!=null?Y:te.system,messages:(ee=Ie?.messages)!=null?ee:Et},supportedUrls:await Lt.supportedUrls,download:C});b=(ue=Ie?.experimental_context)!=null?ue:b;const dt=(Ee=Ie?.activeTools)!=null?Ee:y,{toolChoice:dn,tools:Vo}=await Sv({tools:t,toolChoice:(He=Ie?.toolChoice)!=null?He:r,activeTools:dt}),xl=(ot=Ie?.messages)!=null?ot:Et,$l=(ft=Ie?.system)!=null?ft:te.system,ua=pl(g,Ie?.providerOptions);await Rr({event:{stepNumber:Qe.length,model:gt,system:$l,messages:xl,tools:t,toolChoice:dn,activeTools:dt,steps:[...Qe],providerOptions:ua,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[E,se.onStepStart]}),$e=await Z(()=>{var Ae;return ta({name:"ai.generateText.doGenerate",attributes:Fr({telemetry:f,attributes:{...ea({operationId:"ai.generateText.doGenerate",telemetry:f}),...L,"ai.model.provider":Lt.provider,"ai.model.id":Lt.modelId,"ai.prompt.messages":{input:()=>Nv(xt)},"ai.prompt.tools":{input:()=>Vo?.map(jt=>JSON.stringify(jt))},"ai.prompt.toolChoice":{input:()=>dn!=null?JSON.stringify(dn):void 0},"gen_ai.system":Lt.provider,"gen_ai.request.model":Lt.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":(Ae=N.temperature)!=null?Ae:void 0,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:Se,fn:async jt=>{var On,pn,Pl,Ml,ha,Ol,ma,Ho;const pt=await Lt.doGenerate({...mt,tools:Vo,toolChoice:dn,responseFormat:await p?.responseFormat,prompt:xt,providerOptions:ua,abortSignal:P,headers:M}),fn={id:(pn=(On=pt.response)==null?void 0:On.id)!=null?pn:S(),timestamp:(Ml=(Pl=pt.response)==null?void 0:Pl.timestamp)!=null?Ml:new Date,modelId:(Ol=(ha=pt.response)==null?void 0:ha.modelId)!=null?Ol:Lt.modelId,headers:(ma=pt.response)==null?void 0:ma.headers,body:(Ho=pt.response)==null?void 0:Ho.body};return jt.setAttributes(await Fr({telemetry:f,attributes:{"ai.response.finishReason":pt.finishReason.unified,"ai.response.text":{output:()=>Zv(pt.content)},"ai.response.reasoning":{output:()=>zv(pt.content)},"ai.response.toolCalls":{output:()=>{const Nl=Xv(pt.content);return Nl==null?void 0:JSON.stringify(Nl)}},"ai.response.id":fn.id,"ai.response.model":fn.modelId,"ai.response.timestamp":fn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(pt.providerMetadata),"ai.usage.promptTokens":pt.usage.inputTokens.total,"ai.usage.completionTokens":pt.usage.outputTokens.total,"gen_ai.response.finish_reasons":[pt.finishReason.unified],"gen_ai.response.id":fn.id,"gen_ai.response.model":fn.modelId,"gen_ai.usage.input_tokens":pt.usage.inputTokens.total,"gen_ai.usage.output_tokens":pt.usage.outputTokens.total}})),{...pt,response:fn}}})});const mr=await Promise.all($e.content.filter(Ae=>Ae.type==="tool-call").map(Ae=>Hv({toolCall:Ae,tools:t,repairToolCall:m,system:n,messages:Et}))),da={};for(const Ae of mr){if(Ae.invalid)continue;const jt=t?.[Ae.toolName];jt!=null&&(jt?.onInputAvailable!=null&&await jt.onInputAvailable({input:Ae.input,toolCallId:Ae.toolCallId,messages:Et,abortSignal:P,experimental_context:b}),await Vv({tool:jt,toolCall:Ae,messages:Et,experimental_context:b})&&(da[Ae.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Ae}))}const Rl=mr.filter(Ae=>Ae.invalid&&Ae.dynamic);xe=[];for(const Ae of Rl)xe.push({type:"tool-error",toolCallId:Ae.toolCallId,toolName:Ae.toolName,input:Ae.input,error:md(Ae.error),dynamic:!0});st=mr.filter(Ae=>!Ae.providerExecuted),t!=null&&xe.push(...await Qv({toolCalls:st.filter(Ae=>!Ae.invalid&&da[Ae.toolCallId]==null),tools:t,tracer:Se,telemetry:f,messages:Et,abortSignal:P,experimental_context:b,stepNumber:Qe.length,model:gt,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[O,se.onToolCallFinish]}));for(const Ae of mr){if(!Ae.providerExecuted)continue;const jt=t?.[Ae.toolName];jt?.type==="provider"&&jt.supportsDeferredResults&&($e.content.some(pn=>pn.type==="tool-result"&&pn.toolCallId===Ae.toolCallId)||Or.set(Ae.toolCallId,{toolName:Ae.toolName}))}for(const Ae of $e.content)Ae.type==="tool-result"&&Or.delete(Ae.toolCallId);const pa=f$({content:$e.content,toolCalls:mr,toolOutputs:xe,toolApprovalRequests:Object.values(da),tools:t});We.push(...await Bd({content:pa,tools:t}));const Mn=(et=k?.requestBody)==null||et?($=$e.request)!=null?$:{}:{...$e.request,body:void 0},wt={...$e.response,messages:structuredClone(We),body:(ne=k?.responseBody)==null||ne?(Le=$e.response)==null?void 0:Le.body:void 0},Vr=Qe.length,fa=new Gv({stepNumber:Vr,model:gt,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b,content:pa,finishReason:$e.finishReason.unified,rawFinishReason:$e.finishReason.raw,usage:qv($e.usage),warnings:$e.warnings,providerMetadata:$e.providerMetadata,request:Mn,response:wt});Ud({warnings:(_t=$e.warnings)!=null?_t:[],provider:gt.provider,model:gt.modelId}),Qe.push(fa),await Rr({event:fa,callbacks:[U,se.onStepFinish]})}finally{at!=null&&clearTimeout(at)}}while((st.length>0&&xe.length===st.length||Or.size>0)&&!await Wv({stopConditions:Q,steps:Qe}));z.setAttributes(await Fr({telemetry:f,attributes:{"ai.response.finishReason":$e.finishReason.unified,"ai.response.text":{output:()=>Zv($e.content)},"ai.response.reasoning":{output:()=>zv($e.content)},"ai.response.toolCalls":{output:()=>{const at=Xv($e.content);return at==null?void 0:JSON.stringify(at)}},"ai.response.providerMetadata":JSON.stringify($e.providerMetadata),"ai.usage.promptTokens":$e.usage.inputTokens.total,"ai.usage.completionTokens":$e.usage.outputTokens.total}}));const re=Qe[Qe.length-1],Xe=Qe.reduce((at,Et)=>Lv(at,Et.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await Rr({event:{stepNumber:re.stepNumber,model:re.model,functionId:re.functionId,metadata:re.metadata,experimental_context:re.experimental_context,finishReason:re.finishReason,rawFinishReason:re.rawFinishReason,usage:re.usage,content:re.content,text:re.text,reasoningText:re.reasoningText,reasoning:re.reasoning,files:re.files,sources:re.sources,toolCalls:re.toolCalls,staticToolCalls:re.staticToolCalls,dynamicToolCalls:re.dynamicToolCalls,toolResults:re.toolResults,staticToolResults:re.staticToolResults,dynamicToolResults:re.dynamicToolResults,request:re.request,response:re.response,warnings:re.warnings,providerMetadata:re.providerMetadata,steps:Qe,totalUsage:Xe},callbacks:[A,se.onFinish]});let Nr;return re.finishReason==="stop"&&(Nr=await(p??hl()).parseCompleteOutput({text:re.text},{response:re.response,usage:re.usage,finishReason:re.finishReason})),new p$({steps:Qe,totalUsage:Xe,output:Nr})}})}catch(z){throw Rv(z)}}async function Qv({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=>Vd({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 p$=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 Qy;return this._output}};function Xv(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 f$({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 jd({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function ml(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 h$({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ml(r,{"content-type":"text/plain; charset=utf-8"})})}function e_({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 m$({response:e,status:t,statusText:r,headers:n,textStream:o}){e_({response:e,status:t,statusText:r,headers:Object.fromEntries(ml(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var t_=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
579
|
+
`),{name:"GatewayAuthenticationError"})}function ra({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 Lv({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=Gd(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 s$={startSpan(){return hl},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(hl);if(typeof r=="function")return r(hl);if(typeof n=="function")return n(hl)}},hl={spanContext(){return a$},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}},a$={traceId:"",spanId:"",traceFlags:0};function jv({isEnabled:e=!1,tracer:t}={}){return e?t||u8.getTracer("ai"):s$}async function na({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=Ny.active();try{const i=await Ny.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{Dv(s,i)}finally{s.end()}throw i}})}function Dv(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:pl.ERROR,message:t.message})):e.setStatus({code:pl.ERROR})}async function Fr({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 Uv(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?F8(r.data):r.data}:r)})))}function i$(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function zv(){const e=i$();return t=>{const r=io(t),n=[...e,...r];function o(s){const a=n.map(s).filter(Boolean);return async i=>{for(const l of a)try{await l(i)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function Zv(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:Pr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Kd(){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 Fv(e,t){var r,n,o,s,a,i,l,c,u,h;return{inputTokens:Pr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Pr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Pr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:Pr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:Pr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Pr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Pr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(h=t.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Pr(e.totalTokens,t.totalTokens),reasoningTokens:Pr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Pr(e.cachedInputTokens,t.cachedInputTokens)}}function Pr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ml(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]=ml(s,o):r[n]=o}return r}function l$({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 c$=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Vv(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Vv(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(eo(a)||t===0)throw a;const i=kd(a),l=[...s,a],c=l.length;if(c>t)throw new wv({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&ct.isInstance(a)&&a.isRetryable===!0&&c<=t)return await V5(l$({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),Vv(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new wv({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Hv({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:c$({maxRetries:r,abortSignal:t})}}function Bv({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 m8({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 h={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(h):a.push(h)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function gl(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Yd({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:m}=e,v=t?.[p];if(v?.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 na({name:"ai.toolCall",attributes:Fr({telemetry:n,attributes:{...ra({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(m)}}}),tracer:r,fn:async w=>{let _;await Rr({event:y,callbacks:u});const g=gl();try{const b=nx({execute:v.execute.bind(v),input:m,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:a}});for await(const k of b)k.type==="preliminary"?c?.({...e,type:"tool-result",output:k.output,preliminary:!0}):_=k.output}catch(b){const k=gl()-g;return await Rr({event:{...y,success:!1,error:b,durationMs:k},callbacks:h}),Dv(w,b),{type:"tool-error",toolCallId:f,toolName:p,input:m,error:b,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const C=gl()-g;await Rr({event:{...y,success:!0,output:_,durationMs:C},callbacks:h});try{w.setAttributes(await Fr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(_)}}}))}catch{}return{type:"tool-result",toolCallId:f,toolName:p,input:m,output:_,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function Jv(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
|
|
580
|
+
`)}function Gv(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Wv=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=Lo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=qo(this.base64Data)),this.uint8ArrayData}},u$=class extends Wv{constructor(e){super(e),this.type="file"}};async function Kv({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 d$={};p8(d$,{array:()=>h$,choice:()=>m$,json:()=>g$,object:()=>f$,text:()=>yl});function p$(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 oa(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await pr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await pr({text:p$(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var yl=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),f$=({schema:e,name:t,description:r})=>{const n=ro(e);return{name:"object",responseFormat:Qt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await pr({text:o});if(!a.success)throw new Pn({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 dr({value:a.value,schema:n});if(!i.success)throw new Pn({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 oa(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},h$=({element:e,name:t,description:r})=>{const n=ro(e);return{name:"array",responseFormat:Qt(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 pr({text:o});if(!a.success)throw new Pn({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 Pn({message:"No object generated: response did not match schema.",cause:new Xn({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 dr({value:l,schema:n});if(!c.success)throw new Pn({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 oa(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 dr({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])}})}}},m$=({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 pr({text:n});if(!s.success)throw new Pn({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 Pn({message:"No object generated: response did not match schema.",cause:new Xn({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 oa(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(){}}),g$=({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 pr({text:r});if(!o.success)throw new Pn({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 oa(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 Yv({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Qv(e);throw new Bd({toolName:e.toolName})}try{return await Xv({toolCall:e,tools:t})}catch(a){if(r==null||!(Bd.isInstance(a)||Vd.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 ro(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new T8({cause:l,originalError:a})}if(i==null)throw a;return await Xv({toolCall:i,tools:t})}}catch(a){const i=await pr({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 Qv(e){const t=e.input.trim()===""?{success:!0,value:{}}:await pr({text:e.input});if(t.success===!1)throw new Vd({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 Xv({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await Qv(e);throw new Bd({toolName:e.toolName,availableTools:Object.keys(t)})}const o=ro(n.inputSchema),s=e.input.trim()===""?await dr({value:{},schema:o}):await pr({text:e.input,schema:o});if(s.success===!1)throw new Vd({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 e_=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 Qd(e){return({steps:t})=>t.length===e}async function t_({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Xd({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 ea({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 ea({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 ea({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 r_(...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 y$=Bs({prefix:"aitxt",size:24});async function n_({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Qd(1),experimental_output:h,output:p=h,experimental_telemetry:f,providerOptions:m,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:g,experimental_download:C,experimental_context:b,experimental_include:k,_internal:{generateId:S=y$}={},experimental_onStart:I,experimental_onStepStart:x,experimental_onToolCallStart:j,experimental_onToolCallFinish:O,onStepFinish:U,onFinish:A,...N}){const G=fl(e),X=zv(),Q=io(u),K=Gd(l),he=Cv(l),V=he!=null?new AbortController:void 0,P=r_(i,K!=null?AbortSignal.timeout(K):void 0,V?.signal),{maxRetries:H,retry:Z}=Hv({maxRetries:a,abortSignal:P}),E=Wd(N),M=$n(c??{},`ai/${Sv}`),L=Lv({model:G,telemetry:f,headers:M,settings:{...E,maxRetries:H}}),W={provider:G.provider,modelId:G.modelId},te=await Av({system:n,prompt:o,messages:s}),se=X(f?.integrations);await Rr({event:{model:W,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:E.maxOutputTokens,temperature:E.temperature,topP:E.topP,topK:E.topK,presencePenalty:E.presencePenalty,frequencyPenalty:E.frequencyPenalty,stopSequences:E.stopSequences,seed:E.seed,maxRetries:H,timeout:l,headers:c,providerOptions:m,stopWhen:u,output:p,abortSignal:i,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[I,se.onStart]});const Se=jv(f);try{return await na({name:"ai.generateText",attributes:Fr({telemetry:f,attributes:{...ra({operationId:"ai.generateText",telemetry:f}),...L,"ai.model.provider":G.provider,"ai.model.id":G.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:Se,fn:async z=>{var F,Y,ee,ue,xe,He,ot,ft,et,$,ne,Le,_t;const Ht=te.messages,We=[],{approvedToolApprovals:dn,deniedToolApprovals:ht}=Bv({messages:Ht}),hr=dn.filter(at=>!at.toolCall.providerExecuted);if(ht.length>0||hr.length>0){const at=await o_({toolCalls:hr.map(Ie=>Ie.toolCall),tools:t,tracer:Se,telemetry:f,messages:Ht,abortSignal:P,experimental_context:b,stepNumber:0,model:W,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[O,se.onToolCallFinish]}),xt=[];for(const Ie of at){const Lt=await ea({toolCallId:Ie.toolCallId,input:Ie.input,tool:t?.[Ie.toolName],output:Ie.type==="tool-result"?Ie.output:Ie.error,errorMode:Ie.type==="tool-error"?"text":"none"});xt.push({type:"tool-result",toolCallId:Ie.toolCallId,toolName:Ie.toolName,output:Lt})}for(const Ie of ht)xt.push({type:"tool-result",toolCallId:Ie.toolCall.toolCallId,toolName:Ie.toolCall.toolName,output:{type:"execution-denied",reason:Ie.approvalResponse.reason,...Ie.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ie.approvalResponse.approvalId}}}}});We.push({role:"tool",content:xt})}const Mn=[...dn,...ht].filter(at=>at.toolCall.providerExecuted);Mn.length>0&&We.push({role:"tool",content:Mn.map(at=>({type:"tool-approval-response",approvalId:at.approvalResponse.approvalId,approved:at.approvalResponse.approved,reason:at.approvalResponse.reason,providerExecuted:!0}))});const mt=Wd(N);let $e,st=[],Ee=[];const Qe=[],Or=new Map;do{const at=he!=null?setTimeout(()=>V.abort(),he):void 0;try{const xt=[...Ht,...We],Ie=await _?.({model:G,steps:Qe,stepNumber:Qe.length,messages:xt,experimental_context:b}),Lt=fl((F=Ie?.model)!=null?F:G),gt={provider:Lt.provider,modelId:Lt.modelId},Et=await Ev({prompt:{system:(Y=Ie?.system)!=null?Y:te.system,messages:(ee=Ie?.messages)!=null?ee:xt},supportedUrls:await Lt.supportedUrls,download:C});b=(ue=Ie?.experimental_context)!=null?ue:b;const dt=(xe=Ie?.activeTools)!=null?xe:y,{toolChoice:pn,tools:Bo}=await Pv({tools:t,toolChoice:(He=Ie?.toolChoice)!=null?He:r,activeTools:dt}),Al=(ot=Ie?.messages)!=null?ot:xt,ql=(ft=Ie?.system)!=null?ft:te.system,fa=ml(m,Ie?.providerOptions);await Rr({event:{stepNumber:Qe.length,model:gt,system:ql,messages:Al,tools:t,toolChoice:pn,activeTools:dt,steps:[...Qe],providerOptions:fa,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[x,se.onStepStart]}),$e=await Z(()=>{var Ae;return na({name:"ai.generateText.doGenerate",attributes:Fr({telemetry:f,attributes:{...ra({operationId:"ai.generateText.doGenerate",telemetry:f}),...L,"ai.model.provider":Lt.provider,"ai.model.id":Lt.modelId,"ai.prompt.messages":{input:()=>Uv(Et)},"ai.prompt.tools":{input:()=>Bo?.map(jt=>JSON.stringify(jt))},"ai.prompt.toolChoice":{input:()=>pn!=null?JSON.stringify(pn):void 0},"gen_ai.system":Lt.provider,"gen_ai.request.model":Lt.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":(Ae=N.temperature)!=null?Ae:void 0,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:Se,fn:async jt=>{var Nn,fn,jl,Dl,ya,Ul,va,Jo;const pt=await Lt.doGenerate({...mt,tools:Bo,toolChoice:pn,responseFormat:await p?.responseFormat,prompt:Et,providerOptions:fa,abortSignal:P,headers:M}),hn={id:(fn=(Nn=pt.response)==null?void 0:Nn.id)!=null?fn:S(),timestamp:(Dl=(jl=pt.response)==null?void 0:jl.timestamp)!=null?Dl:new Date,modelId:(Ul=(ya=pt.response)==null?void 0:ya.modelId)!=null?Ul:Lt.modelId,headers:(va=pt.response)==null?void 0:va.headers,body:(Jo=pt.response)==null?void 0:Jo.body};return jt.setAttributes(await Fr({telemetry:f,attributes:{"ai.response.finishReason":pt.finishReason.unified,"ai.response.text":{output:()=>Gv(pt.content)},"ai.response.reasoning":{output:()=>Jv(pt.content)},"ai.response.toolCalls":{output:()=>{const zl=s_(pt.content);return zl==null?void 0:JSON.stringify(zl)}},"ai.response.id":hn.id,"ai.response.model":hn.modelId,"ai.response.timestamp":hn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(pt.providerMetadata),"ai.usage.promptTokens":pt.usage.inputTokens.total,"ai.usage.completionTokens":pt.usage.outputTokens.total,"gen_ai.response.finish_reasons":[pt.finishReason.unified],"gen_ai.response.id":hn.id,"gen_ai.response.model":hn.modelId,"gen_ai.usage.input_tokens":pt.usage.inputTokens.total,"gen_ai.usage.output_tokens":pt.usage.outputTokens.total}})),{...pt,response:hn}}})});const mr=await Promise.all($e.content.filter(Ae=>Ae.type==="tool-call").map(Ae=>Yv({toolCall:Ae,tools:t,repairToolCall:g,system:n,messages:xt}))),ha={};for(const Ae of mr){if(Ae.invalid)continue;const jt=t?.[Ae.toolName];jt!=null&&(jt?.onInputAvailable!=null&&await jt.onInputAvailable({input:Ae.input,toolCallId:Ae.toolCallId,messages:xt,abortSignal:P,experimental_context:b}),await Kv({tool:jt,toolCall:Ae,messages:xt,experimental_context:b})&&(ha[Ae.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Ae}))}const Ll=mr.filter(Ae=>Ae.invalid&&Ae.dynamic);Ee=[];for(const Ae of Ll)Ee.push({type:"tool-error",toolCallId:Ae.toolCallId,toolName:Ae.toolName,input:Ae.input,error:kd(Ae.error),dynamic:!0});st=mr.filter(Ae=>!Ae.providerExecuted),t!=null&&Ee.push(...await o_({toolCalls:st.filter(Ae=>!Ae.invalid&&ha[Ae.toolCallId]==null),tools:t,tracer:Se,telemetry:f,messages:xt,abortSignal:P,experimental_context:b,stepNumber:Qe.length,model:gt,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[O,se.onToolCallFinish]}));for(const Ae of mr){if(!Ae.providerExecuted)continue;const jt=t?.[Ae.toolName];jt?.type==="provider"&&jt.supportsDeferredResults&&($e.content.some(fn=>fn.type==="tool-result"&&fn.toolCallId===Ae.toolCallId)||Or.set(Ae.toolCallId,{toolName:Ae.toolName}))}for(const Ae of $e.content)Ae.type==="tool-result"&&Or.delete(Ae.toolCallId);const ma=_$({content:$e.content,toolCalls:mr,toolOutputs:Ee,toolApprovalRequests:Object.values(ha),tools:t});We.push(...await Xd({content:ma,tools:t}));const On=(et=k?.requestBody)==null||et?($=$e.request)!=null?$:{}:{...$e.request,body:void 0},wt={...$e.response,messages:structuredClone(We),body:(ne=k?.responseBody)==null||ne?(Le=$e.response)==null?void 0:Le.body:void 0},Vr=Qe.length,ga=new e_({stepNumber:Vr,model:gt,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b,content:ma,finishReason:$e.finishReason.unified,rawFinishReason:$e.finishReason.raw,usage:Zv($e.usage),warnings:$e.warnings,providerMetadata:$e.providerMetadata,request:On,response:wt});Jd({warnings:(_t=$e.warnings)!=null?_t:[],provider:gt.provider,model:gt.modelId}),Qe.push(ga),await Rr({event:ga,callbacks:[U,se.onStepFinish]})}finally{at!=null&&clearTimeout(at)}}while((st.length>0&&Ee.length===st.length||Or.size>0)&&!await t_({stopConditions:Q,steps:Qe}));z.setAttributes(await Fr({telemetry:f,attributes:{"ai.response.finishReason":$e.finishReason.unified,"ai.response.text":{output:()=>Gv($e.content)},"ai.response.reasoning":{output:()=>Jv($e.content)},"ai.response.toolCalls":{output:()=>{const at=s_($e.content);return at==null?void 0:JSON.stringify(at)}},"ai.response.providerMetadata":JSON.stringify($e.providerMetadata),"ai.usage.promptTokens":$e.usage.inputTokens.total,"ai.usage.completionTokens":$e.usage.outputTokens.total}}));const re=Qe[Qe.length-1],Xe=Qe.reduce((at,xt)=>Fv(at,xt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await Rr({event:{stepNumber:re.stepNumber,model:re.model,functionId:re.functionId,metadata:re.metadata,experimental_context:re.experimental_context,finishReason:re.finishReason,rawFinishReason:re.rawFinishReason,usage:re.usage,content:re.content,text:re.text,reasoningText:re.reasoningText,reasoning:re.reasoning,files:re.files,sources:re.sources,toolCalls:re.toolCalls,staticToolCalls:re.staticToolCalls,dynamicToolCalls:re.dynamicToolCalls,toolResults:re.toolResults,staticToolResults:re.staticToolResults,dynamicToolResults:re.dynamicToolResults,request:re.request,response:re.response,warnings:re.warnings,providerMetadata:re.providerMetadata,steps:Qe,totalUsage:Xe},callbacks:[A,se.onFinish]});let Nr;return re.finishReason==="stop"&&(Nr=await(p??yl()).parseCompleteOutput({text:re.text},{response:re.response,usage:re.usage,finishReason:re.finishReason})),new v$({steps:Qe,totalUsage:Xe,output:Nr})}})}catch(z){throw qv(z)}}async function o_({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=>Yd({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 v$=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 ov;return this._output}};function s_(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 _$({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 Wv(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 vl(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 w$({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:vl(r,{"content-type":"text/plain; charset=utf-8"})})}function a_({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 b$({response:e,status:t,statusText:r,headers:n,textStream:o}){a_({response:e,status:t,statusText:r,headers:Object.fromEntries(vl(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var i_=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
|
-
`)}})}},r_={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function g$({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new t_);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ml(r,r_)})}function y$({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 v$(e){return e.type.startsWith("data-")}function Jd(e){return e.type.startsWith("tool-")}function _$(e){return e.type==="dynamic-tool"}function n_(e){return Jd(e)||_$(e)}function o_(e){return e.type.split("-").slice(1).join("-")}function w$({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function b$({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 v(m){const b=c.message.parts.filter(n_).find(k=>k.toolCallId===m);if(b==null)throw new Uo({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return b}function y(m){var C;const b=c.message.parts.find(I=>Jd(I)&&I.toolCallId===m.toolCallId),k=m,S=b;b!=null?(b.state=m.state,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=k.rawInput,S.preliminary=k.preliminary,m.title!==void 0&&(S.title=m.title),S.providerExecuted=(C=k.providerExecuted)!=null?C:b.providerExecuted,k.providerMetadata!=null&&(b.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(m){var C,b;const k=c.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===m.toolCallId),S=m,I=k;k!=null?(k.state=m.state,I.toolName=m.toolName,I.input=S.input,I.output=S.output,I.errorText=S.errorText,I.rawInput=(C=S.rawInput)!=null?C:I.rawInput,I.preliminary=S.preliminary,m.title!==void 0&&(I.title=m.title),I.providerExecuted=(b=S.providerExecuted)!=null?b:k.providerExecuted,S.providerMetadata!=null&&(k.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 _(m){if(m!=null){const C=c.message.metadata!=null?pl(c.message.metadata,m):m;t!=null&&await St({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 Uo({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 Uo({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 Uo({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 Uo({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,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}),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(Jd);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 Uo({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 ra(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(n_).find(b=>b.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=v(i.toolCallId);m.state="approval-requested",m.approval={id:i.approvalId},u();break}case"tool-output-denied":{const m=v(i.toolCallId);m.state="output-denied",u();break}case"tool-output-available":{const m=v(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:o_(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=v(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:o_(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 _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(v$(i)){if(r?.[i.type]!=null){const b=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),k=b>=0?b:c.message.parts.length;await St({value:i.data,schema:r[i.type],context:{field:`message.parts[${k}].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(b=>m.type===b.type&&m.id===b.id):void 0;C!=null?C.data=m.data:c.message.parts.push(m),a?.(m),u()}}l.enqueue(i)})}}))}function k$({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,v){if(g.type==="start"){const y=g;y.messageId==null&&e!=null&&(y.messageId=e)}g.type==="abort"&&(i=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=w$({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(v){o(v)}};return b$({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(g,v){g.type==="finish-step"&&await f(),v.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 t_);if(s){const[i,l]=a.tee();a=i,s({stream:l})}e_({response:e,status:t,statusText:r,headers:Object.fromEntries(ml(n,r_).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function na(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 C$({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 s_(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function S$(){let e=[],t=null,r=!1,n=s_();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=s_(),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 I$({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 v=new ReadableStream({start(S){g=S}}),y=new Set,w=new Map,_=new Map;let m=!1,C;function b(){m&&y.size===0&&(C!=null&&g.enqueue(C),g.close())}const k=new TransformStream({async transform(S,I){const E=S.type;switch(E){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":{I.enqueue(S);break}case"file":{I.enqueue({type:"file",file:new o$({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{C={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:qv(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const j=_.get(S.toolCallId);if(j==null){g.enqueue({type:"error",error:new jd({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}I.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:j});break}case"tool-call":{try{const j=await Hv({toolCall:S,tools:e,repairToolCall:i,system:o,messages:s});if(_.set(j.toolCallId,j),I.enqueue(j),j.invalid){g.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:md(j.error),dynamic:!0,title:j.title});break}const O=e?.[j.toolName];if(O==null)break;if(O.onInputAvailable!=null&&await O.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await Vv({tool:O,toolCall:j,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),O.execute!=null&&j.providerExecuted!==!0){const U=c();y.add(U),Vd({toolCall:j,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(U),b()})}}catch(j){g.enqueue({type:"error",error:j})}break}case"tool-result":{const j=S.toolName;S.isError?g.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):I.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const j=E;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){m=!0,b()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){}})),v.pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){S.close()}}))])}})}var E$=Vs({prefix:"aitxt",size:24});function Gd({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Hd(1),experimental_output:h,output:p=h,experimental_telemetry:f,prepareStep:g,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:m,experimental_download:C,includeRawChunks:b=!1,onChunk:k,onError:S=({error:V})=>{console.error(V)},onFinish:I,onAbort:E,onStepFinish:j,experimental_onStart:O,experimental_onStepStart:U,experimental_onToolCallStart:A,experimental_onToolCallFinish:N,experimental_context:G,experimental_include:X,_internal:{now:Q=fl,generateId:K=E$}={},...he}){const V=zd(l),P=vv(l),H=$8(l),Z=P!=null?new AbortController:void 0,x=H!=null?new AbortController:void 0;return new $$({model:ul(e),telemetry:f,headers:c,settings:he,maxRetries:a,abortSignal:Kv(i,V!=null?AbortSignal.timeout(V):void 0,Z?.signal,x?.signal),stepTimeoutMs:P,stepAbortController:Z,chunkTimeoutMs:H,chunkAbortController:x,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:ao(m),activeTools:w,repairToolCall:_,stopConditions:ao(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:k,onError:S,onFinish:I,onAbort:E,onStepFinish:j,onStart:O,onStepStart:U,onToolCallStart:A,onToolCallFinish:N,now:Q,generateId:K,experimental_context:G,download:C,include:X})}function x$(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 $$=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:v,activeTools:y,repairToolCall:w,stopConditions:_,output:m,providerOptions:C,prepareStep:b,includeRawChunks:k,now:S,generateId:I,timeout:E,stopWhen:j,originalAbortSignal:O,onChunk:U,onError:A,onFinish:N,onAbort:G,onStepFinish:X,onStart:Q,onStepStart:K,onToolCallStart:he,onToolCallFinish:V,experimental_context:P,download:H,include:Z}){this._totalUsage=new Fs,this._finishReason=new Fs,this._rawFinishReason=new Fs,this._steps=new Fs,this.outputSpecification=m,this.includeRawChunks=k,this.tools=f;const M=Av()(t?.integrations);let L,W=[];const te=[];let se,Se,z,F={},Y=[];const ee=[],ue=new Map;let Ee,He={},ot={};const ft=new TransformStream({async transform(mt,$e){var st,xe,Qe,Or;$e.enqueue(mt);const{part:re}=mt;if((re.type==="text-delta"||re.type==="reasoning-delta"||re.type==="source"||re.type==="tool-call"||re.type==="tool-result"||re.type==="tool-input-start"||re.type==="tool-input-delta"||re.type==="raw")&&await U?.({chunk:re}),re.type==="error"&&await A({error:Rv(re.error)}),re.type==="text-start"&&(He[re.id]={type:"text",text:"",providerMetadata:re.providerMetadata},W.push(He[re.id])),re.type==="text-delta"){const Xe=He[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Xe.text+=re.text,Xe.providerMetadata=(st=re.providerMetadata)!=null?st:Xe.providerMetadata}if(re.type==="text-end"){const Xe=He[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Xe.providerMetadata=(xe=re.providerMetadata)!=null?xe:Xe.providerMetadata,delete He[re.id]}if(re.type==="reasoning-start"&&(ot[re.id]={type:"reasoning",text:"",providerMetadata:re.providerMetadata},W.push(ot[re.id])),re.type==="reasoning-delta"){const Xe=ot[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Xe.text+=re.text,Xe.providerMetadata=(Qe=re.providerMetadata)!=null?Qe:Xe.providerMetadata}if(re.type==="reasoning-end"){const Xe=ot[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Xe.providerMetadata=(Or=re.providerMetadata)!=null?Or:Xe.providerMetadata,delete ot[re.id]}if(re.type==="file"&&W.push({type:"file",file:re.file,...re.providerMetadata!=null?{providerMetadata:re.providerMetadata}:{}}),re.type==="source"&&W.push(re),re.type==="tool-call"&&W.push(re),re.type==="tool-result"&&!re.preliminary&&W.push(re),re.type==="tool-approval-request"&&W.push(re),re.type==="tool-error"&&W.push(re),re.type==="start-step"&&(W=[],ot={},He={},F=re.request,Y=re.warnings),re.type==="finish-step"){const Xe=await Bd({content:W,tools:f}),Nr=new Gv({stepNumber:ee.length,model:hr,...Pn,experimental_context:P,content:W,finishReason:re.finishReason,rawFinishReason:re.rawFinishReason,usage:re.usage,warnings:Y,request:F,response:{...re.response,messages:[...te,...Xe]},providerMetadata:re.providerMetadata});await Rr({event:Nr,callbacks:[X,M.onStepFinish]}),Ud({warnings:Y,provider:hr.provider,model:hr.modelId}),ee.push(Nr),te.push(...Xe),L.resolve()}re.type==="finish"&&(z=re.totalUsage,se=re.finishReason,Se=re.rawFinishReason)},async flush(mt){try{if(ee.length===0){const Qe=s?.aborted?s.reason:new Qy({message:"No output generated. Check the stream for errors."});ht._finishReason.reject(Qe),ht._rawFinishReason.reject(Qe),ht._totalUsage.reject(Qe),ht._steps.reject(Qe);return}const $e=se??"other",st=z??Fd();ht._finishReason.resolve($e),ht._rawFinishReason.resolve(Se),ht._totalUsage.resolve(st),ht._steps.resolve(ee);const xe=ee[ee.length-1];await Rr({event:{stepNumber:xe.stepNumber,model:xe.model,functionId:xe.functionId,metadata:xe.metadata,experimental_context:xe.experimental_context,finishReason:xe.finishReason,rawFinishReason:xe.rawFinishReason,totalUsage:st,usage:xe.usage,content:xe.content,text:xe.text,reasoningText:xe.reasoningText,reasoning:xe.reasoning,files:xe.files,sources:xe.sources,toolCalls:xe.toolCalls,staticToolCalls:xe.staticToolCalls,dynamicToolCalls:xe.dynamicToolCalls,toolResults:xe.toolResults,staticToolResults:xe.staticToolResults,dynamicToolResults:xe.dynamicToolResults,request:xe.request,response:xe.response,warnings:xe.warnings,providerMetadata:xe.providerMetadata,steps:ee},callbacks:[N,M.onFinish]}),Ee.setAttributes(await Fr({telemetry:t,attributes:{"ai.response.finishReason":$e,"ai.response.text":{output:()=>xe.text},"ai.response.reasoning":{output:()=>xe.reasoningText},"ai.response.toolCalls":{output:()=>{var Qe;return(Qe=xe.toolCalls)!=null&&Qe.length?JSON.stringify(xe.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(xe.providerMetadata),"ai.usage.inputTokens":st.inputTokens,"ai.usage.outputTokens":st.outputTokens,"ai.usage.totalTokens":st.totalTokens,"ai.usage.reasoningTokens":st.reasoningTokens,"ai.usage.cachedInputTokens":st.cachedInputTokens}}))}catch($e){mt.error($e)}finally{Ee.end()}}}),et=S$();this.addStream=et.addStream,this.closeStream=et.close;const $=et.stream.getReader();let ne=new ReadableStream({async start(mt){mt.enqueue({type:"start"})},async pull(mt){function $e(){G?.({steps:ee}),mt.enqueue({type:"abort",...s?.reason!==void 0?{reason:Kn(s.reason)}:{}}),mt.close()}try{const{done:st,value:xe}=await $.read();if(st){mt.close();return}if(s?.aborted){$e();return}mt.enqueue(xe)}catch(st){Xn(st)&&s?.aborted?$e():mt.error(st)}},cancel(mt){return et.stream.cancel(mt)}});for(const mt of v)ne=ne.pipeThrough(mt({tools:f,stopStream(){et.terminate()}}));this.baseStream=ne.pipeThrough(x$(m??hl())).pipeThrough(ft);const{maxRetries:Le,retry:_t}=Dv({maxRetries:o,abortSignal:s}),Ht=Mv(t),We=Zd(n),un=Pv({model:e,telemetry:t,headers:r,settings:{...We,maxRetries:Le}}),ht=this,hr={provider:e.provider,modelId:e.modelId},Pn={functionId:t?.functionId,metadata:t?.metadata};ta({name:"ai.streamText",attributes:Fr({telemetry:t,attributes:{...ea({operationId:"ai.streamText",telemetry:t}),...un,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:Ht,endWhenDone:!1,fn:async mt=>{Ee=mt;const $e=await $v({system:u,prompt:h,messages:p});await Rr({event:{model:hr,system:u,prompt:h,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:We.maxOutputTokens,temperature:We.temperature,topP:We.topP,topK:We.topK,presencePenalty:We.presencePenalty,frequencyPenalty:We.frequencyPenalty,stopSequences:We.stopSequences,seed:We.seed,maxRetries:Le,timeout:E,headers:r,providerOptions:C,stopWhen:j,output:m,abortSignal:O,include:Z,...Pn,experimental_context:P},callbacks:[Q,M.onStart]});const st=$e.messages,xe=[],{approvedToolApprovals:Qe,deniedToolApprovals:Or}=Uv({messages:st});if(Or.length>0||Qe.length>0){const Xe=[...Qe,...Or].filter(gt=>gt.toolCall.providerExecuted),Nr=Qe.filter(gt=>!gt.toolCall.providerExecuted),at=Or.filter(gt=>!gt.toolCall.providerExecuted),Et=Or.filter(gt=>gt.toolCall.providerExecuted);let Ie;const Lt=new ReadableStream({start(gt){Ie=gt}});ht.addStream(Lt);try{for(const xt of[...at,...Et])Ie?.enqueue({type:"tool-output-denied",toolCallId:xt.toolCall.toolCallId,toolName:xt.toolCall.toolName});const gt=[];if(await Promise.all(Nr.map(async xt=>{const dt=await Vd({toolCall:xt.toolCall,tools:f,tracer:Ht,telemetry:t,messages:st,abortSignal:s,experimental_context:P,stepNumber:ee.length,model:hr,onToolCallStart:[he,M.onToolCallStart],onToolCallFinish:[V,M.onToolCallFinish],onPreliminaryToolResult:dn=>{Ie?.enqueue(dn)}});dt!=null&&(Ie?.enqueue(dt),gt.push(dt))})),Xe.length>0&&xe.push({role:"tool",content:Xe.map(xt=>({type:"tool-approval-response",approvalId:xt.approvalResponse.approvalId,approved:xt.approvalResponse.approved,reason:xt.approvalResponse.reason,providerExecuted:!0}))}),gt.length>0||at.length>0){const xt=[];for(const dt of gt)xt.push({type:"tool-result",toolCallId:dt.toolCallId,toolName:dt.toolName,output:await Qs({toolCallId:dt.toolCallId,input:dt.input,tool:f?.[dt.toolName],output:dt.type==="tool-result"?dt.output:dt.error,errorMode:dt.type==="tool-error"?"text":"none"})});for(const dt of at)xt.push({type:"tool-result",toolCallId:dt.toolCall.toolCallId,toolName:dt.toolCall.toolName,output:{type:"execution-denied",reason:dt.approvalResponse.reason}});xe.push({role:"tool",content:xt})}}finally{Ie?.close()}}te.push(...xe);async function re({currentStep:Xe,responseMessages:Nr,usage:at}){var Et,Ie,Lt,gt,xt,dt,dn,Vo,xl;const $l=ht.includeRawChunks,ua=a!=null?setTimeout(()=>i.abort(),a):void 0;let mr;function da(){l!=null&&(mr!=null&&clearTimeout(mr),mr=setTimeout(()=>c.abort(),l))}function Rl(){mr!=null&&(clearTimeout(mr),mr=void 0)}function pa(){ua!=null&&clearTimeout(ua)}try{L=new Fs;const Mn=[...st,...Nr],wt=await b?.({model:e,steps:ee,stepNumber:ee.length,messages:Mn,experimental_context:P}),Vr=ul((Et=wt?.model)!=null?Et:e),fa={provider:Vr.provider,modelId:Vr.modelId},Ae=await kv({prompt:{system:(Ie=wt?.system)!=null?Ie:$e.system,messages:(Lt=wt?.messages)!=null?Lt:Mn},supportedUrls:await Vr.supportedUrls,download:H}),jt=(gt=wt?.activeTools)!=null?gt:y,{toolChoice:On,tools:pn}=await Sv({tools:f,toolChoice:(xt=wt?.toolChoice)!=null?xt:g,activeTools:jt});P=(dt=wt?.experimental_context)!=null?dt:P;const Pl=(dn=wt?.messages)!=null?dn:Mn,Ml=(Vo=wt?.system)!=null?Vo:$e.system,ha=pl(C,wt?.providerOptions);await Rr({event:{stepNumber:ee.length,model:fa,system:Ml,messages:Pl,tools:f,toolChoice:On,activeTools:jt,steps:[...ee],providerOptions:ha,timeout:E,headers:r,stopWhen:j,output:m,abortSignal:O,include:Z,...Pn,experimental_context:P},callbacks:[K,M.onStepStart]});const{result:{stream:Ol,response:ma,request:Ho},doStreamSpan:pt,startTimestampMs:fn}=await _t(()=>ta({name:"ai.streamText.doStream",attributes:Fr({telemetry:t,attributes:{...ea({operationId:"ai.streamText.doStream",telemetry:t}),...un,"ai.model.provider":Vr.provider,"ai.model.id":Vr.modelId,"ai.prompt.messages":{input:()=>Nv(Ae)},"ai.prompt.tools":{input:()=>pn?.map(ke=>JSON.stringify(ke))},"ai.prompt.toolChoice":{input:()=>On!=null?JSON.stringify(On):void 0},"gen_ai.system":Vr.provider,"gen_ai.request.model":Vr.modelId,"gen_ai.request.frequency_penalty":We.frequencyPenalty,"gen_ai.request.max_tokens":We.maxOutputTokens,"gen_ai.request.presence_penalty":We.presencePenalty,"gen_ai.request.stop_sequences":We.stopSequences,"gen_ai.request.temperature":We.temperature,"gen_ai.request.top_k":We.topK,"gen_ai.request.top_p":We.topP}}),tracer:Ht,endWhenDone:!1,fn:async ke=>({startTimestampMs:S(),doStreamSpan:ke,result:await Vr.doStream({...We,tools:pn,toolChoice:On,responseFormat:await m?.responseFormat,prompt:Ae,providerOptions:ha,abortSignal:s,headers:r,includeRawChunks:$l})})})),Nl=I$({tools:f,generatorStream:Ol,tracer:Ht,telemetry:t,system:u,messages:Mn,repairToolCall:w,abortSignal:s,experimental_context:P,generateId:I,stepNumber:ee.length,model:fa,onToolCallStart:[he,M.onToolCallStart],onToolCallFinish:[V,M.onToolCallFinish]}),CM=(xl=Z?.requestBody)==null||xl?Ho??{}:{...Ho,body:void 0},ga=[],ya=[];let fp;const hp={};let Bo="other",mp,Ar=Fd(),gp,ow=!0,Hr={id:I(),timestamp:new Date,modelId:hr.modelId},sw="";ht.addStream(Nl.pipeThrough(new TransformStream({async transform(ke,Nt){var va,_a,Al,yt,Br;if(da(),ke.type==="stream-start"){fp=ke.warnings;return}if(ow){const vt=S()-fn;ow=!1,pt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":vt}),pt.setAttributes({"ai.response.msToFirstChunk":vt}),Nt.enqueue({type:"start-step",request:CM,warnings:fp??[]})}const yp=ke.type;switch(yp){case"tool-approval-request":case"text-start":case"text-end":{Nt.enqueue(ke);break}case"text-delta":{ke.delta.length>0&&(Nt.enqueue({type:"text-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata}),sw+=ke.delta);break}case"reasoning-start":case"reasoning-end":{Nt.enqueue(ke);break}case"reasoning-delta":{Nt.enqueue({type:"reasoning-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata});break}case"tool-call":{Nt.enqueue(ke),ga.push(ke);break}case"tool-result":{Nt.enqueue(ke),ke.preliminary||ya.push(ke);break}case"tool-error":{Nt.enqueue(ke),ya.push(ke);break}case"response-metadata":{Hr={id:(va=ke.id)!=null?va:Hr.id,timestamp:(_a=ke.timestamp)!=null?_a:Hr.timestamp,modelId:(Al=ke.modelId)!=null?Al:Hr.modelId};break}case"finish":{Ar=ke.usage,Bo=ke.finishReason,mp=ke.rawFinishReason,gp=ke.providerMetadata;const vt=S()-fn;pt.addEvent("ai.stream.finish"),pt.setAttributes({"ai.response.msToFinish":vt,"ai.response.avgOutputTokensPerSecond":1e3*((yt=Ar.outputTokens)!=null?yt:0)/vt});break}case"file":{Nt.enqueue(ke);break}case"source":{Nt.enqueue(ke);break}case"tool-input-start":{hp[ke.id]=ke.toolName;const vt=f?.[ke.toolName];vt?.onInputStart!=null&&await vt.onInputStart({toolCallId:ke.id,messages:Mn,abortSignal:s,experimental_context:P}),Nt.enqueue({...ke,dynamic:(Br=ke.dynamic)!=null?Br:vt?.type==="dynamic",title:vt?.title});break}case"tool-input-end":{delete hp[ke.id],Nt.enqueue(ke);break}case"tool-input-delta":{const vt=hp[ke.id],vp=f?.[vt];vp?.onInputDelta!=null&&await vp.onInputDelta({inputTextDelta:ke.delta,toolCallId:ke.id,messages:Mn,abortSignal:s,experimental_context:P}),Nt.enqueue(ke);break}case"error":{Nt.enqueue(ke),Bo="error";break}case"raw":{$l&&Nt.enqueue(ke);break}default:{const vt=yp;throw new Error(`Unknown chunk type: ${vt}`)}}},async flush(ke){const Nt=ga.length>0?JSON.stringify(ga):void 0;try{pt.setAttributes(await Fr({telemetry:t,attributes:{"ai.response.finishReason":Bo,"ai.response.text":{output:()=>sw},"ai.response.reasoning":{output:()=>{const yt=W.filter(Br=>Br.type==="reasoning");return yt.length>0?yt.map(Br=>Br.text).join(`
|
|
585
|
-
`):void 0}},"ai.response.toolCalls":{output:()=>Nt},"ai.response.id":Hr.id,"ai.response.model":Hr.modelId,"ai.response.timestamp":Hr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(gp),"ai.usage.inputTokens":Ar.inputTokens,"ai.usage.outputTokens":Ar.outputTokens,"ai.usage.totalTokens":Ar.totalTokens,"ai.usage.reasoningTokens":Ar.reasoningTokens,"ai.usage.cachedInputTokens":Ar.cachedInputTokens,"gen_ai.response.finish_reasons":[Bo],"gen_ai.response.id":Hr.id,"gen_ai.response.model":Hr.modelId,"gen_ai.usage.input_tokens":Ar.inputTokens,"gen_ai.usage.output_tokens":Ar.outputTokens}}))}catch{}finally{pt.end()}ke.enqueue({type:"finish-step",finishReason:Bo,rawFinishReason:mp,usage:Ar,providerMetadata:gp,response:{...Hr,headers:ma?.headers}});const va=Lv(at,Ar);await L.promise;const _a=ga.filter(yt=>yt.providerExecuted!==!0),Al=ya.filter(yt=>yt.providerExecuted!==!0);for(const yt of ga){if(yt.providerExecuted!==!0)continue;const Br=f?.[yt.toolName];Br?.type==="provider"&&Br.supportsDeferredResults&&(ya.some(vt=>(vt.type==="tool-result"||vt.type==="tool-error")&&vt.toolCallId===yt.toolCallId)||ue.set(yt.toolCallId,{toolName:yt.toolName}))}for(const yt of ya)(yt.type==="tool-result"||yt.type==="tool-error")&&ue.delete(yt.toolCallId);if(pa(),Rl(),(_a.length>0&&Al.length===_a.length||ue.size>0)&&!await Wv({stopConditions:_,steps:ee})){Nr.push(...await Bd({content:ee[ee.length-1].content,tools:f}));try{await re({currentStep:Xe+1,responseMessages:Nr,usage:va})}catch(yt){ke.enqueue({type:"error",error:yt}),ht.closeStream()}}else ke.enqueue({type:"finish",finishReason:Bo,rawFinishReason:mp,totalUsage:va}),ht.closeStream()}})))}finally{pa(),Rl()}}await re({currentStep:0,responseMessages:xe,usage:Fd()})}}).catch(mt=>{ht.addStream(new ReadableStream({start($e){$e.enqueue({type:"error",error:mt}),$e.close()}})),ht.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 na(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return na(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await C$({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 na(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 Ur({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return na(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:hl()).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=Kn}={}){const c=t!=null?y$({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}),v=p.type;switch(v){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}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});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=v;throw new Error(`Unknown chunk type: ${y}`)}}g!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:g})}}));return na(k$({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){m$({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 g$({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 h$({textStream:this.textStream,...e})}};Vs({prefix:"aiobj",size:24}),Vs({prefix:"aiobj",size:24});var R$="AI_MCPClientError",a_=`vercel.ai.error.${R$}`,P$=Symbol.for(a_),i_,l_,ze=class extends(l_=_e,i_=P$,l_){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[i_]=!0,this.data=n,this.code=o}static isInstance(e){return _e.hasMarker(e,a_)}},zo="2025-06-18",M$=[zo,"2025-03-26","2024-11-05"],O$=pe(ve(d(),Me())),N$=lt({name:d(),version:d()}),gl=lt({_meta:pe(T({}).loose())}),ln=gl,c_=T({method:d(),params:pe(gl)}),u_=T({applyDefaults:pe(ge())}).loose(),A$=lt({experimental:pe(T({}).loose()),logging:pe(T({}).loose()),prompts:pe(lt({listChanged:pe(ge())})),resources:pe(lt({subscribe:pe(ge()),listChanged:pe(ge())})),tools:pe(lt({listChanged:pe(ge())})),elicitation:pe(u_)});T({elicitation:pe(u_)}).loose();var q$=ln.extend({protocolVersion:d(),capabilities:A$,serverInfo:N$,instructions:pe(d())}),Wd=ln.extend({nextCursor:pe(d())}),L$=T({name:d(),title:pe(d()),description:pe(d()),inputSchema:T({type:R("object"),properties:pe(T({}).loose())}).loose(),outputSchema:pe(T({}).loose()),annotations:pe(T({title:pe(d())}).loose()),_meta:O$}).loose(),j$=Wd.extend({tools:q(L$)}),d_=T({type:R("text"),text:d()}).loose(),p_=T({type:R("image"),data:Qh(),mimeType:d()}).loose(),D$=T({uri:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d()),size:pe(D())}).loose(),U$=Wd.extend({resources:q(D$)}),f_=T({uri:d(),name:pe(d()),title:pe(d()),mimeType:pe(d())}).loose(),h_=f_.extend({text:d()}),m_=f_.extend({blob:Qh()}),g_=T({type:R("resource"),resource:ae([h_,m_])}).loose(),z$=ln.extend({content:q(ae([d_,p_,g_])),structuredContent:pe(Me()),isError:ge().default(!1).optional()}).or(ln.extend({toolResult:Me()})),Z$=T({uriTemplate:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d())}).loose(),F$=ln.extend({resourceTemplates:q(Z$)}),V$=ln.extend({contents:q(ae([h_,m_]))}),H$=T({name:d(),description:pe(d()),required:pe(ge())}).loose(),B$=T({name:d(),title:pe(d()),description:pe(d()),arguments:pe(q(H$))}).loose(),J$=Wd.extend({prompts:q(B$)}),G$=T({role:ae([R("user"),R("assistant")]),content:ae([d_,p_,g_])}).loose(),W$=ln.extend({description:pe(d()),messages:q(G$)}),K$=gl.extend({message:d(),requestedSchema:Me()}),y_=c_.extend({method:R("elicitation/create"),params:K$}),Y$=ln.extend({action:ae([R("accept"),R("decline"),R("cancel")]),content:pe(ve(d(),Me()))}),yl="2.0",Q$=T({jsonrpc:R(yl),id:ae([d(),D().int()])}).merge(c_).strict(),X$=T({jsonrpc:R(yl),id:ae([d(),D().int()]),result:ln}).strict(),e7=T({jsonrpc:R(yl),id:ae([d(),D().int()]),error:T({code:D().int(),message:d(),data:pe(Me())})}).strict(),t7=T({jsonrpc:R(yl)}).merge(T({method:d(),params:pe(gl)})).strict(),oa=ae([Q$,t7,X$,e7]),v_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",__=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:D().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Xt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:lm.custom,message:"URL must be parseable",fatal:!0}),sh}).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"}),r7=T({resource:d().url(),authorization_servers:q(Xt).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:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}).passthrough(),w_=T({issuer:d(),authorization_endpoint:Xt,token_endpoint:Xt,registration_endpoint:Xt.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(),n7=T({issuer:d(),authorization_endpoint:Xt,token_endpoint:Xt,userinfo_endpoint:Xt.optional(),jwks_uri:Xt,registration_endpoint:Xt.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(),o7=n7.merge(w_.pick({code_challenge_methods_supported:!0})),s7=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:D().optional(),client_secret_expires_at:D().optional()}).strip(),a7=T({redirect_uris:q(Xt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Xt.optional(),logo_uri:Xt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Xt.optional(),policy_uri:d().optional(),jwks_uri:Xt.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),i7=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),l7=a7.merge(s7),c7="AI_MCPClientOAuthError",b_=`vercel.ai.error.${c7}`,u7=Symbol.for(b_),k_,T_,sa=class extends(T_=_e,k_=u7,T_){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[k_]=!0}static isInstance(e){return _e.hasMarker(e,b_)}},Zo=class extends sa{};Zo.errorCode="server_error";var vl=class extends sa{};vl.errorCode="invalid_client";var _l=class extends sa{};_l.errorCode="invalid_grant";var wl=class extends sa{};wl.errorCode="unauthorized_client";var d7={[Zo.errorCode]:Zo,[vl.errorCode]:vl,[_l.errorCode]:_l,[wl.errorCode]:wl};function p7(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function f7({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 bl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function kl(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 h7(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Kd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Kd(e,void 0,r):void 0;throw n}}async function C_(e,t,r=fetch){return await Kd(e,{"MCP-Protocol-Version":t},r)}function m7(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function g7(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:zo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=h7(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await C_(l,i,r);if(!n?.metadataUrl&&m7(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await C_(u,i,r)}return c}async function y7(e,t,r=fetch){const n=await g7(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 r7.parse(await n.json())}function v7(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 _7(e,{fetchFn:t=fetch,protocolVersion:r=zo}={}){var n;const o={"MCP-Protocol-Version":r},s=v7(e);for(const{url:a,type:i}of s){const l=await Kd(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 w_.parse(await l.json());{const c=o7.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 w7(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 p0(),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 S_(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 I_(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":b7(o,s,r);return;case"client_secret_post":k7(o,s,n);return;case"none":T7(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function b7(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 k7(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 Yd(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=i7.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=d7[o]||Zo;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Zo({message:o})}}async function C7(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 v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=S_(r,v);I_(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 Yd(g);return __.parse(await g.json())}async function S7(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=S_(r,f);I_(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 Yd(p);return __.parse({refresh_token:n,...await p.json()})}async function I7(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 Yd(s);return l7.parse(await s.json())}async function Tl(e,t){var r,n;try{return await Qd(e,t)}catch(o){if(o instanceof vl||o instanceof wl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Qd(e,t);if(o instanceof _l)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Qd(e,t);throw o}}async function E7(e,t,r){const n=p7(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!f7({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 Qd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await y7(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await E7(t,e,a),c=await _7(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 v=await I7(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await C7(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,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 v=await S7(i,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof sa)||v instanceof Zo))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await w7(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 x7=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":zo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return xn(t,`ai-sdk/${v_}`,Hs())}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=kl(u);try{if(await Tl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new bl;return(s=this.onerror)==null||s.call(this,v),t(v)}}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 v=new ze({message:g});return(i=this.onerror)==null||i.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ro).getReader(),f=async()=>{var g,v,y;try{for(;;){const{done:w,value:_}=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}=_;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 b=oa.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,b)}catch(b){const k=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,k)}}}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=kl(h);try{if(await Tl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new bl;(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()}},$7=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":zo};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/${v_}`,Hs())}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=kl(p);try{if(await Tl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new bl}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 _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const m=new ze({message:_});throw(s=this.onerror)==null||s.call(this,m),m}if(!("id"in e))return;const v=p.headers.get("content-type")||"";if(v.includes("application/json")){const w=await p.json(),_=Array.isArray(w)?w.map(m=>oa.parse(m)):[oa.parse(w)];for(const m of _)(a=this.onmessage)==null||a.call(this,m);return}if(v.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 _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ro).getReader();(async()=>{var C,b,k;try{for(;;){const{done:S,value:I}=await _.read();if(S)return;const{event:E,data:j}=I;if(E==="message")try{const O=oa.parse(JSON.parse(j));(C=this.onmessage)==null||C.call(this,O)}catch(O){const U=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:O});(b=this.onerror)==null||b.call(this,U)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const y=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${v}`});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=kl(c);try{if(await Tl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new bl;(n=this.onerror)==null||n.call(this,v);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 Ro).getReader(),f=async()=>{var g,v,y,w;try{for(;;){const{done:_,value:m}=await p.read();if(_)return;const{event:C,data:b,id:k}=m;if(k&&(this.lastInboundEventId=k),C==="message")try{const S=oa.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,S)}catch(S){const I=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,I)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),(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 R7(e){switch(e.type){case"sse":return new x7(e);case"http":return new $7(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 P7(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var M7="1.0.0";function E_({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 O7(e){const t=new N7(e);return await t.init(),t}var N7=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=M7,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},P7(e)?this.transport=e:this.transport=R7(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:zo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:q$});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!M$.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:j$,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:z$,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:U$,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:V$,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:F$,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:J$,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:W$,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 _;(_=w?.abortSignal)==null||_.throwIfAborted();const m=await p.callTool({name:s,args:y,options:w});return f!=null?p.extractStructuredContent(m,f,s):m},v=t==="automatic"?Mg({description:i,title:h,inputSchema:Do({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:E_}):{description:i,title:h,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:E_};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await dr({value:e.structuredContent,schema:to(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 pr({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!==y_)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=y_.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=Y$.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}))}},Xd=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),D()]).nullish()})}),Mr=$n({errorSchema:Xd,errorToMessage:e=>e.error.message});function x_(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("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 $_(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 A7({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,${Lo(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 Ur({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Lo(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Lo(i.data),format:"mp3"}};default:throw new Ur({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Ur({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,${Lo(i.data)}`}}}else throw new Ur({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 ep({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?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 q7=be(()=>we(T({id:d().nullish(),created:D().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:D(),end_index:D(),url:d(),title:d()})})).nullish()}),index:D(),logprobs:T({content:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}))),L7=be(()=>we(ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({delta:T({role:ye(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:D(),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:D(),end_index:D(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:D()})),usage:T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}),Xd]))),j7=be(()=>we(T({logitBias:ve(cm(),D()).optional(),logprobs:ae([ge(),D()]).optional(),parallelToolCalls:ge().optional(),user:d().optional(),reasoningEffort:ye(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:D().optional(),store:ge().optional(),metadata:ve(d().max(64),d().max(512)).optional(),prediction:ve(d(),Tt()).optional(),serviceTier:ye(["auto","flex","priority","default"]).optional(),strictJsonSchema:ge().optional(),textVerbosity:ye(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:ye(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:ye(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));function D7({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 Ur({functionality:`tool choice type: ${s}`})}}}var U7=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,v,y,w;const _=[],m=(f=await sn({provider:"openai",providerOptions:p,schema:j7}))!=null?f:{},C=x_(this.modelId),b=(g=m.forceReasoning)!=null?g:C.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:k,warnings:S}=A7({prompt:e,systemMessageMode:(v=m.systemMessageMode)!=null?v:b?"developer":C.systemMessageMode});_.push(...S);const I=(y=m.strictJsonSchema)!=null?y:!0,E={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:I,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:k};b?((m.reasoningEffort!=="none"||!C.supportsNonReasoningParameters)&&(E.temperature!=null&&(E.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),E.top_p!=null&&(E.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),E.logprobs!=null&&(E.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),E.frequency_penalty!=null&&(E.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),E.presence_penalty!=null&&(E.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),E.logit_bias!=null&&(E.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),E.top_logprobs!=null&&(E.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),E.max_tokens!=null&&(E.max_completion_tokens==null&&(E.max_completion_tokens=E.max_tokens),E.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&E.temperature!=null&&(E.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),m.serviceTier==="flex"&&!C.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0),m.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(_.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"}),E.service_tier=void 0);const{tools:j,toolChoice:O,toolWarnings:U}=D7({tools:u,toolChoice:h});return{args:{...E,tools:j,tool_choice:O},warnings:[..._,...U]}}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 Yt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:l,failedResponseHandler:Mr,successfulResponseHandler:fr(q7),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=h.choices[0],g=[],v=f.message.content;v!=null&&v.length>0&&g.push({type:"text",text:v});for(const _ of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(r=_.id)!=null?r:Zt(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:Zt(),url:_.url_citation.url,title:_.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:R_(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:$_(h.usage),request:{body:l},response:{...ep(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 Yt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Mr,successfulResponseHandler:al(L7),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,v,y,w,_,m,C,b,k,S,I,E,j,O,U,A,N;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const G=p.value;if("error"in G){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:G.error});return}if(!c){const K=ep(G);Object.values(K).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...ep(G)}))}G.usage!=null&&(l=G.usage,((g=G.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(v=G.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=G.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=G.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const X=G.choices[0];if(X?.finish_reason!=null&&(i={unified:R_(X.finish_reason),raw:X.finish_reason}),((_=X?.logprobs)==null?void 0:_.content)!=null&&(h.openai.logprobs=X.logprobs.content),X?.delta==null)return;const Q=X.delta;if(Q.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:Q.content})),Q.tool_calls!=null)for(const K of Q.tool_calls){const he=K.index;if(a[he]==null){if(K.type!=null&&K.type!=="function")throw new pd({data:K,message:"Expected 'function' type."});if(K.id==null)throw new pd({data:K,message:"Expected 'id' to be a string."});if(((m=K.function)==null?void 0:m.name)==null)throw new pd({data:K,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),a[he]={id:K.id,type:"function",function:{name:K.function.name,arguments:(C=K.function.arguments)!=null?C:""},hasFinished:!1};const P=a[he];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),xg(P.function.arguments)&&(f.enqueue({type:"tool-input-end",id:P.id}),f.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:Zt(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const V=a[he];V.hasFinished||(((I=K.function)==null?void 0:I.arguments)!=null&&(V.function.arguments+=(j=(E=K.function)==null?void 0:E.arguments)!=null?j:""),f.enqueue({type:"tool-input-delta",id:V.id,delta:(O=K.function.arguments)!=null?O:""}),((U=V.function)==null?void 0:U.name)!=null&&((A=V.function)==null?void 0:A.arguments)!=null&&xg(V.function.arguments)&&(f.enqueue({type:"tool-input-end",id:V.id}),f.enqueue({type:"tool-call",toolCallId:(N=V.id)!=null?N:Zt(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}if(Q.annotations!=null)for(const K of Q.annotations)f.enqueue({type:"source",sourceType:"url",id:Zt(),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:$_(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function P_(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 z7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
584
|
+
`)}})}},l_={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function k$({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new i_);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:vl(r,l_)})}function T$({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 C$(e){return e.type.startsWith("data-")}function ep(e){return e.type.startsWith("tool-")}function S$(e){return e.type==="dynamic-tool"}function c_(e){return ep(e)||S$(e)}function u_(e){return e.type.split("-").slice(1).join("-")}function I$({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function x$({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,m;function v(g){const b=c.message.parts.filter(c_).find(k=>k.toolCallId===g);if(b==null)throw new zo({chunkType:"tool-invocation",chunkId:g,message:`No tool invocation found for tool call ID "${g}".`});return b}function y(g){var C;const b=c.message.parts.find(I=>ep(I)&&I.toolCallId===g.toolCallId),k=g,S=b;b!=null?(b.state=g.state,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=k.rawInput,S.preliminary=k.preliminary,g.title!==void 0&&(S.title=g.title),S.providerExecuted=(C=k.providerExecuted)!=null?C:b.providerExecuted,k.providerMetadata!=null&&(b.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,title:g.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(g){var C,b;const k=c.message.parts.find(x=>x.type==="dynamic-tool"&&x.toolCallId===g.toolCallId),S=g,I=k;k!=null?(k.state=g.state,I.toolName=g.toolName,I.input=S.input,I.output=S.output,I.errorText=S.errorText,I.rawInput=(C=S.rawInput)!=null?C:I.rawInput,I.preliminary=S.preliminary,g.title!==void 0&&(I.title=g.title),I.providerExecuted=(b=S.providerExecuted)!=null?b:k.providerExecuted,S.providerMetadata!=null&&(k.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:g.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function _(g){if(g!=null){const C=c.message.metadata!=null?ml(c.message.metadata,g):g;t!=null&&await St({value:C,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=C}}switch(i.type){case"text-start":{const g={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=g,c.message.parts.push(g),u();break}case"text-delta":{const g=c.activeTextParts[i.id];if(g==null)throw new zo({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.`});g.text+=i.delta,g.providerMetadata=(h=i.providerMetadata)!=null?h:g.providerMetadata,u();break}case"text-end":{const g=c.activeTextParts[i.id];if(g==null)throw new zo({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.`});g.state="done",g.providerMetadata=(p=i.providerMetadata)!=null?p:g.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=g,c.message.parts.push(g),u();break}case"reasoning-delta":{const g=c.activeReasoningParts[i.id];if(g==null)throw new zo({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.`});g.text+=i.delta,g.providerMetadata=(f=i.providerMetadata)!=null?f:g.providerMetadata,u();break}case"reasoning-end":{const g=c.activeReasoningParts[i.id];if(g==null)throw new zo({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.`});g.providerMetadata=(m=i.providerMetadata)!=null?m:g.providerMetadata,g.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}),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 g=c.message.parts.filter(ep);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:g.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 g=c.partialToolCalls[i.toolCallId];if(g==null)throw new zo({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.`});g.text+=i.inputTextDelta;const{value:C}=await oa(g.text);g.dynamic?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:C,title:g.title}):y({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:C,title:g.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 g=c.message.parts.filter(c_).find(b=>b.toolCallId===i.toolCallId);(g!=null?g.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 g=v(i.toolCallId);g.state="approval-requested",g.approval={id:i.approvalId},u();break}case"tool-output-denied":{const g=v(i.toolCallId);g.state="output-denied",u();break}case"tool-output-available":{const g=v(i.toolCallId);g.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:g.title}):y({toolCallId:i.toolCallId,toolName:u_(g),state:"output-available",input:g.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,title:g.title}),u();break}case"tool-output-error":{const g=v(i.toolCallId);g.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:g.title}):y({toolCallId:i.toolCallId,toolName:u_(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,title:g.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 _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(C$(i)){if(r?.[i.type]!=null){const b=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),k=b>=0?b:c.message.parts.length;await St({value:i.data,schema:r[i.type],context:{field:`message.parts[${k}].data`,entityName:i.type,entityId:i.id}})}const g=i;if(g.transient){a?.(g);break}const C=g.id!=null?c.message.parts.find(b=>g.type===b.type&&g.id===b.id):void 0;C!=null?C.data=g.data:c.message.parts.push(g),a?.(g),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(m,v){if(m.type==="start"){const y=m;y.messageId==null&&e!=null&&(y.messageId=e)}m.type==="abort"&&(i=!0),v.enqueue(m)}}));if(n==null&&r==null)return l;const c=I$({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async m=>{await m({state:c,write:()=>{}})};let h=!1;const p=async()=>{if(h||!n)return;h=!0;const m=c.message.id===a?.id;await n({isAborted:i,isContinuation:m,responseMessage:c.message,messages:[...m?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},f=async()=>{if(!r)return;const m=c.message.id===a?.id;try{await r({isContinuation:m,responseMessage:structuredClone(c.message),messages:[...m?t.slice(0,-1):t,structuredClone(c.message)]})}catch(v){o(v)}};return x$({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(m,v){m.type==="finish-step"&&await f(),v.enqueue(m)},async cancel(){await p()},async flush(){await p()}}))}function $$({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new i_);if(s){const[i,l]=a.tee();a=i,s({stream:l})}a_({response:e,status:t,statusText:r,headers:Object.fromEntries(vl(n,l_).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function sa(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 d_(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function P$(){let e=[],t=null,r=!1,n=d_();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=d_(),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 M$({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 m=null;const v=new ReadableStream({start(S){m=S}}),y=new Set,w=new Map,_=new Map;let g=!1,C;function b(){g&&y.size===0&&(C!=null&&m.enqueue(C),m.close())}const k=new TransformStream({async transform(S,I){const x=S.type;switch(x){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":{I.enqueue(S);break}case"file":{I.enqueue({type:"file",file:new u$({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{C={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:Zv(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const j=_.get(S.toolCallId);if(j==null){m.enqueue({type:"error",error:new Hd({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}I.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:j});break}case"tool-call":{try{const j=await Yv({toolCall:S,tools:e,repairToolCall:i,system:o,messages:s});if(_.set(j.toolCallId,j),I.enqueue(j),j.invalid){m.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:kd(j.error),dynamic:!0,title:j.title});break}const O=e?.[j.toolName];if(O==null)break;if(O.onInputAvailable!=null&&await O.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await Kv({tool:O,toolCall:j,messages:s,experimental_context:l})){m.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),O.execute!=null&&j.providerExecuted!==!0){const U=c();y.add(U),Yd({toolCall:j,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:h,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:A=>{m.enqueue(A)}}).then(A=>{m.enqueue(A)}).catch(A=>{m.enqueue({type:"error",error:A})}).finally(()=>{y.delete(U),b()})}}catch(j){m.enqueue({type:"error",error:j})}break}case"tool-result":{const j=S.toolName;S.isError?m.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):I.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const j=x;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){g=!0,b()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){}})),v.pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){S.close()}}))])}})}var O$=Bs({prefix:"aitxt",size:24});function tp({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Qd(1),experimental_output:h,output:p=h,experimental_telemetry:f,prepareStep:m,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:g,experimental_download:C,includeRawChunks:b=!1,onChunk:k,onError:S=({error:V})=>{console.error(V)},onFinish:I,onAbort:x,onStepFinish:j,experimental_onStart:O,experimental_onStepStart:U,experimental_onToolCallStart:A,experimental_onToolCallFinish:N,experimental_context:G,experimental_include:X,_internal:{now:Q=gl,generateId:K=O$}={},...he}){const V=Gd(l),P=Cv(l),H=A8(l),Z=P!=null?new AbortController:void 0,E=H!=null?new AbortController:void 0;return new A$({model:fl(e),telemetry:f,headers:c,settings:he,maxRetries:a,abortSignal:r_(i,V!=null?AbortSignal.timeout(V):void 0,Z?.signal,E?.signal),stepTimeoutMs:P,stepAbortController:Z,chunkTimeoutMs:H,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:io(g),activeTools:w,repairToolCall:_,stopConditions:io(u),output:p,providerOptions:v,prepareStep:m,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:k,onError:S,onFinish:I,onAbort:x,onStepFinish:j,onStart:O,onStepStart:U,onToolCallStart:A,onToolCallFinish:N,now:Q,generateId:K,experimental_context:G,download:C,include:X})}function N$(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const h=JSON.stringify(u.partial);h!==s&&(a({controller:l,partialOutput:u.partial}),s=h)}}})}var A$=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:h,messages:p,tools:f,toolChoice:m,transforms:v,activeTools:y,repairToolCall:w,stopConditions:_,output:g,providerOptions:C,prepareStep:b,includeRawChunks:k,now:S,generateId:I,timeout:x,stopWhen:j,originalAbortSignal:O,onChunk:U,onError:A,onFinish:N,onAbort:G,onStepFinish:X,onStart:Q,onStepStart:K,onToolCallStart:he,onToolCallFinish:V,experimental_context:P,download:H,include:Z}){this._totalUsage=new Hs,this._finishReason=new Hs,this._rawFinishReason=new Hs,this._steps=new Hs,this.outputSpecification=g,this.includeRawChunks=k,this.tools=f;const M=zv()(t?.integrations);let L,W=[];const te=[];let se,Se,z,F={},Y=[];const ee=[],ue=new Map;let xe,He={},ot={};const ft=new TransformStream({async transform(mt,$e){var st,Ee,Qe,Or;$e.enqueue(mt);const{part:re}=mt;if((re.type==="text-delta"||re.type==="reasoning-delta"||re.type==="source"||re.type==="tool-call"||re.type==="tool-result"||re.type==="tool-input-start"||re.type==="tool-input-delta"||re.type==="raw")&&await U?.({chunk:re}),re.type==="error"&&await A({error:qv(re.error)}),re.type==="text-start"&&(He[re.id]={type:"text",text:"",providerMetadata:re.providerMetadata},W.push(He[re.id])),re.type==="text-delta"){const Xe=He[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Xe.text+=re.text,Xe.providerMetadata=(st=re.providerMetadata)!=null?st:Xe.providerMetadata}if(re.type==="text-end"){const Xe=He[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Xe.providerMetadata=(Ee=re.providerMetadata)!=null?Ee:Xe.providerMetadata,delete He[re.id]}if(re.type==="reasoning-start"&&(ot[re.id]={type:"reasoning",text:"",providerMetadata:re.providerMetadata},W.push(ot[re.id])),re.type==="reasoning-delta"){const Xe=ot[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Xe.text+=re.text,Xe.providerMetadata=(Qe=re.providerMetadata)!=null?Qe:Xe.providerMetadata}if(re.type==="reasoning-end"){const Xe=ot[re.id];if(Xe==null){$e.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Xe.providerMetadata=(Or=re.providerMetadata)!=null?Or:Xe.providerMetadata,delete ot[re.id]}if(re.type==="file"&&W.push({type:"file",file:re.file,...re.providerMetadata!=null?{providerMetadata:re.providerMetadata}:{}}),re.type==="source"&&W.push(re),re.type==="tool-call"&&W.push(re),re.type==="tool-result"&&!re.preliminary&&W.push(re),re.type==="tool-approval-request"&&W.push(re),re.type==="tool-error"&&W.push(re),re.type==="start-step"&&(W=[],ot={},He={},F=re.request,Y=re.warnings),re.type==="finish-step"){const Xe=await Xd({content:W,tools:f}),Nr=new e_({stepNumber:ee.length,model:hr,...Mn,experimental_context:P,content:W,finishReason:re.finishReason,rawFinishReason:re.rawFinishReason,usage:re.usage,warnings:Y,request:F,response:{...re.response,messages:[...te,...Xe]},providerMetadata:re.providerMetadata});await Rr({event:Nr,callbacks:[X,M.onStepFinish]}),Jd({warnings:Y,provider:hr.provider,model:hr.modelId}),ee.push(Nr),te.push(...Xe),L.resolve()}re.type==="finish"&&(z=re.totalUsage,se=re.finishReason,Se=re.rawFinishReason)},async flush(mt){try{if(ee.length===0){const Qe=s?.aborted?s.reason:new ov({message:"No output generated. Check the stream for errors."});ht._finishReason.reject(Qe),ht._rawFinishReason.reject(Qe),ht._totalUsage.reject(Qe),ht._steps.reject(Qe);return}const $e=se??"other",st=z??Kd();ht._finishReason.resolve($e),ht._rawFinishReason.resolve(Se),ht._totalUsage.resolve(st),ht._steps.resolve(ee);const Ee=ee[ee.length-1];await Rr({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:st,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:ee},callbacks:[N,M.onFinish]}),xe.setAttributes(await Fr({telemetry:t,attributes:{"ai.response.finishReason":$e,"ai.response.text":{output:()=>Ee.text},"ai.response.reasoning":{output:()=>Ee.reasoningText},"ai.response.toolCalls":{output:()=>{var Qe;return(Qe=Ee.toolCalls)!=null&&Qe.length?JSON.stringify(Ee.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ee.providerMetadata),"ai.usage.inputTokens":st.inputTokens,"ai.usage.outputTokens":st.outputTokens,"ai.usage.totalTokens":st.totalTokens,"ai.usage.reasoningTokens":st.reasoningTokens,"ai.usage.cachedInputTokens":st.cachedInputTokens}}))}catch($e){mt.error($e)}finally{xe.end()}}}),et=P$();this.addStream=et.addStream,this.closeStream=et.close;const $=et.stream.getReader();let ne=new ReadableStream({async start(mt){mt.enqueue({type:"start"})},async pull(mt){function $e(){G?.({steps:ee}),mt.enqueue({type:"abort",...s?.reason!==void 0?{reason:Yn(s.reason)}:{}}),mt.close()}try{const{done:st,value:Ee}=await $.read();if(st){mt.close();return}if(s?.aborted){$e();return}mt.enqueue(Ee)}catch(st){eo(st)&&s?.aborted?$e():mt.error(st)}},cancel(mt){return et.stream.cancel(mt)}});for(const mt of v)ne=ne.pipeThrough(mt({tools:f,stopStream(){et.terminate()}}));this.baseStream=ne.pipeThrough(N$(g??yl())).pipeThrough(ft);const{maxRetries:Le,retry:_t}=Hv({maxRetries:o,abortSignal:s}),Ht=jv(t),We=Wd(n),dn=Lv({model:e,telemetry:t,headers:r,settings:{...We,maxRetries:Le}}),ht=this,hr={provider:e.provider,modelId:e.modelId},Mn={functionId:t?.functionId,metadata:t?.metadata};na({name:"ai.streamText",attributes:Fr({telemetry:t,attributes:{...ra({operationId:"ai.streamText",telemetry:t}),...dn,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:Ht,endWhenDone:!1,fn:async mt=>{xe=mt;const $e=await Av({system:u,prompt:h,messages:p});await Rr({event:{model:hr,system:u,prompt:h,messages:p,tools:f,toolChoice:m,activeTools:y,maxOutputTokens:We.maxOutputTokens,temperature:We.temperature,topP:We.topP,topK:We.topK,presencePenalty:We.presencePenalty,frequencyPenalty:We.frequencyPenalty,stopSequences:We.stopSequences,seed:We.seed,maxRetries:Le,timeout:x,headers:r,providerOptions:C,stopWhen:j,output:g,abortSignal:O,include:Z,...Mn,experimental_context:P},callbacks:[Q,M.onStart]});const st=$e.messages,Ee=[],{approvedToolApprovals:Qe,deniedToolApprovals:Or}=Bv({messages:st});if(Or.length>0||Qe.length>0){const Xe=[...Qe,...Or].filter(gt=>gt.toolCall.providerExecuted),Nr=Qe.filter(gt=>!gt.toolCall.providerExecuted),at=Or.filter(gt=>!gt.toolCall.providerExecuted),xt=Or.filter(gt=>gt.toolCall.providerExecuted);let Ie;const Lt=new ReadableStream({start(gt){Ie=gt}});ht.addStream(Lt);try{for(const Et of[...at,...xt])Ie?.enqueue({type:"tool-output-denied",toolCallId:Et.toolCall.toolCallId,toolName:Et.toolCall.toolName});const gt=[];if(await Promise.all(Nr.map(async Et=>{const dt=await Yd({toolCall:Et.toolCall,tools:f,tracer:Ht,telemetry:t,messages:st,abortSignal:s,experimental_context:P,stepNumber:ee.length,model:hr,onToolCallStart:[he,M.onToolCallStart],onToolCallFinish:[V,M.onToolCallFinish],onPreliminaryToolResult:pn=>{Ie?.enqueue(pn)}});dt!=null&&(Ie?.enqueue(dt),gt.push(dt))})),Xe.length>0&&Ee.push({role:"tool",content:Xe.map(Et=>({type:"tool-approval-response",approvalId:Et.approvalResponse.approvalId,approved:Et.approvalResponse.approved,reason:Et.approvalResponse.reason,providerExecuted:!0}))}),gt.length>0||at.length>0){const Et=[];for(const dt of gt)Et.push({type:"tool-result",toolCallId:dt.toolCallId,toolName:dt.toolName,output:await ea({toolCallId:dt.toolCallId,input:dt.input,tool:f?.[dt.toolName],output:dt.type==="tool-result"?dt.output:dt.error,errorMode:dt.type==="tool-error"?"text":"none"})});for(const dt of at)Et.push({type:"tool-result",toolCallId:dt.toolCall.toolCallId,toolName:dt.toolCall.toolName,output:{type:"execution-denied",reason:dt.approvalResponse.reason}});Ee.push({role:"tool",content:Et})}}finally{Ie?.close()}}te.push(...Ee);async function re({currentStep:Xe,responseMessages:Nr,usage:at}){var xt,Ie,Lt,gt,Et,dt,pn,Bo,Al;const ql=ht.includeRawChunks,fa=a!=null?setTimeout(()=>i.abort(),a):void 0;let mr;function ha(){l!=null&&(mr!=null&&clearTimeout(mr),mr=setTimeout(()=>c.abort(),l))}function Ll(){mr!=null&&(clearTimeout(mr),mr=void 0)}function ma(){fa!=null&&clearTimeout(fa)}try{L=new Hs;const On=[...st,...Nr],wt=await b?.({model:e,steps:ee,stepNumber:ee.length,messages:On,experimental_context:P}),Vr=fl((xt=wt?.model)!=null?xt:e),ga={provider:Vr.provider,modelId:Vr.modelId},Ae=await Ev({prompt:{system:(Ie=wt?.system)!=null?Ie:$e.system,messages:(Lt=wt?.messages)!=null?Lt:On},supportedUrls:await Vr.supportedUrls,download:H}),jt=(gt=wt?.activeTools)!=null?gt:y,{toolChoice:Nn,tools:fn}=await Pv({tools:f,toolChoice:(Et=wt?.toolChoice)!=null?Et:m,activeTools:jt});P=(dt=wt?.experimental_context)!=null?dt:P;const jl=(pn=wt?.messages)!=null?pn:On,Dl=(Bo=wt?.system)!=null?Bo:$e.system,ya=ml(C,wt?.providerOptions);await Rr({event:{stepNumber:ee.length,model:ga,system:Dl,messages:jl,tools:f,toolChoice:Nn,activeTools:jt,steps:[...ee],providerOptions:ya,timeout:x,headers:r,stopWhen:j,output:g,abortSignal:O,include:Z,...Mn,experimental_context:P},callbacks:[K,M.onStepStart]});const{result:{stream:Ul,response:va,request:Jo},doStreamSpan:pt,startTimestampMs:hn}=await _t(()=>na({name:"ai.streamText.doStream",attributes:Fr({telemetry:t,attributes:{...ra({operationId:"ai.streamText.doStream",telemetry:t}),...dn,"ai.model.provider":Vr.provider,"ai.model.id":Vr.modelId,"ai.prompt.messages":{input:()=>Uv(Ae)},"ai.prompt.tools":{input:()=>fn?.map(ke=>JSON.stringify(ke))},"ai.prompt.toolChoice":{input:()=>Nn!=null?JSON.stringify(Nn):void 0},"gen_ai.system":Vr.provider,"gen_ai.request.model":Vr.modelId,"gen_ai.request.frequency_penalty":We.frequencyPenalty,"gen_ai.request.max_tokens":We.maxOutputTokens,"gen_ai.request.presence_penalty":We.presencePenalty,"gen_ai.request.stop_sequences":We.stopSequences,"gen_ai.request.temperature":We.temperature,"gen_ai.request.top_k":We.topK,"gen_ai.request.top_p":We.topP}}),tracer:Ht,endWhenDone:!1,fn:async ke=>({startTimestampMs:S(),doStreamSpan:ke,result:await Vr.doStream({...We,tools:fn,toolChoice:Nn,responseFormat:await g?.responseFormat,prompt:Ae,providerOptions:ya,abortSignal:s,headers:r,includeRawChunks:ql})})})),zl=M$({tools:f,generatorStream:Ul,tracer:Ht,telemetry:t,system:u,messages:On,repairToolCall:w,abortSignal:s,experimental_context:P,generateId:I,stepNumber:ee.length,model:ga,onToolCallStart:[he,M.onToolCallStart],onToolCallFinish:[V,M.onToolCallFinish]}),UM=(Al=Z?.requestBody)==null||Al?Jo??{}:{...Jo,body:void 0},_a=[],wa=[];let _p;const wp={};let Go="other",bp,Ar=Kd(),kp,uw=!0,Hr={id:I(),timestamp:new Date,modelId:hr.modelId},dw="";ht.addStream(zl.pipeThrough(new TransformStream({async transform(ke,Nt){var ba,ka,Zl,yt,Br;if(ha(),ke.type==="stream-start"){_p=ke.warnings;return}if(uw){const vt=S()-hn;uw=!1,pt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":vt}),pt.setAttributes({"ai.response.msToFirstChunk":vt}),Nt.enqueue({type:"start-step",request:UM,warnings:_p??[]})}const Tp=ke.type;switch(Tp){case"tool-approval-request":case"text-start":case"text-end":{Nt.enqueue(ke);break}case"text-delta":{ke.delta.length>0&&(Nt.enqueue({type:"text-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata}),dw+=ke.delta);break}case"reasoning-start":case"reasoning-end":{Nt.enqueue(ke);break}case"reasoning-delta":{Nt.enqueue({type:"reasoning-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata});break}case"tool-call":{Nt.enqueue(ke),_a.push(ke);break}case"tool-result":{Nt.enqueue(ke),ke.preliminary||wa.push(ke);break}case"tool-error":{Nt.enqueue(ke),wa.push(ke);break}case"response-metadata":{Hr={id:(ba=ke.id)!=null?ba:Hr.id,timestamp:(ka=ke.timestamp)!=null?ka:Hr.timestamp,modelId:(Zl=ke.modelId)!=null?Zl:Hr.modelId};break}case"finish":{Ar=ke.usage,Go=ke.finishReason,bp=ke.rawFinishReason,kp=ke.providerMetadata;const vt=S()-hn;pt.addEvent("ai.stream.finish"),pt.setAttributes({"ai.response.msToFinish":vt,"ai.response.avgOutputTokensPerSecond":1e3*((yt=Ar.outputTokens)!=null?yt:0)/vt});break}case"file":{Nt.enqueue(ke);break}case"source":{Nt.enqueue(ke);break}case"tool-input-start":{wp[ke.id]=ke.toolName;const vt=f?.[ke.toolName];vt?.onInputStart!=null&&await vt.onInputStart({toolCallId:ke.id,messages:On,abortSignal:s,experimental_context:P}),Nt.enqueue({...ke,dynamic:(Br=ke.dynamic)!=null?Br:vt?.type==="dynamic",title:vt?.title});break}case"tool-input-end":{delete wp[ke.id],Nt.enqueue(ke);break}case"tool-input-delta":{const vt=wp[ke.id],Cp=f?.[vt];Cp?.onInputDelta!=null&&await Cp.onInputDelta({inputTextDelta:ke.delta,toolCallId:ke.id,messages:On,abortSignal:s,experimental_context:P}),Nt.enqueue(ke);break}case"error":{Nt.enqueue(ke),Go="error";break}case"raw":{ql&&Nt.enqueue(ke);break}default:{const vt=Tp;throw new Error(`Unknown chunk type: ${vt}`)}}},async flush(ke){const Nt=_a.length>0?JSON.stringify(_a):void 0;try{pt.setAttributes(await Fr({telemetry:t,attributes:{"ai.response.finishReason":Go,"ai.response.text":{output:()=>dw},"ai.response.reasoning":{output:()=>{const yt=W.filter(Br=>Br.type==="reasoning");return yt.length>0?yt.map(Br=>Br.text).join(`
|
|
585
|
+
`):void 0}},"ai.response.toolCalls":{output:()=>Nt},"ai.response.id":Hr.id,"ai.response.model":Hr.modelId,"ai.response.timestamp":Hr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(kp),"ai.usage.inputTokens":Ar.inputTokens,"ai.usage.outputTokens":Ar.outputTokens,"ai.usage.totalTokens":Ar.totalTokens,"ai.usage.reasoningTokens":Ar.reasoningTokens,"ai.usage.cachedInputTokens":Ar.cachedInputTokens,"gen_ai.response.finish_reasons":[Go],"gen_ai.response.id":Hr.id,"gen_ai.response.model":Hr.modelId,"gen_ai.usage.input_tokens":Ar.inputTokens,"gen_ai.usage.output_tokens":Ar.outputTokens}}))}catch{}finally{pt.end()}ke.enqueue({type:"finish-step",finishReason:Go,rawFinishReason:bp,usage:Ar,providerMetadata:kp,response:{...Hr,headers:va?.headers}});const ba=Fv(at,Ar);await L.promise;const ka=_a.filter(yt=>yt.providerExecuted!==!0),Zl=wa.filter(yt=>yt.providerExecuted!==!0);for(const yt of _a){if(yt.providerExecuted!==!0)continue;const Br=f?.[yt.toolName];Br?.type==="provider"&&Br.supportsDeferredResults&&(wa.some(vt=>(vt.type==="tool-result"||vt.type==="tool-error")&&vt.toolCallId===yt.toolCallId)||ue.set(yt.toolCallId,{toolName:yt.toolName}))}for(const yt of wa)(yt.type==="tool-result"||yt.type==="tool-error")&&ue.delete(yt.toolCallId);if(ma(),Ll(),(ka.length>0&&Zl.length===ka.length||ue.size>0)&&!await t_({stopConditions:_,steps:ee})){Nr.push(...await Xd({content:ee[ee.length-1].content,tools:f}));try{await re({currentStep:Xe+1,responseMessages:Nr,usage:ba})}catch(yt){ke.enqueue({type:"error",error:yt}),ht.closeStream()}}else ke.enqueue({type:"finish",finishReason:Go,rawFinishReason:bp,totalUsage:ba}),ht.closeStream()}})))}finally{ma(),Ll()}}await re({currentStep:0,responseMessages:Ee,usage:Kd()})}}).catch(mt=>{ht.addStream(new ReadableStream({start($e){$e.enqueue({type:"error",error:mt}),$e.close()}})),ht.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 sa(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return sa(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 sa(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 Ur({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return sa(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:yl()).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=Yn}={}){const c=t!=null?T$({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var f;const m=(f=this.tools)==null?void 0:f[p.toolName];return m==null?p.dynamic:m?.type==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const m=n?.({part:p}),v=p.type;switch(v){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}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});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",...m!=null?{messageMetadata:m}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:p.finishReason,...m!=null?{messageMetadata:m}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=v;throw new Error(`Unknown chunk type: ${y}`)}}m!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:m})}}));return sa(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}={}){$$({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){b$({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 k$({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 w$({textStream:this.textStream,...e})}};Bs({prefix:"aiobj",size:24}),Bs({prefix:"aiobj",size:24});var q$="AI_MCPClientError",p_=`vercel.ai.error.${q$}`,L$=Symbol.for(p_),f_,h_,Ze=class extends(h_=_e,f_=L$,h_){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[f_]=!0,this.data=n,this.code=o}static isInstance(e){return _e.hasMarker(e,p_)}},Zo="2025-06-18",j$=[Zo,"2025-03-26","2024-11-05"],D$=pe(ve(d(),Me())),U$=lt({name:d(),version:d()}),_l=lt({_meta:pe(T({}).loose())}),ln=_l,m_=T({method:d(),params:pe(_l)}),g_=T({applyDefaults:pe(ge())}).loose(),z$=lt({experimental:pe(T({}).loose()),logging:pe(T({}).loose()),prompts:pe(lt({listChanged:pe(ge())})),resources:pe(lt({subscribe:pe(ge()),listChanged:pe(ge())})),tools:pe(lt({listChanged:pe(ge())})),elicitation:pe(g_)});T({elicitation:pe(g_)}).loose();var Z$=ln.extend({protocolVersion:d(),capabilities:z$,serverInfo:U$,instructions:pe(d())}),rp=ln.extend({nextCursor:pe(d())}),F$=T({name:d(),title:pe(d()),description:pe(d()),inputSchema:T({type:R("object"),properties:pe(T({}).loose())}).loose(),outputSchema:pe(T({}).loose()),annotations:pe(T({title:pe(d())}).loose()),_meta:D$}).loose(),V$=rp.extend({tools:q(F$)}),y_=T({type:R("text"),text:d()}).loose(),v_=T({type:R("image"),data:om(),mimeType:d()}).loose(),H$=T({uri:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d()),size:pe(D())}).loose(),B$=rp.extend({resources:q(H$)}),__=T({uri:d(),name:pe(d()),title:pe(d()),mimeType:pe(d())}).loose(),w_=__.extend({text:d()}),b_=__.extend({blob:om()}),k_=T({type:R("resource"),resource:ae([w_,b_])}).loose(),J$=ln.extend({content:q(ae([y_,v_,k_])),structuredContent:pe(Me()),isError:ge().default(!1).optional()}).or(ln.extend({toolResult:Me()})),G$=T({uriTemplate:d(),name:d(),title:pe(d()),description:pe(d()),mimeType:pe(d())}).loose(),W$=ln.extend({resourceTemplates:q(G$)}),K$=ln.extend({contents:q(ae([w_,b_]))}),Y$=T({name:d(),description:pe(d()),required:pe(ge())}).loose(),Q$=T({name:d(),title:pe(d()),description:pe(d()),arguments:pe(q(Y$))}).loose(),X$=rp.extend({prompts:q(Q$)}),e7=T({role:ae([R("user"),R("assistant")]),content:ae([y_,v_,k_])}).loose(),t7=ln.extend({description:pe(d()),messages:q(e7)}),r7=_l.extend({message:d(),requestedSchema:Me()}),T_=m_.extend({method:R("elicitation/create"),params:r7}),n7=ln.extend({action:ae([R("accept"),R("decline"),R("cancel")]),content:pe(ve(d(),Me()))}),wl="2.0",o7=T({jsonrpc:R(wl),id:ae([d(),D().int()])}).merge(m_).strict(),s7=T({jsonrpc:R(wl),id:ae([d(),D().int()]),result:ln}).strict(),a7=T({jsonrpc:R(wl),id:ae([d(),D().int()]),error:T({code:D().int(),message:d(),data:pe(Me())})}).strict(),i7=T({jsonrpc:R(wl)}).merge(T({method:d(),params:pe(_l)})).strict(),aa=ae([o7,i7,s7,a7]),C_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",S_=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:D().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Xt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hm.custom,message:"URL must be parseable",fatal:!0}),dh}).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"}),l7=T({resource:d().url(),authorization_servers:q(Xt).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:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}).passthrough(),I_=T({issuer:d(),authorization_endpoint:Xt,token_endpoint:Xt,registration_endpoint:Xt.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(),c7=T({issuer:d(),authorization_endpoint:Xt,token_endpoint:Xt,userinfo_endpoint:Xt.optional(),jwks_uri:Xt,registration_endpoint:Xt.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(),u7=c7.merge(I_.pick({code_challenge_methods_supported:!0})),d7=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:D().optional(),client_secret_expires_at:D().optional()}).strip(),p7=T({redirect_uris:q(Xt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Xt.optional(),logo_uri:Xt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Xt.optional(),policy_uri:d().optional(),jwks_uri:Xt.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),f7=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),h7=p7.merge(d7),m7="AI_MCPClientOAuthError",x_=`vercel.ai.error.${m7}`,g7=Symbol.for(x_),E_,$_,ia=class extends($_=_e,E_=g7,$_){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[E_]=!0}static isInstance(e){return _e.hasMarker(e,x_)}},Fo=class extends ia{};Fo.errorCode="server_error";var bl=class extends ia{};bl.errorCode="invalid_client";var kl=class extends ia{};kl.errorCode="invalid_grant";var Tl=class extends ia{};Tl.errorCode="unauthorized_client";var y7={[Fo.errorCode]:Fo,[bl.errorCode]:bl,[kl.errorCode]:kl,[Tl.errorCode]:Tl};function v7(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function _7({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 Cl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function Sl(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 w7(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function np(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?np(e,void 0,r):void 0;throw n}}async function R_(e,t,r=fetch){return await np(e,{"MCP-Protocol-Version":t},r)}function b7(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function k7(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Zo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=w7(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await R_(l,i,r);if(!n?.metadataUrl&&b7(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await R_(u,i,r)}return c}async function T7(e,t,r=fetch){const n=await k7(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 l7.parse(await n.json())}function C7(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 S7(e,{fetchFn:t=fetch,protocolVersion:r=Zo}={}){var n;const o={"MCP-Protocol-Version":r},s=C7(e);for(const{url:a,type:i}of s){const l=await np(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 I_.parse(await l.json());{const c=u7.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 I7(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 v0(),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 P_(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 M_(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":x7(o,s,r);return;case"client_secret_post":E7(o,s,n);return;case"none":$7(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function x7(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 $7(e,t){t.set("client_id",e)}async function op(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=f7.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=y7[o]||Fo;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Fo({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 v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=P_(r,v);M_(y,r,p,f)}a&&f.set("resource",a.href);const m=await(l??fetch)(h,{method:"POST",headers:p,body:f});if(!m.ok)throw await op(m);return S_.parse(await m.json())}async function P7(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:[],m=P_(r,f);M_(m,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 op(p);return S_.parse({refresh_token:n,...await p.json()})}async function M7(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 op(s);return h7.parse(await s.json())}async function Il(e,t){var r,n;try{return await sp(e,t)}catch(o){if(o instanceof bl||o instanceof Tl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await sp(e,t);if(o instanceof kl)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await sp(e,t);throw o}}async function O7(e,t,r){const n=v7(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!_7({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 sp(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await T7(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await O7(t,e,a),c=await S7(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 v=await M7(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await R7(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,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 v=await P7(i,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof ia)||v instanceof Fo))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await I7(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}var N7=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":Zo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return $n(t,`ai-sdk/${C_}`,Js())}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=Sl(u);try{if(await Il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Cl;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(m){return(a=this.onerror)==null||a.call(this,m),t(m)}return r(!0)}if(!u.ok||!u.body){let m=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const v=new Ze({message:m});return(i=this.onerror)==null||i.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Po).getReader(),f=async()=>{var m,v,y;try{for(;;){const{done:w,value:_}=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:g,data:C}=_;if(g==="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(g==="message")try{const b=aa.parse(JSON.parse(C));(m=this.onmessage)==null||m.call(this,b)}catch(b){const k=new Ze({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,k)}}}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=Sl(h);try{if(await Il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new Cl;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!h.ok){const p=await h.text().catch(()=>null),f=new Ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${h.status}): ${p}`});(i=this.onerror)==null||i.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},A7=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Zo};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 $n(t,`ai-sdk/${C_}`,Js())}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=Sl(p);try{if(await Il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Cl}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 _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new Ze({message:_});throw(s=this.onerror)==null||s.call(this,g),g}if(!("id"in e))return;const v=p.headers.get("content-type")||"";if(v.includes("application/json")){const w=await p.json(),_=Array.isArray(w)?w.map(g=>aa.parse(g)):[aa.parse(w)];for(const g of _)(a=this.onmessage)==null||a.call(this,g);return}if(v.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 _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Po).getReader();(async()=>{var C,b,k;try{for(;;){const{done:S,value:I}=await _.read();if(S)return;const{event:x,data:j}=I;if(x==="message")try{const O=aa.parse(JSON.parse(j));(C=this.onmessage)==null||C.call(this,O)}catch(O){const U=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:O});(b=this.onerror)==null||b.call(this,U)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const y=new Ze({message:`MCP HTTP Transport Error: Unexpected content type: ${v}`});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=Sl(c);try{if(await Il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Cl;(n=this.onerror)==null||n.call(this,v);return}}catch(m){(o=this.onerror)==null||o.call(this,m);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const m=new Ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,m);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Po).getReader(),f=async()=>{var m,v,y,w;try{for(;;){const{done:_,value:g}=await p.read();if(_)return;const{event:C,data:b,id:k}=g;if(k&&(this.lastInboundEventId=k),C==="message")try{const S=aa.parse(JSON.parse(b));(m=this.onmessage)==null||m.call(this,S)}catch(S){const I=new Ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,I)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),(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 q7(e){switch(e.type){case"sse":return new N7(e);case"http":return new A7(e);default:throw new Ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function L7(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var j7="1.0.0";function O_({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 U7(e);return await t.init(),t}var U7=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=j7,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},L7(e)?this.transport=e:this.transport=q7(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:Zo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Z$});if(e===void 0)throw new Ze({message:"Server sent invalid initialize result"});if(!j$.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:V$,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:J$,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:B$,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:W$,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:X$,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:t7,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,m=async(y,w)=>{var _;(_=w?.abortSignal)==null||_.throwIfAborted();const g=await p.callTool({name:s,args:y,options:w});return f!=null?p.extractStructuredContent(g,f,s):g},v=t==="automatic"?jg({description:i,title:h,inputSchema:Uo({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:m,toModelOutput:O_}):{description:i,title:h,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:m,toModelOutput:O_};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await dr({value:e.structuredContent,schema:ro(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 pr({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!==T_)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=T_.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=n7.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}))}},ap=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),D()]).nullish()})}),Mr=Rn({errorSchema:ap,errorToMessage:e=>e.error.message});function N_(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("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 A_(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 z7({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,${jo(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 Ur({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:jo(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:jo(i.data),format:"mp3"}};default:throw new Ur({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Ur({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,${jo(i.data)}`}}}else throw new Ur({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 ip({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function q_(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 Z7=be(()=>we(T({id:d().nullish(),created:D().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:D(),end_index:D(),url:d(),title:d()})})).nullish()}),index:D(),logprobs:T({content:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}))),F7=be(()=>we(ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({delta:T({role:ye(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:D(),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:D(),end_index:D(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:D()})),usage:T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}),ap]))),V7=be(()=>we(T({logitBias:ve(mm(),D()).optional(),logprobs:ae([ge(),D()]).optional(),parallelToolCalls:ge().optional(),user:d().optional(),reasoningEffort:ye(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:D().optional(),store:ge().optional(),metadata:ve(d().max(64),d().max(512)).optional(),prediction:ve(d(),Tt()).optional(),serviceTier:ye(["auto","flex","priority","default"]).optional(),strictJsonSchema:ge().optional(),textVerbosity:ye(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:ye(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:ye(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));function H7({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 Ur({functionality:`tool choice type: ${s}`})}}}var B7=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,m,v,y,w;const _=[],g=(f=await sn({provider:"openai",providerOptions:p,schema:V7}))!=null?f:{},C=N_(this.modelId),b=(m=g.forceReasoning)!=null?m:C.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:k,warnings:S}=z7({prompt:e,systemMessageMode:(v=g.systemMessageMode)!=null?v:b?"developer":C.systemMessageMode});_.push(...S);const I=(y=g.strictJsonSchema)!=null?y:!0,x={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs=="number"?!0:void 0,top_logprobs:typeof g.logprobs=="number"?g.logprobs:typeof g.logprobs=="boolean"&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.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:I,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:g.reasoningEffort,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:k};b?((g.reasoningEffort!=="none"||!C.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,_.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,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!C.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),g.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(_.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:j,toolChoice:O,toolWarnings:U}=H7({tools:u,toolChoice:h});return{args:{...x,tools:j,tool_choice:O},warnings:[..._,...U]}}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 Yt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:l,failedResponseHandler:Mr,successfulResponseHandler:fr(Z7),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=h.choices[0],m=[],v=f.message.content;v!=null&&v.length>0&&m.push({type:"text",text:v});for(const _ of(t=f.message.tool_calls)!=null?t:[])m.push({type:"tool-call",toolCallId:(r=_.id)!=null?r:Zt(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])m.push({type:"source",sourceType:"url",id:Zt(),url:_.url_citation.url,title:_.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:m,finishReason:{unified:q_(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:A_(h.usage),request:{body:l},response:{...ip(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 Yt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Mr,successfulResponseHandler:cl(F7),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 m,v,y,w,_,g,C,b,k,S,I,x,j,O,U,A,N;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const G=p.value;if("error"in G){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:G.error});return}if(!c){const K=ip(G);Object.values(K).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...ip(G)}))}G.usage!=null&&(l=G.usage,((m=G.usage.completion_tokens_details)==null?void 0:m.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(v=G.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=G.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=G.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const X=G.choices[0];if(X?.finish_reason!=null&&(i={unified:q_(X.finish_reason),raw:X.finish_reason}),((_=X?.logprobs)==null?void 0:_.content)!=null&&(h.openai.logprobs=X.logprobs.content),X?.delta==null)return;const Q=X.delta;if(Q.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:Q.content})),Q.tool_calls!=null)for(const K of Q.tool_calls){const he=K.index;if(a[he]==null){if(K.type!=null&&K.type!=="function")throw new _d({data:K,message:"Expected 'function' type."});if(K.id==null)throw new _d({data:K,message:"Expected 'id' to be a string."});if(((g=K.function)==null?void 0:g.name)==null)throw new _d({data:K,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),a[he]={id:K.id,type:"function",function:{name:K.function.name,arguments:(C=K.function.arguments)!=null?C:""},hasFinished:!1};const P=a[he];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),Ng(P.function.arguments)&&(f.enqueue({type:"tool-input-end",id:P.id}),f.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:Zt(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const V=a[he];V.hasFinished||(((I=K.function)==null?void 0:I.arguments)!=null&&(V.function.arguments+=(j=(x=K.function)==null?void 0:x.arguments)!=null?j:""),f.enqueue({type:"tool-input-delta",id:V.id,delta:(O=K.function.arguments)!=null?O:""}),((U=V.function)==null?void 0:U.name)!=null&&((A=V.function)==null?void 0:A.arguments)!=null&&Ng(V.function.arguments)&&(f.enqueue({type:"tool-input-end",id:V.id}),f.enqueue({type:"tool-call",toolCallId:(N=V.id)!=null?N:Zt(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}if(Q.annotations!=null)for(const K of Q.annotations)f.enqueue({type:"source",sourceType:"url",id:Zt(),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:A_(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function L_(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 J7({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
|
|
587
|
+
`,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Qn({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
590
|
`;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Ur({functionality:"tool-call messages"})}}).join("");n+=`${r}:
|
|
@@ -592,9 +592,9 @@ ${a}
|
|
|
592
592
|
|
|
593
593
|
`;break}case"tool":throw new Ur({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
|
|
594
594
|
`,{prompt:n,stopSequences:[`
|
|
595
|
-
${t}:`]}}function M_({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 O_(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 Z7=be(()=>we(T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(D()),top_logprobs:q(ve(d(),D())).nullish()}).nullish()})),usage:T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}))),F7=be(()=>we(ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:D(),logprobs:T({tokens:q(d()),token_logprobs:q(D()),top_logprobs:q(ve(d(),D())).nullish()}).nullish()})),usage:T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}),Xd]))),N_=be(()=>we(T({echo:ge().optional(),logitBias:ve(d(),D()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([ge(),D()]).optional()}))),V7=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 sn({provider:"openai",providerOptions:p,schema:N_}),...await sn({provider:this.providerOptionsName,providerOptions:p,schema:N_})};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:v,stopSequences:y}=z7({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:v,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 Yt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:r,failedResponseHandler:Mr,successfulResponseHandler:fr(Z7),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:P_(s.usage),finishReason:{unified:O_(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...M_(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 Yt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Mr,successfulResponseHandler:al(F7),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",...M_(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:O_(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:P_(l)})}})),request:{body:n},response:{headers:o}}}},H7=be(()=>we(T({dimensions:D().optional(),user:d().optional()}))),B7=be(()=>we(T({data:q(T({embedding:q(D())})),usage:T({prompt_tokens:D()}).nullish()}))),J7=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 NI({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await sn({provider:"openai",providerOptions:n,schema:H7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Yt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:qt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Mr,successfulResponseHandler:fr(B7),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}}}},A_=be(()=>we(T({created:D().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:D().nullish(),output_tokens:D().nullish(),total_tokens:D().nullish(),input_tokens_details:T({image_tokens:D().nullish(),text_tokens:D().nullish()}).nullish()}).nullish()}))),G7={"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},W7=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function K7(e){return W7.some(t=>e.startsWith(t))}var Y7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=G7[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,v,y,w,_,m,C;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&b.push({type:"unsupported",feature:"seed"});const k=(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:E,responseHeaders:j}=await Rg({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:qt(this.config.headers(),l),formData:zI({model:this.modelId,prompt:e,image:await Promise.all(t.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([Ao(O.data)],{type:O.mediaType})],{type:O.mediaType}):gg(O.url))),mask:r!=null?await Q7(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:Mr,successfulResponseHandler:fr(A_),abortSignal:c,fetch:this.config.fetch});return{images:E.data.map(O=>O.b64_json),warnings:b,usage:E.usage!=null?{inputTokens:(g=E.usage.input_tokens)!=null?g:void 0,outputTokens:(v=E.usage.output_tokens)!=null?v:void 0,totalTokens:(y=E.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:E.data.map((O,U)=>{var A,N,G,X,Q,K;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(A=E.created)!=null?A:void 0,size:(N=E.size)!=null?N:void 0,quality:(G=E.quality)!=null?G:void 0,background:(X=E.background)!=null?X:void 0,outputFormat:(Q=E.output_format)!=null?Q:void 0,...q_((K=E.usage)==null?void 0:K.input_tokens_details,U,E.data.length)}})}}}}const{value:S,responseHeaders:I}=await Yt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:qt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...K7(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Mr,successfulResponseHandler:fr(A_),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(E=>E.b64_json),warnings:b,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_: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:k,modelId:this.modelId,headers:I},providerMetadata:{openai:{images:S.data.map((E,j)=>{var O,U,A,N,G,X;return{...E.revised_prompt?{revisedPrompt:E.revised_prompt}:{},created:(O=S.created)!=null?O:void 0,size:(U=S.size)!=null?U:void 0,quality:(A=S.quality)!=null?A:void 0,background:(N=S.background)!=null?N:void 0,outputFormat:(G=S.output_format)!=null?G:void 0,...q_((X=S.usage)==null?void 0:X.input_tokens_details,j,S.data.length)}})}}}}};function q_(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 Q7(e){if(!e)return;if(e.type==="url")return gg(e.url);const t=e.data instanceof Uint8Array?e.data:Ao(e.data);return new Blob([t],{type:e.mediaType})}var L_=be(()=>we(T({callId:d(),operation:Ue("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()})])}))),j_=be(()=>we(T({status:ye(["completed","failed"]),output:d().optional()}))),X7=$r({id:"openai.apply_patch",inputSchema:L_,outputSchema:j_}),eR=X7,tR=be(()=>we(T({code:d().nullish(),containerId:d()}))),rR=be(()=>we(T({outputs:q(Ue("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullish()}))),nR=be(()=>we(T({container:ae([d(),T({fileIds:q(d()).optional()})]).optional()}))),oR=$r({id:"openai.code_interpreter",inputSchema:tR,outputSchema:rR}),sR=(e={})=>oR(e),aR=be(()=>we(T({name:d(),description:d().optional(),format:ae([T({type:R("grammar"),syntax:ye(["regex","lark"]),definition:d()}),T({type:R("text")})]).optional()}))),iR=be(()=>we(d())),lR=G5({id:"openai.custom",inputSchema:iR}),cR=e=>lR(e),D_=T({key:d(),type:ye(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),D(),ge(),q(d())])}),U_=T({type:ye(["and","or"]),filters:q(ae([D_,gc(()=>U_)]))}),uR=be(()=>we(T({vectorStoreIds:q(d()),maxNumResults:D().optional(),ranking:T({ranker:d().optional(),scoreThreshold:D().optional()}).optional(),filters:ae([D_,U_]).optional()}))),dR=be(()=>we(T({queries:q(d()),results:q(T({attributes:ve(d(),Me()),fileId:d(),filename:d(),score:D(),text:d()})).nullable()}))),pR=$r({id:"openai.file_search",inputSchema:T({}),outputSchema:dR}),fR=be(()=>we(T({background:ye(["auto","opaque","transparent"]).optional(),inputFidelity:ye(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:ye(["auto"]).optional(),outputCompression:D().int().min(0).max(100).optional(),outputFormat:ye(["png","jpeg","webp"]).optional(),partialImages:D().int().min(0).max(3).optional(),quality:ye(["auto","low","medium","high"]).optional(),size:ye(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),hR=be(()=>we(T({}))),mR=be(()=>we(T({result:d()}))),gR=$r({id:"openai.image_generation",inputSchema:hR,outputSchema:mR}),yR=(e={})=>gR(e),z_=be(()=>we(T({action:T({type:R("exec"),command:q(d()),timeoutMs:D().optional(),user:d().optional(),workingDirectory:d().optional(),env:ve(d(),d()).optional()})}))),Z_=be(()=>we(T({output:d()}))),vR=$r({id:"openai.local_shell",inputSchema:z_,outputSchema:Z_}),F_=be(()=>we(T({action:T({commands:q(d()),timeoutMs:D().optional(),maxOutputLength:D().optional()})}))),tp=be(()=>we(T({output:q(T({stdout:d(),stderr:d(),outcome:Ue("type",[T({type:R("timeout")}),T({type:R("exit"),exitCode:D()})])}))}))),_R=q(Ue("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(),wR=be(()=>we(T({environment:ae([T({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:ye(["1g","4g","16g","64g"]).optional(),networkPolicy:Ue("type",[T({type:R("disabled")}),T({type:R("allowlist"),allowedDomains:q(d()),domainSecrets:q(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:_R}),T({type:R("containerReference"),containerId:d()}),T({type:R("local").optional(),skills:q(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),bR=$r({id:"openai.shell",inputSchema:F_,outputSchema:tp}),kR=be(()=>we(T({externalWebAccess:ge().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:ye(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),TR=be(()=>we(T({}))),CR=be(()=>we(T({action:Ue("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(Ue("type",[T({type:R("url"),url:d()}),T({type:R("api"),name:d()})])).optional()}))),SR=$r({id:"openai.web_search",inputSchema:TR,outputSchema:CR}),IR=(e={})=>SR(e),ER=be(()=>we(T({searchContextSize:ye(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),xR=be(()=>we(T({}))),$R=be(()=>we(T({action:Ue("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()}))),RR=$r({id:"openai.web_search_preview",inputSchema:xR,outputSchema:$R}),rp=gc(()=>ae([d(),D(),ge(),Ei(),q(rp),ve(d(),rp)])),PR=be(()=>we(T({serverLabel:d(),allowedTools:ae([q(d()),T({readOnly:ge().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ve(d(),d()).optional(),requireApproval:ae([ye(["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."))),MR=be(()=>we(T({}))),OR=be(()=>we(T({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),rp]).optional()}))),NR=$r({id:"openai.mcp",inputSchema:MR,outputSchema:OR}),AR=e=>NR(e),qR={applyPatch:eR,customTool:cR,codeInterpreter:sR,fileSearch:pR,imageGeneration:yR,localShell:vR,shell:bR,webSearchPreview:RR,webSearch:IR,mcp:AR};function V_(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 LR({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var h,p,f,g,v,y,w,_,m,C,b,k,S;const I=[],E=[],j=new Set;for(const{role:O,content:U}of e)switch(O){case"system":{switch(r){case"system":{I.push({role:"system",content:U});break}case"developer":{I.push({role:"developer",content:U});break}case"remove":{E.push({type:"other",message:"system messages are removed for this model"});break}default:{const A=r;throw new Error(`Unsupported system message mode: ${A}`)}}break}case"user":{I.push({role:"user",content:U.map((A,N)=>{var G,X,Q;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const K=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&H_(A.data,o)?{file_id:A.data}:{image_url:`data:${K};base64,${Lo(A.data)}`},detail:(X=(G=A.providerOptions)==null?void 0:G[n])==null?void 0:X.imageDetail}}else{if(A.mediaType==="application/pdf")return A.data instanceof URL?{type:"input_file",file_url:A.data.toString()}:{type:"input_file",...typeof A.data=="string"&&H_(A.data,o)?{file_id:A.data}:{filename:(Q=A.filename)!=null?Q:`part-${N}.pdf`,file_data:`data:application/pdf;base64,${Lo(A.data)}`}};throw new Ur({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const N of U)switch(N.type){case"text":{const G=(h=N.providerOptions)==null?void 0:h[n],X=G?.itemId,Q=G?.phase;if(a&&X!=null)break;if(s&&X!=null){I.push({type:"item_reference",id:X});break}I.push({role:"assistant",content:[{type:"output_text",text:N.text}],id:X,...Q!=null&&{phase:Q}});break}case"tool-call":{const G=(y=(f=(p=N.providerOptions)==null?void 0:p[n])==null?void 0:f.itemId)!=null?y:(v=(g=N.providerMetadata)==null?void 0:g[n])==null?void 0:v.itemId;if(a&&G!=null)break;if(N.providerExecuted){s&&G!=null&&I.push({type:"item_reference",id:G});break}if(s&&G!=null){I.push({type:"item_reference",id:G});break}const X=t.toProviderToolName(N.toolName);if(i&&X==="local_shell"){const Q=await St({value:N.input,schema:z_});I.push({type:"local_shell_call",call_id:N.toolCallId,id:G,action:{type:"exec",command:Q.action.command,timeout_ms:Q.action.timeoutMs,user:Q.action.user,working_directory:Q.action.workingDirectory,env:Q.action.env}});break}if(l&&X==="shell"){const Q=await St({value:N.input,schema:F_});I.push({type:"shell_call",call_id:N.toolCallId,id:G,status:"completed",action:{commands:Q.action.commands,timeout_ms:Q.action.timeoutMs,max_output_length:Q.action.maxOutputLength}});break}if(c&&X==="apply_patch"){const Q=await St({value:N.input,schema:L_});I.push({type:"apply_patch_call",call_id:Q.callId,id:G,status:"completed",operation:Q.operation});break}if(u?.has(X)){I.push({type:"custom_tool_call",call_id:N.toolCallId,name:X,input:typeof N.input=="string"?N.input:JSON.stringify(N.input),id:G});break}I.push({type:"function_call",call_id:N.toolCallId,name:X,arguments:JSON.stringify(N.input),id:G});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 G=t.toProviderToolName(N.toolName);if(l&&G==="shell"){if(N.output.type==="json"){const X=await St({value:N.output.value,schema:tp});I.push({type:"shell_call_output",call_id:N.toolCallId,output:X.output.map(Q=>({stdout:Q.stdout,stderr:Q.stderr,outcome:Q.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Q.outcome.exitCode}}))})}break}if(s){const X=(m=(_=(w=N.providerOptions)==null?void 0:w[n])==null?void 0:_.itemId)!=null?m:N.toolCallId;I.push({type:"item_reference",id:X})}else E.push({type:"other",message:`Results for OpenAI tool ${N.toolName} are not sent to the API when store is false`});break}case"reasoning":{const G=await sn({provider:n,providerOptions:N.providerOptions,schema:jR}),X=G?.itemId;if(a&&X!=null)break;if(X!=null){const Q=A[X];if(s)Q===void 0&&(I.push({type:"item_reference",id:X}),A[X]={type:"reasoning",id:X,summary:[]});else{const K=[];N.text.length>0?K.push({type:"summary_text",text:N.text}):Q!==void 0&&E.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(N)}.`}),Q===void 0?(A[X]={type:"reasoning",id:X,encrypted_content:G?.reasoningEncryptedContent,summary:K},I.push(A[X])):(Q.summary.push(...K),G?.reasoningEncryptedContent!=null&&(Q.encrypted_content=G.reasoningEncryptedContent))}}else{const Q=G?.reasoningEncryptedContent;if(Q!=null){const K=[];N.text.length>0&&K.push({type:"summary_text",text:N.text}),I.push({type:"reasoning",encrypted_content:Q,summary:K})}else E.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(N)}.`})}break}}break}case"tool":{for(const A of U){if(A.type==="tool-approval-response"){const Q=A;if(j.has(Q.approvalId))continue;j.add(Q.approvalId),s&&I.push({type:"item_reference",id:Q.approvalId}),I.push({type:"mcp_approval_response",approval_request_id:Q.approvalId,approve:Q.approved});continue}const N=A.output;if(N.type==="execution-denied"&&((b=(C=N.providerOptions)==null?void 0:C.openai)==null?void 0:b.approvalId))continue;const G=t.toProviderToolName(A.toolName);if(i&&G==="local_shell"&&N.type==="json"){const Q=await St({value:N.value,schema:Z_});I.push({type:"local_shell_call_output",call_id:A.toolCallId,output:Q.output});continue}if(l&&G==="shell"&&N.type==="json"){const Q=await St({value:N.value,schema:tp});I.push({type:"shell_call_output",call_id:A.toolCallId,output:Q.output.map(K=>({stdout:K.stdout,stderr:K.stderr,outcome:K.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:K.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&N.type==="json"){const Q=await St({value:N.value,schema:j_});I.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:Q.status,output:Q.output});continue}if(u?.has(G)){let Q;switch(N.type){case"text":case"error-text":Q=N.value;break;case"execution-denied":Q=(k=N.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":Q=JSON.stringify(N.value);break;case"content":Q=N.value.map(K=>{var he;switch(K.type){case"text":return{type:"input_text",text:K.text};case"image-data":return{type:"input_image",image_url:`data:${K.mediaType};base64,${K.data}`};case"image-url":return{type:"input_image",image_url:K.url};case"file-data":return{type:"input_file",filename:(he=K.filename)!=null?he:"data",file_data:`data:${K.mediaType};base64,${K.data}`};default:E.push({type:"other",message:`unsupported custom tool content part type: ${K.type}`});return}}).filter(wg);break;default:Q=""}I.push({type:"custom_tool_call_output",call_id:A.toolCallId,output:Q});continue}let X;switch(N.type){case"text":case"error-text":X=N.value;break;case"execution-denied":X=(S=N.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":X=JSON.stringify(N.value);break;case"content":X=N.value.map(Q=>{var K;switch(Q.type){case"text":return{type:"input_text",text:Q.text};case"image-data":return{type:"input_image",image_url:`data:${Q.mediaType};base64,${Q.data}`};case"image-url":return{type:"input_image",image_url:Q.url};case"file-data":return{type:"input_file",filename:(K=Q.filename)!=null?K:"data",file_data:`data:${Q.mediaType};base64,${Q.data}`};default:{E.push({type:"other",message:`unsupported tool content part type: ${Q.type}`});return}}}).filter(wg);break}I.push({type:"function_call_output",call_id:A.toolCallId,output:X})}break}default:{const A=O;throw new Error(`Unsupported role: ${A}`)}}return{input:I,warnings:E}}var jR=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function B_({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 DR=be(()=>we(ae([T({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}),T({type:ye(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:D(),input_tokens_details:T({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:T({reasoning_tokens:D().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:R("response.created"),response:T({id:d(),created_at:D(),model:d(),service_tier:d().nullish()})}),T({type:R("response.output_item.added"),output_index:D(),item:Ue("type",[T({type:R("message"),id:d(),phase:ye(["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(Ue("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:ye(["in_progress","completed"]),operation:Ue("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("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),T({type:R("shell_call"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ue("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])}),T({type:R("response.output_item.done"),output_index:D(),item:Ue("type",[T({type:R("message"),id:d(),phase:ye(["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("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:R("completed")}),T({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ue("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:Ue("type",[T({type:R("search"),query:d().nullish(),sources:q(Ue("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:ve(d(),ae([d(),D(),ge()])),file_id:d(),filename:d(),score:D(),text:d()})).nullish()}),T({type:R("local_shell_call"),id:d(),call_id:d(),action:T({type:R("exec"),command:q(d()),timeout_ms:D().optional(),user:d().optional(),working_directory:d().optional(),env:ve(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:ae([d(),T({type:d().optional(),code:ae([D(),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:Tt(),annotations:ve(d(),Me()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([D(),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:ye(["in_progress","completed"]),operation:Ue("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:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ue("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])}),T({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.custom_tool_call_input.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:D(),partial_image_b64:d()}),T({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:D(),code:d()}),T({type:R("response.output_text.annotation.added"),annotation:Ue("type",[T({type:R("url_citation"),start_index:D(),end_index:D(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:D()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:D(),end_index:D()}),T({type:R("file_path"),file_id:d(),index:D()})])}),T({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:D()}),T({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:D(),delta:d()}),T({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:D()}),T({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:D(),delta:d(),obfuscation:d().nullish()}),T({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:D(),diff:d()}),T({type:R("error"),sequence_number:D(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),UR=be(()=>we(T({id:d().optional(),created_at:D().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(Ue("type",[T({type:R("message"),role:R("assistant"),id:d(),phase:ye(["commentary","final_answer"]).nullish(),content:q(T({type:R("output_text"),text:d(),logprobs:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish(),annotations:q(Ue("type",[T({type:R("url_citation"),start_index:D(),end_index:D(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:D()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:D(),end_index:D()}),T({type:R("file_path"),file_id:d(),index:D()})]))}))}),T({type:R("web_search_call"),id:d(),status:d(),action:Ue("type",[T({type:R("search"),query:d().nullish(),sources:q(Ue("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:ve(d(),ae([d(),D(),ge()])),file_id:d(),filename:d(),score:D(),text:d()})).nullish()}),T({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ue("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:D().optional(),user:d().optional(),working_directory:d().optional(),env:ve(d(),d()).optional()})}),T({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:R("custom_tool_call"),call_id:d(),name:d(),input: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:ae([d(),T({type:d().optional(),code:ae([D(),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:Tt(),annotations:ve(d(),Me()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([D(),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:ye(["in_progress","completed"]),operation:Ue("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:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ue("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:D(),input_tokens_details:T({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:T({reasoning_tokens:D().nullish()}).nullish()}).optional()}))),J_=20,G_=be(()=>we(T({conversation:d().nullish(),include:q(ye(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([ge(),D().min(1).max(J_)]).optional(),maxToolCalls:D().nullish(),metadata:Tt().nullish(),parallelToolCalls:ge().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:ye(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:ye(["auto","flex","priority","default"]).nullish(),store:ge().nullish(),strictJsonSchema:ge().nullish(),textVerbosity:ye(["low","medium","high"]).nullish(),truncation:ye(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:ye(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));async function zR({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o;e=e?.length?e:void 0;const s=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const a=[],i=n??new Set;for(const c of e)switch(c.type){case"function":a.push({type:"function",name:c.name,description:c.description,parameters:c.inputSchema,...c.strict!=null?{strict:c.strict}:{}});break;case"provider":{switch(c.id){case"openai.file_search":{const u=await St({value:c.args,schema:uR});a.push({type:"file_search",vector_store_ids:u.vectorStoreIds,max_num_results:u.maxNumResults,ranking_options:u.ranking?{ranker:u.ranking.ranker,score_threshold:u.ranking.scoreThreshold}:void 0,filters:u.filters});break}case"openai.local_shell":{a.push({type:"local_shell"});break}case"openai.shell":{const u=await St({value:c.args,schema:wR});a.push({type:"shell",...u.environment&&{environment:ZR(u.environment)}});break}case"openai.apply_patch":{a.push({type:"apply_patch"});break}case"openai.web_search_preview":{const u=await St({value:c.args,schema:ER});a.push({type:"web_search_preview",search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.web_search":{const u=await St({value:c.args,schema:kR});a.push({type:"web_search",filters:u.filters!=null?{allowed_domains:u.filters.allowedDomains}:void 0,external_web_access:u.externalWebAccess,search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.code_interpreter":{const u=await St({value:c.args,schema:nR});a.push({type:"code_interpreter",container:u.container==null?{type:"auto",file_ids:void 0}:typeof u.container=="string"?u.container:{type:"auto",file_ids:u.container.fileIds}});break}case"openai.image_generation":{const u=await St({value:c.args,schema:fR});a.push({type:"image_generation",background:u.background,input_fidelity:u.inputFidelity,input_image_mask:u.inputImageMask?{file_id:u.inputImageMask.fileId,image_url:u.inputImageMask.imageUrl}:void 0,model:u.model,moderation:u.moderation,partial_images:u.partialImages,quality:u.quality,output_compression:u.outputCompression,output_format:u.outputFormat,size:u.size});break}case"openai.mcp":{const u=await St({value:c.args,schema:PR}),h=g=>({tool_names:g.toolNames}),p=u.requireApproval,f=p==null?void 0:typeof p=="string"?p:p.never!=null?{never:h(p.never)}:void 0;a.push({type:"mcp",server_label:u.serverLabel,allowed_tools:Array.isArray(u.allowedTools)?u.allowedTools:u.allowedTools?{read_only:u.allowedTools.readOnly,tool_names:u.allowedTools.toolNames}:void 0,authorization:u.authorization,connector_id:u.connectorId,headers:u.headers,require_approval:f??"never",server_description:u.serverDescription,server_url:u.serverUrl});break}case"openai.custom":{const u=await St({value:c.args,schema:aR});a.push({type:"custom",name:u.name,description:u.description,format:u.format}),i.add(u.name);break}}break}default:s.push({type:"unsupported",feature:`function tool ${c}`});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:s};const l=t.type;switch(l){case"auto":case"none":case"required":return{tools:a,toolChoice:l,toolWarnings:s};case"tool":{const c=(o=r?.toProviderToolName(t.toolName))!=null?o:t.toolName;return{tools:a,toolChoice:c==="code_interpreter"||c==="file_search"||c==="image_generation"||c==="web_search_preview"||c==="web_search"||c==="mcp"||c==="apply_patch"?{type:c}:i.has(c)?{type:"custom",name:c}:{type:"function",name:c},toolWarnings:s}}default:{const c=l;throw new Ur({functionality:`tool choice type: ${c}`})}}}function ZR(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:FR(r.skills)}}return{type:"local",skills:e.skills}}function FR(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 W_(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,v,y,w,_,m,C,b;const k=[],S=x_(this.modelId);o!=null&&k.push({type:"unsupported",feature:"topK"}),i!=null&&k.push({type:"unsupported",feature:"seed"}),s!=null&&k.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&k.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&k.push({type:"unsupported",feature:"stopSequences"});const I=this.config.provider.includes("azure")?"azure":"openai";let E=await sn({provider:I,providerOptions:c,schema:G_});E==null&&I!=="openai"&&(E=await sn({provider:"openai",providerOptions:c,schema:G_}));const j=(f=E?.forceReasoning)!=null?f:S.isReasoningModel;E?.conversation&&E?.previousResponseId&&k.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const O=LI({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"},resolveProviderToolName:te=>te.id==="openai.custom"?te.args.name:void 0}),U=new Set,{tools:A,toolChoice:N,toolWarnings:G}=await zR({tools:u,toolChoice:h,toolNameMapping:O,customProviderToolNames:U}),{input:X,warnings:Q}=await LR({prompt:l,toolNameMapping:O,systemMessageMode:(g=E?.systemMessageMode)!=null?g:j?"developer":S.systemMessageMode,providerOptionsName:I,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=E?.store)!=null?v:!0,hasConversation:E?.conversation!=null,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch"),customProviderToolNames:U.size>0?U:void 0});k.push(...Q);const K=(y=E?.strictJsonSchema)!=null?y:!0;let he=E?.include;function V(te){he==null?he=[te]:he.includes(te)||(he=[...he,te])}function P(te){return u?.find(se=>se.type==="provider"&&se.id===te)!=null}const H=typeof E?.logprobs=="number"?E?.logprobs:E?.logprobs===!0?J_:void 0;H&&V("message.output_text.logprobs");const Z=(w=u?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:w.name;Z&&V("web_search_call.action.sources"),P("openai.code_interpreter")&&V("code_interpreter_call.outputs");const x=E?.store;x===!1&&j&&V("reasoning.encrypted_content");const M={model:this.modelId,input:X,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||E?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:K,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...E?.textVerbosity&&{verbosity:E.textVerbosity}}},conversation:E?.conversation,max_tool_calls:E?.maxToolCalls,metadata:E?.metadata,parallel_tool_calls:E?.parallelToolCalls,previous_response_id:E?.previousResponseId,store:x,user:E?.user,instructions:E?.instructions,service_tier:E?.serviceTier,include:he,prompt_cache_key:E?.promptCacheKey,prompt_cache_retention:E?.promptCacheRetention,safety_identifier:E?.safetyIdentifier,top_logprobs:H,truncation:E?.truncation,...j&&(E?.reasoningEffort!=null||E?.reasoningSummary!=null)&&{reasoning:{...E?.reasoningEffort!=null&&{effort:E.reasoningEffort},...E?.reasoningSummary!=null&&{summary:E.reasoningSummary}}}};j?E?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(E?.reasoningEffort!=null&&k.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),E?.reasoningSummary!=null&&k.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),E?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),E?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(k.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 L=(b=(C=(m=u?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:m.args)==null?void 0:C.environment)==null?void 0:b.type,W=L==="containerAuto"||L==="containerReference";return{webSearchToolName:Z,args:{...M,tools:A,tool_choice:N},warnings:[...k,...G],store:x,toolNameMapping:O,providerOptionsName:I,isShellProviderExecuted:W}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,g,v,y,w,_,m,C,b,k,S,I,E;const{args:j,warnings:O,webSearchToolName:U,toolNameMapping:A,providerOptionsName:N,isShellProviderExecuted:G}=await this.getArgs(e),X=this.config.url({path:"/responses",modelId:this.modelId}),Q=W_(e.prompt),{responseHeaders:K,value:he,rawValue:V}=await Yt({url:X,headers:qt(this.config.headers(),e.headers),body:j,failedResponseHandler:Mr,successfulResponseHandler:fr(UR),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new ct({message:he.error.message,url:X,requestBodyValues:j,statusCode:400,responseHeaders:K,responseBody:V,isRetryable:!1});const P=[],H=[];let Z=!1;for(const L of he.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const W of L.summary)P.push({type:"reasoning",text:W.text,providerMetadata:{[N]:{itemId:L.id,reasoningEncryptedContent:(t=L.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),result:{result:L.result}});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:L.action}),providerMetadata:{[N]:{itemId:L.id}}});break}case"shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:L.action.commands}}),...G&&{providerExecuted:!0},providerMetadata:{[N]:{itemId:L.id}}});break}case"shell_call_output":{P.push({type:"tool-result",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),result:{output:L.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="exit"?{type:"exit",exitCode:W.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const W of L.content){(n=(r=e.providerOptions)==null?void 0:r[N])!=null&&n.logprobs&&W.logprobs&&H.push(W.logprobs);const te={itemId:L.id,...L.phase!=null&&{phase:L.phase},...W.annotations.length>0&&{annotations:W.annotations}};P.push({type:"text",text:W.text,providerMetadata:{[N]:te}});for(const se of W.annotations)se.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:Zt(),url:se.url,title:se.title}):se.type==="file_citation"?P.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:se.filename,filename:se.filename,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?P.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:se.filename,filename:se.filename,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:Zt(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{Z=!0,P.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{[N]:{itemId:L.id}}});break}case"custom_tool_call":{Z=!0;const W=A.toCustomToolName(L.name);P.push({type:"tool-call",toolCallId:L.call_id,toolName:W,input:JSON.stringify(L.input),providerMetadata:{[N]:{itemId:L.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName(U??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName(U??"web_search"),result:Y_(L.action)});break}case"mcp_call":{const W=L.approval_request_id!=null&&(y=Q[L.approval_request_id])!=null?y:L.id,te=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:W,toolName:te,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-result",toolCallId:W,toolName:te,result:{type:"call",serverLabel:L.server_label,name:L.name,arguments:L.arguments,...L.output!=null?{output:L.output}:{},...L.error!=null?{error:L.error}:{}},providerMetadata:{[N]:{itemId:L.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const W=(w=L.approval_request_id)!=null?w:L.id,te=(C=(m=(_=this.config).generateId)==null?void 0:m.call(_))!=null?C:Zt(),se=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:te,toolName:se,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-approval-request",approvalId:W,toolCallId:te});break}case"computer_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:L.status||"completed"}});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),result:{queries:L.queries,results:(k=(b=L.results)==null?void 0:b.map(W=>({attributes:W.attributes,fileId:W.file_id,filename:W.filename,score:W.score,text:W.text})))!=null?k:null}});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:L.code,containerId:L.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:L.outputs}});break}case"apply_patch_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:L.call_id,operation:L.operation}),providerMetadata:{[N]:{itemId:L.id}}});break}}const x={[N]:{responseId:he.id,...H.length>0?{logprobs:H}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},M=he.usage;return{content:P,finishReason:{unified:B_({finishReason:(S=he.incomplete_details)==null?void 0:S.reason,hasFunctionCall:Z}),raw:(E=(I=he.incomplete_details)==null?void 0:I.reason)!=null?E:void 0},usage:V_(M),request:{body:j},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:K,body:V},providerMetadata:x,warnings:O}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await Yt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Mr,successfulResponseHandler:al(DR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,h=W_(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const v=[];let y=null;const w={},_=[];let m,C=!1;const b={};let k;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,I){var E,j,O,U,A,N,G,X,Q,K,he,V,P,H,Z,x,M,L,W,te,se,Se,z,F,Y,ee,ue,Ee,He,ot,ft,et;if(e.includeRawChunks&&I.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},I.enqueue({type:"error",error:S.error});return}const $=S.value;if(K_($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const ne=o.toCustomToolName($.item.name);w[$.output_index]={toolName:ne,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:ne})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:ne,operation:Le}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Le.type==="delete_file",endEmitted:Le.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:ne,toolName:o.toCustomToolName("apply_patch")}),Le.type==="delete_file"){const _t=JSON.stringify({callId:ne,operation:Le});I.enqueue({type:"tool-input-delta",id:ne,delta:_t}),I.enqueue({type:"tool-input-end",id:ne})}else I.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${io(ne)}","operation":{"type":"${io(Le.type)}","path":"${io(Le.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(_.splice(0,_.length),m=(E=$.item.phase)!=null?E:void 0,I.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):K_($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(j=$.item.encrypted_content)!=null?j:null}}})))}else if(BR($)){if($.item.type==="message"){const ne=(O=$.item.phase)!=null?O:m;m=void 0,I.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...ne!=null&&{phase:ne},..._.length>0&&{annotations:_}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,C=!0,I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,C=!0;const ne=o.toCustomToolName($.item.name);I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:ne,input:JSON.stringify($.item.input),providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:Y_($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(A=(U=$.item.results)==null?void 0:U.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?A:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const ne=(N=$.item.approval_request_id)!=null?N:void 0,Le=ne!=null&&(X=(G=p.get(ne))!=null?G:h[ne])!=null?X:$.item.id,_t=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:Le,toolName:_t,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:Le,toolName:_t,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const ne=w[$.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:io($.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&$.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[a]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const ne=(he=(K=(Q=u.config).generateId)==null?void 0:K.call(Q))!=null?he:Zt(),Le=(V=$.item.approval_request_id)!=null?V:$.item.id;p.set(Le,ne);const _t=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:ne,toolName:_t,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:Le,toolCallId:ne})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.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($.item.type==="reasoning"){const ne=b[$.item.id],Le=Object.entries(ne.summaryParts).filter(([_t,Ht])=>Ht==="active"||Ht==="can-conclude").map(([_t])=>_t);for(const _t of Le)I.enqueue({type:"reasoning-end",id:`${$.item.id}:${_t}`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(P=$.item.encrypted_content)!=null?P:null}}});delete b[$.item.id]}}else if(WR($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:$.delta})}else if(KR($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:$.delta})}else if(eP($)){const ne=w[$.output_index];ne?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:io($.delta)}),ne.applyPatch.hasDiff=!0)}else if(tP($)){const ne=w[$.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:io($.diff)}),ne.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(YR($))I.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(QR($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:io($.delta)})}else if(XR($)){const ne=w[$.output_index];ne!=null&&(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),I.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(GR($))y=$.response.id,I.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(HR($))I.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(Z=(H=e.providerOptions)==null?void 0:H[a])!=null&&Z.logprobs&&$.logprobs&&v.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const ne=b[$.item_id];ne.summaryParts[$.summary_index]="active";for(const Le of Object.keys(ne.summaryParts))ne.summaryParts[Le]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${Le}`,providerMetadata:{[a]:{itemId:$.item_id}}}),ne.summaryParts[Le]="concluded");I.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id,reasoningEncryptedContent:(M=(x=b[$.item_id])==null?void 0:x.encryptedContent)!=null?M:null}}})}}else $.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[a]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude":JR($)?(f={unified:B_({finishReason:(L=$.response.incomplete_details)==null?void 0:L.reason,hasFunctionCall:C}),raw:(te=(W=$.response.incomplete_details)==null?void 0:W.reason)!=null?te:void 0},g=$.response.usage,typeof $.response.service_tier=="string"&&(k=$.response.service_tier)):rP($)?(_.push($.annotation),$.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(z=(Se=(se=u.config).generateId)==null?void 0:Se.call(se))!=null?z:Zt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(ee=(Y=(F=u.config).generateId)==null?void 0:Y.call(F))!=null?ee:Zt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(He=(Ee=(ue=u.config).generateId)==null?void 0:Ee.call(ue))!=null?He:Zt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(et=(ft=(ot=u.config).generateId)==null?void 0:ft.call(ot))!=null?et:Zt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):nP($)&&I.enqueue({type:"error",error:$})},flush(S){const I={[a]:{responseId:y,...v.length>0?{logprobs:v}:{},...k!==void 0?{serviceTier:k}:{}}};S.enqueue({type:"finish",finishReason:f,usage:V_(g),providerMetadata:I})}})),request:{body:t},response:{headers:l}}}};function HR(e){return e.type==="response.output_text.delta"}function BR(e){return e.type==="response.output_item.done"}function JR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function GR(e){return e.type==="response.created"}function WR(e){return e.type==="response.function_call_arguments.delta"}function KR(e){return e.type==="response.custom_tool_call_input.delta"}function YR(e){return e.type==="response.image_generation_call.partial_image"}function QR(e){return e.type==="response.code_interpreter_call_code.delta"}function XR(e){return e.type==="response.code_interpreter_call_code.done"}function eP(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function tP(e){return e.type==="response.apply_patch_call_operation_diff.done"}function K_(e){return e.type==="response.output_item.added"}function rP(e){return e.type==="response.output_text.annotation.added"}function nP(e){return e.type==="error"}function Y_(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 io(e){return JSON.stringify(e).slice(1,-1)}var oP=be(()=>we(T({instructions:d().nullish(),speed:D().min(.25).max(4).default(1).nullish()}))),sP=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 sn({provider:"openai",providerOptions:a,schema:oP}),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 Yt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:s,failedResponseHandler:Mr,successfulResponseHandler:W5(),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}}}},aP=be(()=>we(T({text:d(),language:d().nullish(),duration:D().nullish(),words:q(T({word:d(),start:D(),end:D()})).nullish(),segments:q(T({id:D(),seek:D(),start:D(),end:D(),text:d(),tokens:q(D()),temperature:D(),avg_logprob:D(),compression_ratio:D(),no_speech_prob:D()})).nullish()}))),iP=be(()=>we(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:D().min(0).max(1).default(0).optional(),timestampGranularities:q(ye(["word","segment"])).default(["segment"]).optional()}))),Q_={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"},lP=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 sn({provider:"openai",providerOptions:r,schema:iP}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Ao(e)]);s.append("model",this.modelId);const i=YI(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 Rg({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Mr,successfulResponseHandler:fr(aP),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in Q_?Q_[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:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},cP="3.0.41";function X_(e={}){var t,r;const n=(t=Og(jo({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 ${KI({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${cP}`),a=v=>new U7(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=v=>new V7(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new J7(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new Y7(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new lP(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),h=v=>new sP(v,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new VR(v,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return p(v)};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=qR,g}X_();var e1="vercel.ai.error",uP=Symbol.for(e1),t1,dP=class dw extends Error{constructor({name:t,message:r,cause:n}){super(r),this[t1]=!0,this.name=t,this.cause=n}static isInstance(t){return dw.hasMarker(t,e1)}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}};t1=uP;var It=dP,r1="AI_APICallError",n1=`vercel.ai.error.${r1}`,pP=Symbol.for(n1),o1,cn=class extends It{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:r1,message:e,cause:a}),this[o1]=!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 It.hasMarker(e,n1)}};o1=pP;var s1="AI_EmptyResponseBodyError",a1=`vercel.ai.error.${s1}`,fP=Symbol.for(a1),i1,hP=class extends It{constructor({message:e="Empty response body"}={}){super({name:s1,message:e}),this[i1]=!0}static isInstance(e){return It.hasMarker(e,a1)}};i1=fP;function l1(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var c1="AI_InvalidArgumentError",u1=`vercel.ai.error.${c1}`,mP=Symbol.for(u1),d1,p1=class extends It{constructor({message:e,cause:t,argument:r}){super({name:c1,message:e,cause:t}),this[d1]=!0,this.argument=r}static isInstance(e){return It.hasMarker(e,u1)}};d1=mP;var f1="AI_InvalidResponseDataError",h1=`vercel.ai.error.${f1}`,gP=Symbol.for(h1),m1,g1=class extends It{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:f1,message:t}),this[m1]=!0,this.data=e}static isInstance(e){return It.hasMarker(e,h1)}};m1=gP;var y1="AI_JSONParseError",v1=`vercel.ai.error.${y1}`,yP=Symbol.for(v1),_1,Cl=class extends It{constructor({text:e,cause:t}){super({name:y1,message:`JSON parsing failed: Text: ${e}.
|
|
596
|
-
Error message: ${
|
|
597
|
-
Error message: ${l1(r)}`,cause:r}),this[$1]=!0,this.value=t}static isInstance(t){return It.hasMarker(t,x1)}static wrap({value:t,cause:r}){return Tp.isInstance(r)&&r.value===t?r:new Tp({value:t,cause:r})}};$1=wP;var aa=bP,R1="AI_UnsupportedFunctionalityError",P1=`vercel.ai.error.${R1}`,kP=Symbol.for(P1),M1,O1=class extends It{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:R1,message:t}),this[M1]=!0,this.functionality=e}static isInstance(e){return It.hasMarker(e,P1)}};M1=kP;function N1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Il(e){return Object.fromEntries([...e.headers])}var TP=({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 p1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},El=TP();function np(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var CP=["fetch failed","failed to fetch"];function SP({error:e,url:t,requestBodyValues:r}){if(np(e))return e;if(e instanceof TypeError&&CP.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new cn({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function IP(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 A1(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 xP="3.0.18";function $P({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Sl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Sl({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 Sl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Sl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var RP=/"__proto__"\s*:/,PP=/"constructor"\s*:/;function q1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||RP.test(e)===!1&&PP.test(e)===!1?t:MP(t)}function MP(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 op(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return q1(e)}try{return q1(e)}finally{Error.stackTraceLimit=t}}var sp=Symbol.for("vercel.ai.validator");function OP(e){return{[sp]:!0,validate:e}}function NP(e){return typeof e=="object"&&e!==null&&sp in e&&e[sp]===!0&&"validate"in e}function AP(e){return NP(e)?e:typeof e=="function"?e():qP(e)}function qP(e){return OP(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new aa({value:t,cause:r.issues})}})}async function LP({value:e,schema:t}){const r=await ia({value:e,schema:t});if(!r.success)throw aa.wrap({value:e,cause:r.error});return r.value}async function ia({value:e,schema:t}){const r=AP(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:aa.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:aa.wrap({value:e,cause:n}),rawValue:e}}}async function jP({text:e,schema:t}){try{const r=op(e);return t==null?r:LP({value:r,schema:t})}catch(r){throw Cl.isInstance(r)||aa.isInstance(r)?r:new Cl({text:e,cause:r})}}async function L1({text:e,schema:t}){try{const r=op(e);return t==null?{success:!0,value:r,rawValue:r}:await ia({value:r,schema:t})}catch(r){return{success:!1,error:Cl.isInstance(r)?r:new Cl({text:e,cause:r}),rawValue:void 0}}}function j1(e){try{return op(e),!0}catch{return!1}}function DP({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ro).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await L1({text:r,schema:t}))}}))}async function D1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ia({value:t[e],schema:r});if(!n.success)throw new p1({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var UP=()=>globalThis.fetch,U1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>zP({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),zP=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=UP()})=>{try{const i=await a(e,{method:"POST",headers:A1(t,`ai-sdk/provider-utils/${xP}`,IP()),body:r.content,signal:s}),l=Il(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw np(u)||cn.isInstance(u)?u:new cn({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&&(np(c)||cn.isInstance(c))?c:new cn({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw SP({error:i,url:e,requestBodyValues:r.values})}},ZP=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Il(n);if(a.trim()==="")return{responseHeaders:i,value:new cn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await jP({text:a,schema:e});return{responseHeaders:i,value:new cn({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 cn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},FP=e=>async({response:t})=>{const r=Il(t);if(t.body==null)throw new hP({});return{responseHeaders:r,value:DP({stream:t.body,schema:e})}},VP=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await L1({text:o,schema:e}),a=Il(t);if(!s.success)throw new cn({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:HP}=globalThis;function BP(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return HP(t)}function JP(e){return e instanceof Uint8Array?BP(e):e}function GP(e){return e?.replace(/\/$/,"")}function la(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function WP(e){const t=[];for(const{role:r,content:n,...o}of e){const s=la({...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,...la(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=la(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,${JP(a.data)}`},...i}}else throw new O1({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=la(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=la(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 z1({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 Z1(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 ap=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),KP=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),D()]).nullish()})}),YP={errorSchema:KP,errorToMessage:e=>e.error.message};function QP({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 O1({functionality:`tool choice type: ${s}`})}}}var XP=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:YP;this.chunkSchema=tM(o.errorSchema),this.failedResponseHandler=ZP(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,v,y;const w=[],_=Object.assign((f=await D1({provider:"openai-compatible",providerOptions:i,schema:ap}))!=null?f:{},(g=await D1({provider:this.providerOptionsName,providerOptions:i,schema:ap}))!=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:b}=QP({tools:p,toolChoice:h});return{args:{model:this.modelId,user:_.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:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([k])=>!Object.keys(ap.shape).includes(k))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:WP(e),tools:m,tool_choice:C},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,g,v,y,w;const{args:_,warnings:m}=await this.getArgs({...e}),C=JSON.stringify(_),{responseHeaders:b,value:k,rawValue:S}=await U1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:N1(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:VP(eM),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=k.choices[0],E=[],j=I.message.content;j!=null&&j.length>0&&E.push({type:"text",text:j});const O=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(O!=null&&O.length>0&&E.push({type:"reasoning",text:O}),I.message.tool_calls!=null)for(const N of I.message.tool_calls)E.push({type:"tool-call",toolCallId:(r=N.id)!=null?r:El(),toolName:N.function.name,input:N.function.arguments});const U={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=k.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(U[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(U[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:E,finishReason:Z1(I.finish_reason),usage:{inputTokens:(i=(a=k.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=k.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=k.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(g=(f=(p=k.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:U,request:{body:C},response:{...z1(k),headers:b,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 U1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:N1(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:FP(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(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,m,C,b,k,S,I,E,j,O,U,A;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const N=v.value;if(s?.processChunk(v.rawValue),"error"in N){c="error",y.enqueue({type:"error",error:N.error.message});return}if(h&&(h=!1,y.enqueue({type:"response-metadata",...z1(N)})),N.usage!=null){const{prompt_tokens:K,completion_tokens:he,total_tokens:V,prompt_tokens_details:P,completion_tokens_details:H}=N.usage;u.promptTokens=K??void 0,u.completionTokens=he??void 0,u.totalTokens=V??void 0,H?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=H?.reasoning_tokens),H?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=H?.accepted_prediction_tokens),H?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=H?.rejected_prediction_tokens),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const G=N.choices[0];if(G?.finish_reason!=null&&(c=Z1(G.finish_reason)),G?.delta==null)return;const X=G.delta,Q=(w=X.reasoning_content)!=null?w:X.reasoning;if(Q&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Q})),X.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:X.content})),X.tool_calls!=null)for(const K of X.tool_calls){const he=K.index;if(l[he]==null){if(K.id==null)throw new g1({data:K,message:"Expected 'id' to be a string."});if(((_=K.function)==null?void 0:_.name)==null)throw new g1({data:K,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),l[he]={id:K.id,type:"function",function:{name:K.function.name,arguments:(m=K.function.arguments)!=null?m:""},hasFinished:!1};const P=l[he];((C=P.function)==null?void 0:C.name)!=null&&((b=P.function)==null?void 0:b.arguments)!=null&&(P.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),j1(P.function.arguments)&&(y.enqueue({type:"tool-input-end",id:P.id}),y.enqueue({type:"tool-call",toolCallId:(k=P.id)!=null?k:El(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const V=l[he];V.hasFinished||(((S=K.function)==null?void 0:S.arguments)!=null&&(V.function.arguments+=(E=(I=K.function)==null?void 0:I.arguments)!=null?E:""),y.enqueue({type:"tool-input-delta",id:V.id,delta:(j=K.function.arguments)!=null?j:""}),((O=V.function)==null?void 0:O.name)!=null&&((U=V.function)==null?void 0:U.arguments)!=null&&j1(V.function.arguments)&&(y.enqueue({type:"tool-input-end",id:V.id}),y.enqueue({type:"tool-call",toolCallId:(A=V.id)!=null?A:El(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(v){var y,w,_,m,C,b;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:S.id}),v.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:El(),toolName:S.function.name,input:S.function.arguments});const k={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(m=u.totalTokens)!=null?m:void 0,reasoningTokens:(C=u.completionTokensDetails.reasoningTokens)!=null?C:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:k})}})),request:{body:o},response:{headers:a}}}},F1=T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish(),eM=T({id:d().nullish(),created:D().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:F1}),tM=e=>ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({delta:T({role:ye(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:D(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:F1}),e]);T({echo:ge().optional(),logitBias:ve(d(),D()).optional(),suffix:d().optional(),user:d().optional()});var rM=T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()});T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:rM.nullish()}),T({dimensions:D().optional(),user:d().optional()}),T({data:q(T({embedding:q(D())})),usage:T({prompt_tokens:D()}).nullish(),providerMetadata:ve(d(),ve(d(),Tt())).optional()}),T({data:q(T({b64_json:d()}))});var V1=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}}},nM={extractMetadata:async({parsedBody:e})=>{const t=await ia({value:e,schema:oM});return!t.success||t.value.usage==null?void 0:V1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await ia({value:t,schema:sM});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:()=>V1(e)}}},H1=T({prompt_cache_hit_tokens:D().nullish(),prompt_cache_miss_tokens:D().nullish()}),oM=T({usage:H1.nullish()}),sM=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:H1.nullish()}),aM="1.0.30";function B1(e={}){var t;const r=GP((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>A1({Authorization:`Bearer ${$P({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${aM}`);class o extends XP{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:nM}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new I1({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new I1({modelId:i,modelType:"imageModel"})},a}B1();const J1=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]=Mg({description:o,inputSchema:Do({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function iM(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
595
|
+
${t}:`]}}function j_({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 D_(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 G7=be(()=>we(T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(D()),top_logprobs:q(ve(d(),D())).nullish()}).nullish()})),usage:T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}))),W7=be(()=>we(ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:D(),logprobs:T({tokens:q(d()),token_logprobs:q(D()),top_logprobs:q(ve(d(),D())).nullish()}).nullish()})),usage:T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}),ap]))),U_=be(()=>we(T({echo:ge().optional(),logitBias:ve(d(),D()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([ge(),D()]).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=[],m={...await sn({provider:"openai",providerOptions:p,schema:U_}),...await sn({provider:this.providerOptionsName,providerOptions:p,schema:U_})};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:v,stopSequences:y}=J7({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:h,prompt:v,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 Yt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:r,failedResponseHandler:Mr,successfulResponseHandler:fr(G7),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:L_(s.usage),finishReason:{unified:D_(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...j_(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 Yt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Mr,successfulResponseHandler:cl(W7),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...j_(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:D_(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_(l)})}})),request:{body:n},response:{headers:o}}}},Y7=be(()=>we(T({dimensions:D().optional(),user:d().optional()}))),Q7=be(()=>we(T({data:q(T({embedding:q(D())})),usage:T({prompt_tokens:D()}).nullish()}))),X7=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 U5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await sn({provider:"openai",providerOptions:n,schema:Y7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Yt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:qt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Mr,successfulResponseHandler:fr(Q7),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}}}},z_=be(()=>we(T({created:D().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:D().nullish(),output_tokens:D().nullish(),total_tokens:D().nullish(),input_tokens_details:T({image_tokens:D().nullish(),text_tokens:D().nullish()}).nullish()}).nullish()}))),eR={"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},tR=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function rR(e){return tR.some(t=>e.startsWith(t))}var nR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=eR[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,m,v,y,w,_,g,C;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&b.push({type:"unsupported",feature:"seed"});const k=(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:x,responseHeaders:j}=await qg({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:qt(this.config.headers(),l),formData:J5({model:this.modelId,prompt:e,image:await Promise.all(t.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([qo(O.data)],{type:O.mediaType})],{type:O.mediaType}):kg(O.url))),mask:r!=null?await oR(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:Mr,successfulResponseHandler:fr(z_),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(O=>O.b64_json),warnings:b,usage:x.usage!=null?{inputTokens:(m=x.usage.input_tokens)!=null?m:void 0,outputTokens:(v=x.usage.output_tokens)!=null?v:void 0,totalTokens:(y=x.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:x.data.map((O,U)=>{var A,N,G,X,Q,K;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(A=x.created)!=null?A:void 0,size:(N=x.size)!=null?N:void 0,quality:(G=x.quality)!=null?G:void 0,background:(X=x.background)!=null?X:void 0,outputFormat:(Q=x.output_format)!=null?Q:void 0,...Z_((K=x.usage)==null?void 0:K.input_tokens_details,U,x.data.length)}})}}}}const{value:S,responseHeaders:I}=await Yt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:qt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...rR(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Mr,successfulResponseHandler:fr(z_),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(x=>x.b64_json),warnings:b,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_:void 0,outputTokens:(g=S.usage.output_tokens)!=null?g:void 0,totalTokens:(C=S.usage.total_tokens)!=null?C:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:I},providerMetadata:{openai:{images:S.data.map((x,j)=>{var O,U,A,N,G,X;return{...x.revised_prompt?{revisedPrompt:x.revised_prompt}:{},created:(O=S.created)!=null?O:void 0,size:(U=S.size)!=null?U:void 0,quality:(A=S.quality)!=null?A:void 0,background:(N=S.background)!=null?N:void 0,outputFormat:(G=S.output_format)!=null?G:void 0,...Z_((X=S.usage)==null?void 0:X.input_tokens_details,j,S.data.length)}})}}}}};function Z_(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 oR(e){if(!e)return;if(e.type==="url")return kg(e.url);const t=e.data instanceof Uint8Array?e.data:qo(e.data);return new Blob([t],{type:e.mediaType})}var F_=be(()=>we(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()})])}))),V_=be(()=>we(T({status:ye(["completed","failed"]),output:d().optional()}))),sR=$r({id:"openai.apply_patch",inputSchema:F_,outputSchema:V_}),aR=sR,iR=be(()=>we(T({code:d().nullish(),containerId:d()}))),lR=be(()=>we(T({outputs:q(ze("type",[T({type:R("logs"),logs:d()}),T({type:R("image"),url:d()})])).nullish()}))),cR=be(()=>we(T({container:ae([d(),T({fileIds:q(d()).optional()})]).optional()}))),uR=$r({id:"openai.code_interpreter",inputSchema:iR,outputSchema:lR}),dR=(e={})=>uR(e),pR=be(()=>we(T({name:d(),description:d().optional(),format:ae([T({type:R("grammar"),syntax:ye(["regex","lark"]),definition:d()}),T({type:R("text")})]).optional()}))),fR=be(()=>we(d())),hR=ex({id:"openai.custom",inputSchema:fR}),mR=e=>hR(e),H_=T({key:d(),type:ye(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),D(),ge(),q(d())])}),B_=T({type:ye(["and","or"]),filters:q(ae([H_,Tc(()=>B_)]))}),gR=be(()=>we(T({vectorStoreIds:q(d()),maxNumResults:D().optional(),ranking:T({ranker:d().optional(),scoreThreshold:D().optional()}).optional(),filters:ae([H_,B_]).optional()}))),yR=be(()=>we(T({queries:q(d()),results:q(T({attributes:ve(d(),Me()),fileId:d(),filename:d(),score:D(),text:d()})).nullable()}))),vR=$r({id:"openai.file_search",inputSchema:T({}),outputSchema:yR}),_R=be(()=>we(T({background:ye(["auto","opaque","transparent"]).optional(),inputFidelity:ye(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:ye(["auto"]).optional(),outputCompression:D().int().min(0).max(100).optional(),outputFormat:ye(["png","jpeg","webp"]).optional(),partialImages:D().int().min(0).max(3).optional(),quality:ye(["auto","low","medium","high"]).optional(),size:ye(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),wR=be(()=>we(T({}))),bR=be(()=>we(T({result:d()}))),kR=$r({id:"openai.image_generation",inputSchema:wR,outputSchema:bR}),TR=(e={})=>kR(e),J_=be(()=>we(T({action:T({type:R("exec"),command:q(d()),timeoutMs:D().optional(),user:d().optional(),workingDirectory:d().optional(),env:ve(d(),d()).optional()})}))),G_=be(()=>we(T({output:d()}))),CR=$r({id:"openai.local_shell",inputSchema:J_,outputSchema:G_}),W_=be(()=>we(T({action:T({commands:q(d()),timeoutMs:D().optional(),maxOutputLength:D().optional()})}))),lp=be(()=>we(T({output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exitCode:D()})])}))}))),SR=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(),IR=be(()=>we(T({environment:ae([T({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:ye(["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:SR}),T({type:R("containerReference"),containerId:d()}),T({type:R("local").optional(),skills:q(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),xR=$r({id:"openai.shell",inputSchema:W_,outputSchema:lp}),ER=be(()=>we(T({externalWebAccess:ge().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:ye(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),$R=be(()=>we(T({}))),RR=be(()=>we(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()}))),PR=$r({id:"openai.web_search",inputSchema:$R,outputSchema:RR}),MR=(e={})=>PR(e),OR=be(()=>we(T({searchContextSize:ye(["low","medium","high"]).optional(),userLocation:T({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),NR=be(()=>we(T({}))),AR=be(()=>we(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()}))),qR=$r({id:"openai.web_search_preview",inputSchema:NR,outputSchema:AR}),cp=Tc(()=>ae([d(),D(),ge(),Ri(),q(cp),ve(d(),cp)])),LR=be(()=>we(T({serverLabel:d(),allowedTools:ae([q(d()),T({readOnly:ge().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ve(d(),d()).optional(),requireApproval:ae([ye(["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."))),jR=be(()=>we(T({}))),DR=be(()=>we(T({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),cp]).optional()}))),UR=$r({id:"openai.mcp",inputSchema:jR,outputSchema:DR}),zR=e=>UR(e),ZR={applyPatch:aR,customTool:mR,codeInterpreter:dR,fileSearch:vR,imageGeneration:TR,localShell:CR,shell:xR,webSearchPreview:qR,webSearch:MR,mcp:zR};function K_(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 Y_(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function FR({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var h,p,f,m,v,y,w,_,g,C,b,k,S;const I=[],x=[],j=new Set;for(const{role:O,content:U}of e)switch(O){case"system":{switch(r){case"system":{I.push({role:"system",content:U});break}case"developer":{I.push({role:"developer",content:U});break}case"remove":{x.push({type:"other",message:"system messages are removed for this model"});break}default:{const A=r;throw new Error(`Unsupported system message mode: ${A}`)}}break}case"user":{I.push({role:"user",content:U.map((A,N)=>{var G,X,Q;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const K=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&Y_(A.data,o)?{file_id:A.data}:{image_url:`data:${K};base64,${jo(A.data)}`},detail:(X=(G=A.providerOptions)==null?void 0:G[n])==null?void 0:X.imageDetail}}else{if(A.mediaType==="application/pdf")return A.data instanceof URL?{type:"input_file",file_url:A.data.toString()}:{type:"input_file",...typeof A.data=="string"&&Y_(A.data,o)?{file_id:A.data}:{filename:(Q=A.filename)!=null?Q:`part-${N}.pdf`,file_data:`data:application/pdf;base64,${jo(A.data)}`}};throw new Ur({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const N of U)switch(N.type){case"text":{const G=(h=N.providerOptions)==null?void 0:h[n],X=G?.itemId,Q=G?.phase;if(a&&X!=null)break;if(s&&X!=null){I.push({type:"item_reference",id:X});break}I.push({role:"assistant",content:[{type:"output_text",text:N.text}],id:X,...Q!=null&&{phase:Q}});break}case"tool-call":{const G=(y=(f=(p=N.providerOptions)==null?void 0:p[n])==null?void 0:f.itemId)!=null?y:(v=(m=N.providerMetadata)==null?void 0:m[n])==null?void 0:v.itemId;if(a&&G!=null)break;if(N.providerExecuted){s&&G!=null&&I.push({type:"item_reference",id:G});break}if(s&&G!=null){I.push({type:"item_reference",id:G});break}const X=t.toProviderToolName(N.toolName);if(i&&X==="local_shell"){const Q=await St({value:N.input,schema:J_});I.push({type:"local_shell_call",call_id:N.toolCallId,id:G,action:{type:"exec",command:Q.action.command,timeout_ms:Q.action.timeoutMs,user:Q.action.user,working_directory:Q.action.workingDirectory,env:Q.action.env}});break}if(l&&X==="shell"){const Q=await St({value:N.input,schema:W_});I.push({type:"shell_call",call_id:N.toolCallId,id:G,status:"completed",action:{commands:Q.action.commands,timeout_ms:Q.action.timeoutMs,max_output_length:Q.action.maxOutputLength}});break}if(c&&X==="apply_patch"){const Q=await St({value:N.input,schema:F_});I.push({type:"apply_patch_call",call_id:Q.callId,id:G,status:"completed",operation:Q.operation});break}if(u?.has(X)){I.push({type:"custom_tool_call",call_id:N.toolCallId,name:X,input:typeof N.input=="string"?N.input:JSON.stringify(N.input),id:G});break}I.push({type:"function_call",call_id:N.toolCallId,name:X,arguments:JSON.stringify(N.input),id:G});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 G=t.toProviderToolName(N.toolName);if(l&&G==="shell"){if(N.output.type==="json"){const X=await St({value:N.output.value,schema:lp});I.push({type:"shell_call_output",call_id:N.toolCallId,output:X.output.map(Q=>({stdout:Q.stdout,stderr:Q.stderr,outcome:Q.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Q.outcome.exitCode}}))})}break}if(s){const X=(g=(_=(w=N.providerOptions)==null?void 0:w[n])==null?void 0:_.itemId)!=null?g:N.toolCallId;I.push({type:"item_reference",id:X})}else x.push({type:"other",message:`Results for OpenAI tool ${N.toolName} are not sent to the API when store is false`});break}case"reasoning":{const G=await sn({provider:n,providerOptions:N.providerOptions,schema:VR}),X=G?.itemId;if(a&&X!=null)break;if(X!=null){const Q=A[X];if(s)Q===void 0&&(I.push({type:"item_reference",id:X}),A[X]={type:"reasoning",id:X,summary:[]});else{const K=[];N.text.length>0?K.push({type:"summary_text",text:N.text}):Q!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(N)}.`}),Q===void 0?(A[X]={type:"reasoning",id:X,encrypted_content:G?.reasoningEncryptedContent,summary:K},I.push(A[X])):(Q.summary.push(...K),G?.reasoningEncryptedContent!=null&&(Q.encrypted_content=G.reasoningEncryptedContent))}}else{const Q=G?.reasoningEncryptedContent;if(Q!=null){const K=[];N.text.length>0&&K.push({type:"summary_text",text:N.text}),I.push({type:"reasoning",encrypted_content:Q,summary:K})}else x.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(N)}.`})}break}}break}case"tool":{for(const A of U){if(A.type==="tool-approval-response"){const Q=A;if(j.has(Q.approvalId))continue;j.add(Q.approvalId),s&&I.push({type:"item_reference",id:Q.approvalId}),I.push({type:"mcp_approval_response",approval_request_id:Q.approvalId,approve:Q.approved});continue}const N=A.output;if(N.type==="execution-denied"&&((b=(C=N.providerOptions)==null?void 0:C.openai)==null?void 0:b.approvalId))continue;const G=t.toProviderToolName(A.toolName);if(i&&G==="local_shell"&&N.type==="json"){const Q=await St({value:N.value,schema:G_});I.push({type:"local_shell_call_output",call_id:A.toolCallId,output:Q.output});continue}if(l&&G==="shell"&&N.type==="json"){const Q=await St({value:N.value,schema:lp});I.push({type:"shell_call_output",call_id:A.toolCallId,output:Q.output.map(K=>({stdout:K.stdout,stderr:K.stderr,outcome:K.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:K.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&N.type==="json"){const Q=await St({value:N.value,schema:V_});I.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:Q.status,output:Q.output});continue}if(u?.has(G)){let Q;switch(N.type){case"text":case"error-text":Q=N.value;break;case"execution-denied":Q=(k=N.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":Q=JSON.stringify(N.value);break;case"content":Q=N.value.map(K=>{var he;switch(K.type){case"text":return{type:"input_text",text:K.text};case"image-data":return{type:"input_image",image_url:`data:${K.mediaType};base64,${K.data}`};case"image-url":return{type:"input_image",image_url:K.url};case"file-data":return{type:"input_file",filename:(he=K.filename)!=null?he:"data",file_data:`data:${K.mediaType};base64,${K.data}`};default:x.push({type:"other",message:`unsupported custom tool content part type: ${K.type}`});return}}).filter(Ig);break;default:Q=""}I.push({type:"custom_tool_call_output",call_id:A.toolCallId,output:Q});continue}let X;switch(N.type){case"text":case"error-text":X=N.value;break;case"execution-denied":X=(S=N.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":X=JSON.stringify(N.value);break;case"content":X=N.value.map(Q=>{var K;switch(Q.type){case"text":return{type:"input_text",text:Q.text};case"image-data":return{type:"input_image",image_url:`data:${Q.mediaType};base64,${Q.data}`};case"image-url":return{type:"input_image",image_url:Q.url};case"file-data":return{type:"input_file",filename:(K=Q.filename)!=null?K:"data",file_data:`data:${Q.mediaType};base64,${Q.data}`};default:{x.push({type:"other",message:`unsupported tool content part type: ${Q.type}`});return}}}).filter(Ig);break}I.push({type:"function_call_output",call_id:A.toolCallId,output:X})}break}default:{const A=O;throw new Error(`Unsupported role: ${A}`)}}return{input:I,warnings:x}}var VR=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Q_({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 HR=be(()=>we(ae([T({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish()}),T({type:ye(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:D(),input_tokens_details:T({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:T({reasoning_tokens:D().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:R("response.created"),response:T({id:d(),created_at:D(),model:d(),service_tier:d().nullish()})}),T({type:R("response.output_item.added"),output_index:D(),item:ze("type",[T({type:R("message"),id:d(),phase:ye(["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:ye(["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("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),T({type:R("shell_call"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])}),T({type:R("response.output_item.done"),output_index:D(),item:ze("type",[T({type:R("message"),id:d(),phase:ye(["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("custom_tool_call"),id:d(),call_id:d(),name:d(),input: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:ve(d(),ae([d(),D(),ge()])),file_id:d(),filename:d(),score:D(),text:d()})).nullish()}),T({type:R("local_shell_call"),id:d(),call_id:d(),action:T({type:R("exec"),command:q(d()),timeout_ms:D().optional(),user:d().optional(),working_directory:d().optional(),env:ve(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:ae([d(),T({type:d().optional(),code:ae([D(),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:Tt(),annotations:ve(d(),Me()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([D(),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:ye(["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:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])}),T({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.custom_tool_call_input.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:D(),partial_image_b64:d()}),T({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:D(),delta:d()}),T({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:D(),code:d()}),T({type:R("response.output_text.annotation.added"),annotation:ze("type",[T({type:R("url_citation"),start_index:D(),end_index:D(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:D()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:D(),end_index:D()}),T({type:R("file_path"),file_id:d(),index:D()})])}),T({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:D()}),T({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:D(),delta:d()}),T({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:D()}),T({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:D(),delta:d(),obfuscation:d().nullish()}),T({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:D(),diff:d()}),T({type:R("error"),sequence_number:D(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),BR=be(()=>we(T({id:d().optional(),created_at:D().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:ye(["commentary","final_answer"]).nullish(),content:q(T({type:R("output_text"),text:d(),logprobs:q(T({token:d(),logprob:D(),top_logprobs:q(T({token:d(),logprob:D()}))})).nullish(),annotations:q(ze("type",[T({type:R("url_citation"),start_index:D(),end_index:D(),url:d(),title:d()}),T({type:R("file_citation"),file_id:d(),filename:d(),index:D()}),T({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:D(),end_index:D()}),T({type:R("file_path"),file_id:d(),index: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:ve(d(),ae([d(),D(),ge()])),file_id:d(),filename:d(),score:D(),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:D().optional(),user:d().optional(),working_directory:d().optional(),env:ve(d(),d()).optional()})}),T({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:R("custom_tool_call"),call_id:d(),name:d(),input: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:ae([d(),T({type:d().optional(),code:ae([D(),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:Tt(),annotations:ve(d(),Me()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([D(),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:ye(["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:ye(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:R("shell_call_output"),id:d(),call_id:d(),status:ye(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:ze("type",[T({type:R("timeout")}),T({type:R("exit"),exit_code:D()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:D(),input_tokens_details:T({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:T({reasoning_tokens:D().nullish()}).nullish()}).optional()}))),X_=20,e1=be(()=>we(T({conversation:d().nullish(),include:q(ye(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([ge(),D().min(1).max(X_)]).optional(),maxToolCalls:D().nullish(),metadata:Tt().nullish(),parallelToolCalls:ge().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:ye(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:ye(["auto","flex","priority","default"]).nullish(),store:ge().nullish(),strictJsonSchema:ge().nullish(),textVerbosity:ye(["low","medium","high"]).nullish(),truncation:ye(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:ye(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));async function JR({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o;e=e?.length?e:void 0;const s=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const a=[],i=n??new Set;for(const c of e)switch(c.type){case"function":a.push({type:"function",name:c.name,description:c.description,parameters:c.inputSchema,...c.strict!=null?{strict:c.strict}:{}});break;case"provider":{switch(c.id){case"openai.file_search":{const u=await St({value:c.args,schema:gR});a.push({type:"file_search",vector_store_ids:u.vectorStoreIds,max_num_results:u.maxNumResults,ranking_options:u.ranking?{ranker:u.ranking.ranker,score_threshold:u.ranking.scoreThreshold}:void 0,filters:u.filters});break}case"openai.local_shell":{a.push({type:"local_shell"});break}case"openai.shell":{const u=await St({value:c.args,schema:IR});a.push({type:"shell",...u.environment&&{environment:GR(u.environment)}});break}case"openai.apply_patch":{a.push({type:"apply_patch"});break}case"openai.web_search_preview":{const u=await St({value:c.args,schema:OR});a.push({type:"web_search_preview",search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.web_search":{const u=await St({value:c.args,schema:ER});a.push({type:"web_search",filters:u.filters!=null?{allowed_domains:u.filters.allowedDomains}:void 0,external_web_access:u.externalWebAccess,search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.code_interpreter":{const u=await St({value:c.args,schema:cR});a.push({type:"code_interpreter",container:u.container==null?{type:"auto",file_ids:void 0}:typeof u.container=="string"?u.container:{type:"auto",file_ids:u.container.fileIds}});break}case"openai.image_generation":{const u=await St({value:c.args,schema:_R});a.push({type:"image_generation",background:u.background,input_fidelity:u.inputFidelity,input_image_mask:u.inputImageMask?{file_id:u.inputImageMask.fileId,image_url:u.inputImageMask.imageUrl}:void 0,model:u.model,moderation:u.moderation,partial_images:u.partialImages,quality:u.quality,output_compression:u.outputCompression,output_format:u.outputFormat,size:u.size});break}case"openai.mcp":{const u=await St({value:c.args,schema:LR}),h=m=>({tool_names:m.toolNames}),p=u.requireApproval,f=p==null?void 0:typeof p=="string"?p:p.never!=null?{never:h(p.never)}:void 0;a.push({type:"mcp",server_label:u.serverLabel,allowed_tools:Array.isArray(u.allowedTools)?u.allowedTools:u.allowedTools?{read_only:u.allowedTools.readOnly,tool_names:u.allowedTools.toolNames}:void 0,authorization:u.authorization,connector_id:u.connectorId,headers:u.headers,require_approval:f??"never",server_description:u.serverDescription,server_url:u.serverUrl});break}case"openai.custom":{const u=await St({value:c.args,schema:pR});a.push({type:"custom",name:u.name,description:u.description,format:u.format}),i.add(u.name);break}}break}default:s.push({type:"unsupported",feature:`function tool ${c}`});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:s};const l=t.type;switch(l){case"auto":case"none":case"required":return{tools:a,toolChoice:l,toolWarnings:s};case"tool":{const c=(o=r?.toProviderToolName(t.toolName))!=null?o:t.toolName;return{tools:a,toolChoice:c==="code_interpreter"||c==="file_search"||c==="image_generation"||c==="web_search_preview"||c==="web_search"||c==="mcp"||c==="apply_patch"?{type:c}:i.has(c)?{type:"custom",name:c}:{type:"function",name:c},toolWarnings:s}}default:{const c=l;throw new Ur({functionality:`tool choice type: ${c}`})}}}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:WR(r.skills)}}return{type:"local",skills:e.skills}}function WR(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 t1(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 KR=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,m,v,y,w,_,g,C,b;const k=[],S=N_(this.modelId);o!=null&&k.push({type:"unsupported",feature:"topK"}),i!=null&&k.push({type:"unsupported",feature:"seed"}),s!=null&&k.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&k.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&k.push({type:"unsupported",feature:"stopSequences"});const I=this.config.provider.includes("azure")?"azure":"openai";let x=await sn({provider:I,providerOptions:c,schema:e1});x==null&&I!=="openai"&&(x=await sn({provider:"openai",providerOptions:c,schema:e1}));const j=(f=x?.forceReasoning)!=null?f:S.isReasoningModel;x?.conversation&&x?.previousResponseId&&k.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const O=F5({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"},resolveProviderToolName:te=>te.id==="openai.custom"?te.args.name:void 0}),U=new Set,{tools:A,toolChoice:N,toolWarnings:G}=await JR({tools:u,toolChoice:h,toolNameMapping:O,customProviderToolNames:U}),{input:X,warnings:Q}=await FR({prompt:l,toolNameMapping:O,systemMessageMode:(m=x?.systemMessageMode)!=null?m:j?"developer":S.systemMessageMode,providerOptionsName:I,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=x?.store)!=null?v:!0,hasConversation:x?.conversation!=null,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch"),customProviderToolNames:U.size>0?U:void 0});k.push(...Q);const K=(y=x?.strictJsonSchema)!=null?y:!0;let he=x?.include;function V(te){he==null?he=[te]:he.includes(te)||(he=[...he,te])}function P(te){return u?.find(se=>se.type==="provider"&&se.id===te)!=null}const H=typeof x?.logprobs=="number"?x?.logprobs:x?.logprobs===!0?X_:void 0;H&&V("message.output_text.logprobs");const Z=(w=u?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:w.name;Z&&V("web_search_call.action.sources"),P("openai.code_interpreter")&&V("code_interpreter_call.outputs");const E=x?.store;E===!1&&j&&V("reasoning.encrypted_content");const M={model:this.modelId,input:X,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||x?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:K,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...x?.textVerbosity&&{verbosity:x.textVerbosity}}},conversation:x?.conversation,max_tool_calls:x?.maxToolCalls,metadata:x?.metadata,parallel_tool_calls:x?.parallelToolCalls,previous_response_id:x?.previousResponseId,store:E,user:x?.user,instructions:x?.instructions,service_tier:x?.serviceTier,include:he,prompt_cache_key:x?.promptCacheKey,prompt_cache_retention:x?.promptCacheRetention,safety_identifier:x?.safetyIdentifier,top_logprobs:H,truncation:x?.truncation,...j&&(x?.reasoningEffort!=null||x?.reasoningSummary!=null)&&{reasoning:{...x?.reasoningEffort!=null&&{effort:x.reasoningEffort},...x?.reasoningSummary!=null&&{summary:x.reasoningSummary}}}};j?x?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(x?.reasoningEffort!=null&&k.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),x?.reasoningSummary!=null&&k.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),x?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),x?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(k.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 L=(b=(C=(g=u?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:g.args)==null?void 0:C.environment)==null?void 0:b.type,W=L==="containerAuto"||L==="containerReference";return{webSearchToolName:Z,args:{...M,tools:A,tool_choice:N},warnings:[...k,...G],store:E,toolNameMapping:O,providerOptionsName:I,isShellProviderExecuted:W}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,m,v,y,w,_,g,C,b,k,S,I,x;const{args:j,warnings:O,webSearchToolName:U,toolNameMapping:A,providerOptionsName:N,isShellProviderExecuted:G}=await this.getArgs(e),X=this.config.url({path:"/responses",modelId:this.modelId}),Q=t1(e.prompt),{responseHeaders:K,value:he,rawValue:V}=await Yt({url:X,headers:qt(this.config.headers(),e.headers),body:j,failedResponseHandler:Mr,successfulResponseHandler:fr(BR),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new ct({message:he.error.message,url:X,requestBodyValues:j,statusCode:400,responseHeaders:K,responseBody:V,isRetryable:!1});const P=[],H=[];let Z=!1;for(const L of he.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const W of L.summary)P.push({type:"reasoning",text:W.text,providerMetadata:{[N]:{itemId:L.id,reasoningEncryptedContent:(t=L.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),result:{result:L.result}});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:L.action}),providerMetadata:{[N]:{itemId:L.id}}});break}case"shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:L.action.commands}}),...G&&{providerExecuted:!0},providerMetadata:{[N]:{itemId:L.id}}});break}case"shell_call_output":{P.push({type:"tool-result",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),result:{output:L.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="exit"?{type:"exit",exitCode:W.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const W of L.content){(n=(r=e.providerOptions)==null?void 0:r[N])!=null&&n.logprobs&&W.logprobs&&H.push(W.logprobs);const te={itemId:L.id,...L.phase!=null&&{phase:L.phase},...W.annotations.length>0&&{annotations:W.annotations}};P.push({type:"text",text:W.text,providerMetadata:{[N]:te}});for(const se of W.annotations)se.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:Zt(),url:se.url,title:se.title}):se.type==="file_citation"?P.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:se.filename,filename:se.filename,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?P.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:se.filename,filename:se.filename,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(v=(m=(f=this.config).generateId)==null?void 0:m.call(f))!=null?v:Zt(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[N]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{Z=!0,P.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{[N]:{itemId:L.id}}});break}case"custom_tool_call":{Z=!0;const W=A.toCustomToolName(L.name);P.push({type:"tool-call",toolCallId:L.call_id,toolName:W,input:JSON.stringify(L.input),providerMetadata:{[N]:{itemId:L.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName(U??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName(U??"web_search"),result:n1(L.action)});break}case"mcp_call":{const W=L.approval_request_id!=null&&(y=Q[L.approval_request_id])!=null?y:L.id,te=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:W,toolName:te,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-result",toolCallId:W,toolName:te,result:{type:"call",serverLabel:L.server_label,name:L.name,arguments:L.arguments,...L.output!=null?{output:L.output}:{},...L.error!=null?{error:L.error}:{}},providerMetadata:{[N]:{itemId:L.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const W=(w=L.approval_request_id)!=null?w:L.id,te=(C=(g=(_=this.config).generateId)==null?void 0:g.call(_))!=null?C:Zt(),se=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:te,toolName:se,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-approval-request",approvalId:W,toolCallId:te});break}case"computer_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:L.status||"completed"}});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),result:{queries:L.queries,results:(k=(b=L.results)==null?void 0:b.map(W=>({attributes:W.attributes,fileId:W.file_id,filename:W.filename,score:W.score,text:W.text})))!=null?k:null}});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:L.code,containerId:L.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:L.outputs}});break}case"apply_patch_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:L.call_id,operation:L.operation}),providerMetadata:{[N]:{itemId:L.id}}});break}}const E={[N]:{responseId:he.id,...H.length>0?{logprobs:H}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},M=he.usage;return{content:P,finishReason:{unified:Q_({finishReason:(S=he.incomplete_details)==null?void 0:S.reason,hasFunctionCall:Z}),raw:(x=(I=he.incomplete_details)==null?void 0:I.reason)!=null?x:void 0},usage:K_(M),request:{body:j},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:K,body:V},providerMetadata:E,warnings:O}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await Yt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Mr,successfulResponseHandler:cl(HR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,h=t1(e.prompt),p=new Map;let f={unified:"other",raw:void 0},m;const v=[];let y=null;const w={},_=[];let g,C=!1;const b={};let k;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,I){var x,j,O,U,A,N,G,X,Q,K,he,V,P,H,Z,E,M,L,W,te,se,Se,z,F,Y,ee,ue,xe,He,ot,ft,et;if(e.includeRawChunks&&I.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},I.enqueue({type:"error",error:S.error});return}const $=S.value;if(r1($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const ne=o.toCustomToolName($.item.name);w[$.output_index]={toolName:ne,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:ne})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:ne,operation:Le}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Le.type==="delete_file",endEmitted:Le.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:ne,toolName:o.toCustomToolName("apply_patch")}),Le.type==="delete_file"){const _t=JSON.stringify({callId:ne,operation:Le});I.enqueue({type:"tool-input-delta",id:ne,delta:_t}),I.enqueue({type:"tool-input-end",id:ne})}else I.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${lo(ne)}","operation":{"type":"${lo(Le.type)}","path":"${lo(Le.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(_.splice(0,_.length),g=(x=$.item.phase)!=null?x:void 0,I.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):r1($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(j=$.item.encrypted_content)!=null?j:null}}})))}else if(QR($)){if($.item.type==="message"){const ne=(O=$.item.phase)!=null?O:g;g=void 0,I.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...ne!=null&&{phase:ne},..._.length>0&&{annotations:_}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,C=!0,I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,C=!0;const ne=o.toCustomToolName($.item.name);I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:ne,input:JSON.stringify($.item.input),providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:n1($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(A=(U=$.item.results)==null?void 0:U.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?A:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const ne=(N=$.item.approval_request_id)!=null?N:void 0,Le=ne!=null&&(X=(G=p.get(ne))!=null?G:h[ne])!=null?X:$.item.id,_t=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:Le,toolName:_t,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:Le,toolName:_t,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const ne=w[$.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:lo($.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&$.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[a]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const ne=(he=(K=(Q=u.config).generateId)==null?void 0:K.call(Q))!=null?he:Zt(),Le=(V=$.item.approval_request_id)!=null?V:$.item.id;p.set(Le,ne);const _t=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:ne,toolName:_t,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:Le,toolCallId:ne})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.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($.item.type==="reasoning"){const ne=b[$.item.id],Le=Object.entries(ne.summaryParts).filter(([_t,Ht])=>Ht==="active"||Ht==="can-conclude").map(([_t])=>_t);for(const _t of Le)I.enqueue({type:"reasoning-end",id:`${$.item.id}:${_t}`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(P=$.item.encrypted_content)!=null?P:null}}});delete b[$.item.id]}}else if(tP($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:$.delta})}else if(rP($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:$.delta})}else if(aP($)){const ne=w[$.output_index];ne?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:lo($.delta)}),ne.applyPatch.hasDiff=!0)}else if(iP($)){const ne=w[$.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:lo($.diff)}),ne.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(nP($))I.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(oP($)){const ne=w[$.output_index];ne!=null&&I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:lo($.delta)})}else if(sP($)){const ne=w[$.output_index];ne!=null&&(I.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:ne.toolCallId}),I.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(eP($))y=$.response.id,I.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(YR($))I.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(Z=(H=e.providerOptions)==null?void 0:H[a])!=null&&Z.logprobs&&$.logprobs&&v.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const ne=b[$.item_id];ne.summaryParts[$.summary_index]="active";for(const Le of Object.keys(ne.summaryParts))ne.summaryParts[Le]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${Le}`,providerMetadata:{[a]:{itemId:$.item_id}}}),ne.summaryParts[Le]="concluded");I.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id,reasoningEncryptedContent:(M=(E=b[$.item_id])==null?void 0:E.encryptedContent)!=null?M:null}}})}}else $.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[a]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude":XR($)?(f={unified:Q_({finishReason:(L=$.response.incomplete_details)==null?void 0:L.reason,hasFunctionCall:C}),raw:(te=(W=$.response.incomplete_details)==null?void 0:W.reason)!=null?te:void 0},m=$.response.usage,typeof $.response.service_tier=="string"&&(k=$.response.service_tier)):lP($)?(_.push($.annotation),$.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(z=(Se=(se=u.config).generateId)==null?void 0:Se.call(se))!=null?z:Zt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(ee=(Y=(F=u.config).generateId)==null?void 0:Y.call(F))!=null?ee:Zt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(He=(xe=(ue=u.config).generateId)==null?void 0:xe.call(ue))!=null?He:Zt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(et=(ft=(ot=u.config).generateId)==null?void 0:ft.call(ot))!=null?et:Zt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):cP($)&&I.enqueue({type:"error",error:$})},flush(S){const I={[a]:{responseId:y,...v.length>0?{logprobs:v}:{},...k!==void 0?{serviceTier:k}:{}}};S.enqueue({type:"finish",finishReason:f,usage:K_(m),providerMetadata:I})}})),request:{body:t},response:{headers:l}}}};function YR(e){return e.type==="response.output_text.delta"}function QR(e){return e.type==="response.output_item.done"}function XR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function eP(e){return e.type==="response.created"}function tP(e){return e.type==="response.function_call_arguments.delta"}function rP(e){return e.type==="response.custom_tool_call_input.delta"}function nP(e){return e.type==="response.image_generation_call.partial_image"}function oP(e){return e.type==="response.code_interpreter_call_code.delta"}function sP(e){return e.type==="response.code_interpreter_call_code.done"}function aP(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function iP(e){return e.type==="response.apply_patch_call_operation_diff.done"}function r1(e){return e.type==="response.output_item.added"}function lP(e){return e.type==="response.output_text.annotation.added"}function cP(e){return e.type==="error"}function n1(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 lo(e){return JSON.stringify(e).slice(1,-1)}var uP=be(()=>we(T({instructions:d().nullish(),speed:D().min(.25).max(4).default(1).nullish()}))),dP=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 sn({provider:"openai",providerOptions:a,schema:uP}),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 Yt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),body:s,failedResponseHandler:Mr,successfulResponseHandler:tx(),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}}}},pP=be(()=>we(T({text:d(),language:d().nullish(),duration:D().nullish(),words:q(T({word:d(),start:D(),end:D()})).nullish(),segments:q(T({id:D(),seek:D(),start:D(),end:D(),text:d(),tokens:q(D()),temperature:D(),avg_logprob:D(),compression_ratio:D(),no_speech_prob:D()})).nullish()}))),fP=be(()=>we(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:D().min(0).max(1).default(0).optional(),timestampGranularities:q(ye(["word","segment"])).default(["segment"]).optional()}))),o1={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"},hP=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 sn({provider:"openai",providerOptions:r,schema:fP}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([qo(e)]);s.append("model",this.modelId);const i=nI(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:m}=await qg({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:qt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Mr,successfulResponseHandler:fr(pP),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in o1?o1[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:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:f,body:m}}}},mP="3.0.41";function s1(e={}){var t,r;const n=(t=Dg(Do({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>$n({Authorization:`Bearer ${rI({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${mP}`),a=v=>new B7(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=v=>new K7(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new X7(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new nR(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new hP(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),h=v=>new dP(v,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new KR(v,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),m=function(v){return p(v)};return m.specificationVersion="v3",m.languageModel=p,m.chat=a,m.completion=i,m.responses=f,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=u,m.transcriptionModel=u,m.speech=h,m.speechModel=h,m.tools=ZR,m}s1();var a1="vercel.ai.error",gP=Symbol.for(a1),i1,yP=class yw extends Error{constructor({name:t,message:r,cause:n}){super(r),this[i1]=!0,this.name=t,this.cause=n}static isInstance(t){return yw.hasMarker(t,a1)}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}};i1=gP;var It=yP,l1="AI_APICallError",c1=`vercel.ai.error.${l1}`,vP=Symbol.for(c1),u1,cn=class extends It{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:l1,message:e,cause:a}),this[u1]=!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 It.hasMarker(e,c1)}};u1=vP;var d1="AI_EmptyResponseBodyError",p1=`vercel.ai.error.${d1}`,_P=Symbol.for(p1),f1,wP=class extends It{constructor({message:e="Empty response body"}={}){super({name:d1,message:e}),this[f1]=!0}static isInstance(e){return It.hasMarker(e,p1)}};f1=_P;function h1(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var m1="AI_InvalidArgumentError",g1=`vercel.ai.error.${m1}`,bP=Symbol.for(g1),y1,v1=class extends It{constructor({message:e,cause:t,argument:r}){super({name:m1,message:e,cause:t}),this[y1]=!0,this.argument=r}static isInstance(e){return It.hasMarker(e,g1)}};y1=bP;var _1="AI_InvalidResponseDataError",w1=`vercel.ai.error.${_1}`,kP=Symbol.for(w1),b1,k1=class extends It{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:_1,message:t}),this[b1]=!0,this.data=e}static isInstance(e){return It.hasMarker(e,w1)}};b1=kP;var T1="AI_JSONParseError",C1=`vercel.ai.error.${T1}`,TP=Symbol.for(C1),S1,xl=class extends It{constructor({text:e,cause:t}){super({name:T1,message:`JSON parsing failed: Text: ${e}.
|
|
596
|
+
Error message: ${h1(t)}`,cause:t}),this[S1]=!0,this.text=e}static isInstance(e){return It.hasMarker(e,C1)}};S1=TP;var I1="AI_LoadAPIKeyError",x1=`vercel.ai.error.${I1}`,CP=Symbol.for(x1),E1,El=class extends It{constructor({message:e}){super({name:I1,message:e}),this[E1]=!0}static isInstance(e){return It.hasMarker(e,x1)}};E1=CP;var $1="AI_NoSuchModelError",R1=`vercel.ai.error.${$1}`,SP=Symbol.for(R1),P1,M1=class extends It{constructor({errorName:e=$1,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[P1]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return It.hasMarker(e,R1)}};P1=SP;var O1="AI_TypeValidationError",N1=`vercel.ai.error.${O1}`,IP=Symbol.for(N1),A1,xP=class $p extends It{constructor({value:t,cause:r}){super({name:O1,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
597
|
+
Error message: ${h1(r)}`,cause:r}),this[A1]=!0,this.value=t}static isInstance(t){return It.hasMarker(t,N1)}static wrap({value:t,cause:r}){return $p.isInstance(r)&&r.value===t?r:new $p({value:t,cause:r})}};A1=IP;var la=xP,q1="AI_UnsupportedFunctionalityError",L1=`vercel.ai.error.${q1}`,EP=Symbol.for(L1),j1,D1=class extends It{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:q1,message:t}),this[j1]=!0,this.functionality=e}static isInstance(e){return It.hasMarker(e,L1)}};j1=EP;function U1(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function $l(e){return Object.fromEntries([...e.headers])}var $P=({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 v1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Rl=$P();function up(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var RP=["fetch failed","failed to fetch"];function PP({error:e,url:t,requestBodyValues:r}){if(up(e))return e;if(e instanceof TypeError&&RP.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new cn({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function MP(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 OP(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 z1(e,...t){const r=new Headers(OP(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var NP="3.0.18";function AP({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new El({message:`${n} API key must be a string.`});if(typeof process>"u")throw new El({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new El({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new El({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var qP=/"__proto__"\s*:/,LP=/"constructor"\s*:/;function Z1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||qP.test(e)===!1&&LP.test(e)===!1?t:jP(t)}function jP(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 dp(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Z1(e)}try{return Z1(e)}finally{Error.stackTraceLimit=t}}var pp=Symbol.for("vercel.ai.validator");function DP(e){return{[pp]:!0,validate:e}}function UP(e){return typeof e=="object"&&e!==null&&pp in e&&e[pp]===!0&&"validate"in e}function zP(e){return UP(e)?e:typeof e=="function"?e():ZP(e)}function ZP(e){return DP(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new la({value:t,cause:r.issues})}})}async function FP({value:e,schema:t}){const r=await ca({value:e,schema:t});if(!r.success)throw la.wrap({value:e,cause:r.error});return r.value}async function ca({value:e,schema:t}){const r=zP(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:la.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:la.wrap({value:e,cause:n}),rawValue:e}}}async function VP({text:e,schema:t}){try{const r=dp(e);return t==null?r:FP({value:r,schema:t})}catch(r){throw xl.isInstance(r)||la.isInstance(r)?r:new xl({text:e,cause:r})}}async function F1({text:e,schema:t}){try{const r=dp(e);return t==null?{success:!0,value:r,rawValue:r}:await ca({value:r,schema:t})}catch(r){return{success:!1,error:xl.isInstance(r)?r:new xl({text:e,cause:r}),rawValue:void 0}}}function V1(e){try{return dp(e),!0}catch{return!1}}function HP({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Po).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await F1({text:r,schema:t}))}}))}async function H1({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ca({value:t[e],schema:r});if(!n.success)throw new v1({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var BP=()=>globalThis.fetch,B1=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>JP({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),JP=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=BP()})=>{try{const i=await a(e,{method:"POST",headers:z1(t,`ai-sdk/provider-utils/${NP}`,MP()),body:r.content,signal:s}),l=$l(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw up(u)||cn.isInstance(u)?u:new cn({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&&(up(c)||cn.isInstance(c))?c:new cn({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw PP({error:i,url:e,requestBodyValues:r.values})}},GP=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=$l(n);if(a.trim()==="")return{responseHeaders:i,value:new cn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await VP({text:a,schema:e});return{responseHeaders:i,value:new cn({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 cn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},WP=e=>async({response:t})=>{const r=$l(t);if(t.body==null)throw new wP({});return{responseHeaders:r,value:HP({stream:t.body,schema:e})}},KP=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await F1({text:o,schema:e}),a=$l(t);if(!s.success)throw new cn({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:YP}=globalThis;function QP(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return YP(t)}function XP(e){return e instanceof Uint8Array?QP(e):e}function eM(e){return e?.replace(/\/$/,"")}function ua(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function tM(e){const t=[];for(const{role:r,content:n,...o}of e){const s=ua({...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,...ua(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=ua(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,${XP(a.data)}`},...i}}else throw new D1({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=ua(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=ua(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 J1({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 G1(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 fp=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),rM=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),D()]).nullish()})}),nM={errorSchema:rM,errorToMessage:e=>e.error.message};function oM({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 D1({functionality:`tool choice type: ${s}`})}}}var sM=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:nM;this.chunkSchema=iM(o.errorSchema),this.failedResponseHandler=GP(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,m,v,y;const w=[],_=Object.assign((f=await H1({provider:"openai-compatible",providerOptions:i,schema:fp}))!=null?f:{},(m=await H1({provider:this.providerOptionsName,providerOptions:i,schema:fp}))!=null?m:{});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:g,toolChoice:C,toolWarnings:b}=oM({tools:p,toolChoice:h});return{args:{model:this.modelId,user:_.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:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([k])=>!Object.keys(fp.shape).includes(k))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:tM(e),tools:g,tool_choice:C},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,h,p,f,m,v,y,w;const{args:_,warnings:g}=await this.getArgs({...e}),C=JSON.stringify(_),{responseHeaders:b,value:k,rawValue:S}=await B1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:U1(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:KP(aM),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=k.choices[0],x=[],j=I.message.content;j!=null&&j.length>0&&x.push({type:"text",text:j});const O=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(O!=null&&O.length>0&&x.push({type:"reasoning",text:O}),I.message.tool_calls!=null)for(const N of I.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=N.id)!=null?r:Rl(),toolName:N.function.name,input:N.function.arguments});const U={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=k.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(U[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(U[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:x,finishReason:G1(I.finish_reason),usage:{inputTokens:(i=(a=k.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=k.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=k.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(m=(f=(p=k.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:void 0,cachedInputTokens:(w=(y=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:U,request:{body:C},response:{...J1(k),headers:b,body:S},warnings:g}}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 B1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:U1(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:WP(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,m=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,g,C,b,k,S,I,x,j,O,U,A;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const N=v.value;if(s?.processChunk(v.rawValue),"error"in N){c="error",y.enqueue({type:"error",error:N.error.message});return}if(h&&(h=!1,y.enqueue({type:"response-metadata",...J1(N)})),N.usage!=null){const{prompt_tokens:K,completion_tokens:he,total_tokens:V,prompt_tokens_details:P,completion_tokens_details:H}=N.usage;u.promptTokens=K??void 0,u.completionTokens=he??void 0,u.totalTokens=V??void 0,H?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=H?.reasoning_tokens),H?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=H?.accepted_prediction_tokens),H?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=H?.rejected_prediction_tokens),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const G=N.choices[0];if(G?.finish_reason!=null&&(c=G1(G.finish_reason)),G?.delta==null)return;const X=G.delta,Q=(w=X.reasoning_content)!=null?w:X.reasoning;if(Q&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Q})),X.content&&(m||(y.enqueue({type:"text-start",id:"txt-0"}),m=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:X.content})),X.tool_calls!=null)for(const K of X.tool_calls){const he=K.index;if(l[he]==null){if(K.id==null)throw new k1({data:K,message:"Expected 'id' to be a string."});if(((_=K.function)==null?void 0:_.name)==null)throw new k1({data:K,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),l[he]={id:K.id,type:"function",function:{name:K.function.name,arguments:(g=K.function.arguments)!=null?g:""},hasFinished:!1};const P=l[he];((C=P.function)==null?void 0:C.name)!=null&&((b=P.function)==null?void 0:b.arguments)!=null&&(P.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),V1(P.function.arguments)&&(y.enqueue({type:"tool-input-end",id:P.id}),y.enqueue({type:"tool-call",toolCallId:(k=P.id)!=null?k:Rl(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const V=l[he];V.hasFinished||(((S=K.function)==null?void 0:S.arguments)!=null&&(V.function.arguments+=(x=(I=K.function)==null?void 0:I.arguments)!=null?x:""),y.enqueue({type:"tool-input-delta",id:V.id,delta:(j=K.function.arguments)!=null?j:""}),((O=V.function)==null?void 0:O.name)!=null&&((U=V.function)==null?void 0:U.arguments)!=null&&V1(V.function.arguments)&&(y.enqueue({type:"tool-input-end",id:V.id}),y.enqueue({type:"tool-call",toolCallId:(A=V.id)!=null?A:Rl(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(v){var y,w,_,g,C,b;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),m&&v.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:S.id}),v.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:Rl(),toolName:S.function.name,input:S.function.arguments});const k={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(C=u.completionTokensDetails.reasoningTokens)!=null?C:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:k})}})),request:{body:o},response:{headers:a}}}},W1=T({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:T({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish(),aM=T({id:d().nullish(),created:D().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:W1}),iM=e=>ae([T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({delta:T({role:ye(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:D(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:W1}),e]);T({echo:ge().optional(),logitBias:ve(d(),D()).optional(),suffix:d().optional(),user:d().optional()});var lM=T({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()});T({id:d().nullish(),created:D().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:lM.nullish()}),T({dimensions:D().optional(),user:d().optional()}),T({data:q(T({embedding:q(D())})),usage:T({prompt_tokens:D()}).nullish(),providerMetadata:ve(d(),ve(d(),Tt())).optional()}),T({data:q(T({b64_json:d()}))});var K1=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}}},cM={extractMetadata:async({parsedBody:e})=>{const t=await ca({value:e,schema:uM});return!t.success||t.value.usage==null?void 0:K1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await ca({value:t,schema:dM});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:()=>K1(e)}}},Y1=T({prompt_cache_hit_tokens:D().nullish(),prompt_cache_miss_tokens:D().nullish()}),uM=T({usage:Y1.nullish()}),dM=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:Y1.nullish()}),pM="1.0.30";function Q1(e={}){var t;const r=eM((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>z1({Authorization:`Bearer ${AP({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${pM}`);class o extends sM{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:cM}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new M1({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new M1({modelId:i,modelType:"imageModel"})},a}Q1();const X1=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]=jg({description:o,inputSchema:Uo({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function fM(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
598
598
|
# 工具调用
|
|
599
599
|
|
|
600
600
|
你可以根据需要调用以下工具:
|
|
@@ -630,15 +630,183 @@ Thought: 用户想要获取今天的日期,我需要调用日期相关的工
|
|
|
630
630
|
- 必须严格按照 XML 格式调用工具
|
|
631
631
|
- arguments 必须是有效的 JSON 格式
|
|
632
632
|
- 如果不需要调用工具,直接给出最终答案即可
|
|
633
|
-
`,r}function
|
|
634
|
-
${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===
|
|
635
|
-
${
|
|
636
|
-
</tool_response>`};l.push(k),a.push(k)}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
|
|
633
|
+
`,r}function ew(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 hM={openai:s1,deepseek:Q1};class mM{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=hM[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 js(new URL(t.url)):"type"in t&&t.type==="extension"?r=new z0(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 j0({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 Fs||r&&r instanceof Ds)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 X1(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={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=fM(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
634
|
+
${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===tp?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,...m}=s,y=(await n_({model:this.llm(n),messages:p,...m})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const _=ew(y,r);if(!_)return this.responseMessages=a,{text:y,response:{messages:a}};const g=await this._executeReActToolCall(_.toolName,_.arguments,r),k={role:"user",content:`<tool_response>
|
|
635
|
+
${g.success?JSON.stringify(g.result):`工具执行失败 - ${g.error}`}
|
|
636
|
+
</tool_response>`};l.push(k),a.push(k)}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 m=t[0]?.role==="system"?t[0]:null,v=m?t.slice(1):[...t];let y=0,w="";const _=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const g=a._buildMessagesForModel(m,v,_),{tools:C,...b}=s;delete b.system,delete b.onFinish;const k=await tp({...b,model:i,messages:g});let S="";for await(const X of k.fullStream)X.type==="text-delta"?(S+=X.text||"",p.enqueue({type:"text-delta",text:X.text})):X.type==="text-start"?p.enqueue({type:"text-start"}):X.type==="text-end"||X.type==="finish-step"||X.type==="finish"||X.type==="start"||X.type==="start-step"||p.enqueue(X);w+=S;const I={role:"assistant",content:w};v.push(I),f.push(I);const x=ew(w,r);if(!x){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});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=f,l({messages:f});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:x.toolName});const O=JSON.stringify(x.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:O}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:x.toolName,input:x.arguments});const U=await a._executeReActToolCall(x.toolName,x.arguments,r);let A,N=U.result;if(U.success&&U.result&&typeof U.result=="object"&&U.result.screenshot){A=U.result.screenshot;const{screenshot:X,...Q}=U.result;N=Q}let G="";if(U.success){N&&Array.isArray(N.content)&&N.content.length>0&&N.content[0].text?G=N.content[0].text:G=JSON.stringify(N);let X=`<tool_response>
|
|
637
637
|
${G}
|
|
638
638
|
</tool_response>`;A&&(X+=`
|
|
639
|
-
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:X});const Q=A?{role:"user",content:[{type:"text",text:X},{type:"image",image:A}]}:{role:"user",content:X};v.push(Q),f.push(Q),w=""}else G=`工具执行失败 - ${U.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:
|
|
639
|
+
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:X});const Q=A?{role:"user",content:[{type:"text",text:X},{type:"image",image:A}]}:{role:"user",content:X};v.push(Q),f.push(Q),w=""}else G=`工具执行失败 - ${U.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:x.arguments,error:{message:G}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f})}catch(g){p.error(g),c(g)}}}),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=this._tempMergeTools(o.tools,!1),a={model:this.llm(r),stopWhen:Qd(n),...o,tools:s,activeTools:this._getActiveToolNames(s)};let i=null;if(o.message&&!o.messages)i={role:"user",content:o.message},this.responseMessages.push(i),a.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const c=o.messages[o.messages.length-1];c.role==="user"&&(i=c)}const l=t(a);return l?.response?.then(c=>{const u=c.messages?.[0];i&&u?.role!=="user"&&this.responseMessages.push(i),this.responseMessages.push(...c.messages)}),l}async chat(t){return this._chat(n_,t)}async chatStream(t){return this._chat(tp,t)}}let un=null,Pl=null,tw=null,Ml=0;const gM="next-sdk-tool-body-glow";function da(){return typeof window<"u"&&typeof document<"u"}function yM(){if(!da()||tw)return;const e=document.createElement("style");e.textContent=`
|
|
640
|
+
.${gM} {
|
|
641
|
+
position: relative;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
.next-sdk-tool-overlay {
|
|
645
|
+
position: fixed;
|
|
646
|
+
inset: 0;
|
|
647
|
+
z-index: 999999;
|
|
648
|
+
pointer-events: none;
|
|
649
|
+
display: flex;
|
|
650
|
+
align-items: flex-end;
|
|
651
|
+
justify-content: flex-start;
|
|
652
|
+
padding: 0 0 18px 18px;
|
|
653
|
+
background: transparent;
|
|
654
|
+
animation: next-sdk-overlay-fade-in 260ms ease-out;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
.next-sdk-tool-overlay--exit {
|
|
658
|
+
animation: next-sdk-overlay-fade-out 220ms ease-in forwards;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
.next-sdk-tool-overlay__glow-ring {
|
|
662
|
+
display: none;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
.next-sdk-tool-overlay__panel {
|
|
666
|
+
position: relative;
|
|
667
|
+
min-width: min(320px, 78vw);
|
|
668
|
+
max-width: min(420px, 82vw);
|
|
669
|
+
padding: 10px 14px;
|
|
670
|
+
border-radius: 999px;
|
|
671
|
+
background:
|
|
672
|
+
linear-gradient(135deg, rgba(15, 23, 42, 0.9), rgba(17, 24, 39, 0.9)),
|
|
673
|
+
radial-gradient(circle at top left, rgba(96, 165, 250, 0.25), transparent 55%),
|
|
674
|
+
radial-gradient(circle at bottom right, rgba(45, 212, 191, 0.22), transparent 60%);
|
|
675
|
+
box-shadow:
|
|
676
|
+
0 12px 28px rgba(15, 23, 42, 0.78),
|
|
677
|
+
0 0 0 1px rgba(148, 163, 184, 0.26);
|
|
678
|
+
display: flex;
|
|
679
|
+
align-items: center;
|
|
680
|
+
gap: 10px;
|
|
681
|
+
pointer-events: none;
|
|
682
|
+
transform-origin: center;
|
|
683
|
+
animation: next-sdk-panel-pop-in 260ms cubic-bezier(0.18, 0.89, 0.32, 1.28);
|
|
684
|
+
color: #e5e7eb;
|
|
685
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
.next-sdk-tool-overlay__indicator {
|
|
689
|
+
width: 26px;
|
|
690
|
+
height: 26px;
|
|
691
|
+
border-radius: 999px;
|
|
692
|
+
background: radial-gradient(circle at 30% 10%, #f9fafb, #93c5fd);
|
|
693
|
+
box-shadow:
|
|
694
|
+
0 0 0 1px rgba(191, 219, 254, 0.6),
|
|
695
|
+
0 8px 18px rgba(37, 99, 235, 0.8),
|
|
696
|
+
0 0 28px rgba(56, 189, 248, 0.9);
|
|
697
|
+
position: relative;
|
|
698
|
+
flex-shrink: 0;
|
|
699
|
+
display: flex;
|
|
700
|
+
align-items: center;
|
|
701
|
+
justify-content: center;
|
|
702
|
+
overflow: hidden;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
.next-sdk-tool-overlay__indicator-orbit {
|
|
706
|
+
position: absolute;
|
|
707
|
+
inset: 2px;
|
|
708
|
+
border-radius: inherit;
|
|
709
|
+
border: 1px solid rgba(248, 250, 252, 0.6);
|
|
710
|
+
box-sizing: border-box;
|
|
711
|
+
opacity: 0.9;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
.next-sdk-tool-overlay__indicator-orbit::before {
|
|
715
|
+
content: '';
|
|
716
|
+
position: absolute;
|
|
717
|
+
width: 6px;
|
|
718
|
+
height: 6px;
|
|
719
|
+
border-radius: 999px;
|
|
720
|
+
background: #f9fafb;
|
|
721
|
+
box-shadow:
|
|
722
|
+
0 0 12px rgba(248, 250, 252, 0.9),
|
|
723
|
+
0 0 24px rgba(250, 249, 246, 0.9);
|
|
724
|
+
top: 0;
|
|
725
|
+
left: 50%;
|
|
726
|
+
transform: translate(-50%, -50%);
|
|
727
|
+
transform-origin: 50% 18px;
|
|
728
|
+
animation: next-sdk-indicator-orbit 1.4s linear infinite;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
.next-sdk-tool-overlay__indicator-core {
|
|
732
|
+
width: 14px;
|
|
733
|
+
height: 14px;
|
|
734
|
+
border-radius: inherit;
|
|
735
|
+
background: radial-gradient(circle at 30% 20%, #f9fafb, #bfdbfe);
|
|
736
|
+
box-shadow:
|
|
737
|
+
0 0 12px rgba(248, 250, 252, 0.9),
|
|
738
|
+
0 0 32px rgba(191, 219, 254, 0.8);
|
|
739
|
+
opacity: 0.96;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
.next-sdk-tool-overlay__content {
|
|
743
|
+
display: flex;
|
|
744
|
+
flex-direction: column;
|
|
745
|
+
gap: 1px;
|
|
746
|
+
min-width: 0;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
.next-sdk-tool-overlay__title {
|
|
750
|
+
font-size: 11px;
|
|
751
|
+
letter-spacing: 0.08em;
|
|
752
|
+
text-transform: uppercase;
|
|
753
|
+
color: rgba(156, 163, 175, 0.96);
|
|
754
|
+
display: flex;
|
|
755
|
+
align-items: center;
|
|
756
|
+
gap: 6px;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
.next-sdk-tool-overlay__title-dot {
|
|
760
|
+
width: 6px;
|
|
761
|
+
height: 6px;
|
|
762
|
+
border-radius: 999px;
|
|
763
|
+
background: #22c55e;
|
|
764
|
+
box-shadow:
|
|
765
|
+
0 0 8px rgba(34, 197, 94, 0.9),
|
|
766
|
+
0 0 14px rgba(22, 163, 74, 0.9);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
.next-sdk-tool-overlay__label {
|
|
770
|
+
font-size: 12px;
|
|
771
|
+
font-weight: 500;
|
|
772
|
+
color: #e5e7eb;
|
|
773
|
+
white-space: nowrap;
|
|
774
|
+
text-overflow: ellipsis;
|
|
775
|
+
overflow: hidden;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
@keyframes next-sdk-overlay-fade-in {
|
|
779
|
+
from { opacity: 0; }
|
|
780
|
+
to { opacity: 1; }
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
@keyframes next-sdk-overlay-fade-out {
|
|
784
|
+
from { opacity: 1; }
|
|
785
|
+
to { opacity: 0; }
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
@keyframes next-sdk-indicator-orbit {
|
|
789
|
+
from {
|
|
790
|
+
transform: translate(-50%, -50%) rotate(0deg) translateY(0);
|
|
791
|
+
}
|
|
792
|
+
to {
|
|
793
|
+
transform: translate(-50%, -50%) rotate(360deg) translateY(0);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
@keyframes next-sdk-panel-pop-in {
|
|
798
|
+
0% {
|
|
799
|
+
opacity: 0;
|
|
800
|
+
transform: scale(0.92) translateY(10px);
|
|
801
|
+
}
|
|
802
|
+
100% {
|
|
803
|
+
opacity: 1;
|
|
804
|
+
transform: scale(1) translateY(0);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
`,document.head.appendChild(e),tw=e}function vM(){if(!da()||un)return;yM();const e=document.createElement("div");e.className="next-sdk-tool-overlay";const t=document.createElement("div");t.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-orbit";const s=document.createElement("div");s.className="next-sdk-tool-overlay__indicator-core";const a=document.createElement("div");a.className="next-sdk-tool-overlay__content";const i=document.createElement("div");i.className="next-sdk-tool-overlay__title",i.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",i.prepend(l),a.appendChild(i),a.appendChild(c),n.appendChild(o),n.appendChild(s),r.appendChild(n),r.appendChild(a),e.appendChild(t),e.appendChild(r),document.body.appendChild(e),un=e,Pl=c}function _M(e){da()&&(vM(),!(!un||!Pl)&&(un.classList.remove("next-sdk-tool-overlay--exit"),Pl.textContent=e.label))}function wM(){if(!un)return;un.classList.add("next-sdk-tool-overlay--exit");const e=un;let t=!1,r;const n=()=>{t||(t=!0,r!==void 0&&(clearTimeout(r),r=void 0),e.parentNode&&e.parentNode.removeChild(e),un===e&&(un=null,Pl=null),e.removeEventListener("animationend",n))};e.addEventListener("animationend",n),r=setTimeout(n,500)}function bM(e){da()&&(Ml+=1,_M(e))}function kM(){!da()||Ml<=0||(Ml-=1,Ml===0&&wM())}function TM(e,t,r){if(!r)return;const n=t||e;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const rw="next-sdk:tool-call",hp="next-sdk:tool-response",mp="next-sdk:page-ready",nw="next-sdk:page-leave",ow="next-sdk:remoter-ready",sw="next-sdk:route-state-initial",Vo=new Map,Ol=e=>e.replace(/\/+$/,"")||"/",gp=new Set;function CM(){typeof window<"u"&&gp.add({win:window,origin:window.location.origin||"*"})}CM();function aw(e,t){const r={type:e,route:t};gp.forEach(({win:n,origin:o})=>{try{n.postMessage(r,o)}catch{}})}function SM(){typeof window>"u"||window.addEventListener("message",e=>{if(e.data?.type!==ow||!e.source||e.origin!==window.location.origin)return;const t=e.source;gp.add({win:t,origin:e.origin||"*"});const r={type:sw,toolRouteMap:Array.from(yp.entries()),activeRoutes:Array.from(Vo.keys())};try{t.postMessage(r,e.origin||"*")}catch{}})}SM();const yp=new Map;function IM(){return new Map(yp)}function xM(){return new Set(Vo.keys())}let pa=null;function EM(e){pa=e}function $M(e,t=1500){if(typeof window>"u")return Promise.resolve();const r=Ol(e);return new Promise(n=>{let o=!1;const s=()=>{o||(o=!0,window.removeEventListener("message",a),n())},a=i=>{if(i.source!==window||i.data?.type!==mp)return;Ol(String(i.data.route??""))===r&&s()};window.addEventListener("message",a),setTimeout(s,t)})}function RM(e,t){const r=t?.name??"navigate_to_page",n=t?.title??"页面跳转",o=t?.description??'当需要的工具在当前页面不可用时,使用此工具跳转到特定页面。例如:要查询订单时跳转到 "/orders",要创建价保时跳转到 "/price-protection"。',s=t?.timeoutMs??1500;return e.registerTool(r,{title:n,description:o,inputSchema:{path:Ue().describe('目标页面的路由地址,例如 "/orders"、"/inventory"、"/price-protection" 等。')}},async({path:a})=>{if(typeof window>"u")return{content:[{type:"text",text:"当前环境不支持页面跳转(window 不存在)。"}]};if(!pa)return{content:[{type:"text",text:"页面跳转失败:尚未在应用入口调用 setNavigator 注册导航函数,无法执行路由跳转。"}]};try{const i=Ol(a),l=Ol(window.location.pathname);if(l===i||l.endsWith(i)&&(l.length===i.length||l[l.lastIndexOf(i)-1]==="/"))return{content:[{type:"text",text:`当前已在页面:${a}。请继续你的下一步操作。`}]};const u=$M(a,s);return await pa(a),await u,{content:[{type:"text",text:`已成功跳转至页面:${a}。请继续你的下一步操作。`}]}}catch(i){return{content:[{type:"text",text:`页面跳转失败:${i instanceof Error?i.message:String(i)}。`}]}}})}function PM(e,t,r=3e4,n){return o=>{const s=Gu();return new Promise((a,i)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",h),c&&window.removeEventListener("message",c),n&&kM()};l=setTimeout(()=>{u(),i(new Error(`工具 [${e}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const h=y=>{y.source===window&&y.data?.type===hp&&y.data.callId===s&&(u(),y.data.error?i(new Error(y.data.error)):a(y.data.result))};window.addEventListener("message",h);const p=()=>{window.postMessage({type:rw,callId:s,toolName:e,route:t,input:o},window.location.origin||"*")};let f=!1;const m=()=>{f||(f=!0,p())};(async()=>{try{if(n&&bM(n),Vo.get(t)){m();return}c=y=>{y.source===window&&y.data?.type===mp&&y.data.route===t&&(window.removeEventListener("message",c),m())},window.addEventListener("message",c),pa&&await pa(t),Vo.get(t)&&(window.removeEventListener("message",c),m())}catch(y){u(),i(y instanceof Error?y:new Error(String(y)))}})()})}}function MM(e){return new Proxy(e,{get(t,r,n){return r==="registerTool"?(o,s,a)=>{const i=t.registerTool.bind(t);if(typeof a=="function")return i(o,s,a);const{route:l,timeout:c,invokeEffect:u}=a;yp.set(o,l);const h=TM(o,s?.title,u);return i(o,s,PM(o,l,c,h))}:Reflect.get(t,r,n)}})}function OM(e){const{route:t,handlers:r}=e,n=a=>a.replace(/\/+$/,"")||"/",o=n(t??window.location.pathname),s=async a=>{if(a.source!==window||a.data?.type!==rw||n(String(a.data?.route??""))!==o||!(a.data.toolName in r))return;const{callId:i,toolName:l,input:c}=a.data;try{const u=await r[l](c);window.postMessage({type:hp,callId:i,result:u},window.location.origin||"*")}catch(u){window.postMessage({type:hp,callId:i,error:u instanceof Error?u.message:String(u)},window.location.origin||"*")}};return Vo.set(o,!0),window.addEventListener("message",s),aw(mp,o),()=>{Vo.delete(o),window.removeEventListener("message",s),aw(nw,o)}}const iw=/^\.\/[^/]+\/SKILL\.md$/,NM=/^---\s*\n([\s\S]+?)\s*\n---/;function vp(e){const t=e.match(NM);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 Ho(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.replace(/\\/g,"/"),s=o.lastIndexOf("skills/"),a=s>=0?o.slice(s+7):o,i=a.startsWith("./")?a:`./${a}`;t[i]=n}return t}function lw(e){const t=Ho(e);return Object.keys(t).filter(r=>iw.test(r))}function AM(e){const t=Ho(e),r=Object.keys(t).filter(o=>iw.test(o)),n=[];for(const o of r){const s=t[o];if(!s)continue;const a=vp(s);a&&n.push({name:a.name,description:a.description,path:o})}return n}function qM(e){return e.length===0?"":`## 可用技能
|
|
640
808
|
|
|
641
809
|
${e.map(r=>`- **${r.name}**: ${r.description}`).join(`
|
|
642
810
|
`)}
|
|
643
811
|
|
|
644
|
-
当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function
|
|
812
|
+
当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function LM(e){const t=Ho(e);return Object.keys(t)}function Nl(e,t){const r=Ho(e),n=r[t];if(n)return n;const o=t.replace(/^\.?\//,"/"),s=Object.keys(r).find(a=>a.endsWith(o));return s?r[s]:void 0}function cw(e,t){const r=Ho(e),n=lw(r),o=n.find(s=>s.startsWith(`./${t}/SKILL.md`));if(o)return o;for(const s of n){const a=r[s];if(a){const i=vp(a);if(i&&i.name===t)return s}}}const jM=Bt({skillName:Ue().optional().describe('进入某个技能的主入口名称。优先匹配技能的目录名(如 ecommerce),或者技能的中文名称(如"客户价保单创建及审核")。'),path:Ue().optional().describe("你想查阅的文档的路径。如 ./calculator/SKILL.md 或从其他文档里看到的相对路径 ./reference/inventory.md。"),currentPath:Ue().optional().describe("你当前正在阅读的文档路径(如果有)。比如你刚刚读取了 ./ecommerce/SKILL.md,请把这个路径原样传回来,这样系统才能根据你的相对路径准确找到下一份文件。")});function DM(e){const t=Ho(e);return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整文档内容。如果你想根据相对路径查阅文件,请务必同时提供你当前所在的文件路径 currentPath。",inputSchema:jM,execute:n=>{const{skillName:o,path:s,currentPath:a}=n;let i,l="";if(s){let c=".";if(a){const p=a.lastIndexOf("/");p>=0&&(c=a.slice(0,p))}const u=`http://localhost/${c}/`;if(l="."+new URL(s,u).pathname,i=Nl(t,l),i===void 0&&(s.startsWith("./")||s.startsWith("../"))&&a){const p=a.split("/");if(p.length>=2){const m=`http://localhost/${p[1]}/`,y="."+new URL(s,m).pathname;i=Nl(t,y),i&&(l=y)}}if(i&&!t[l]){const p=l.replace(/^\.?\//,"/"),f=Object.keys(t).find(m=>m.endsWith(p));f&&(l=f)}}else if(o){const c=cw(t,o);c&&(l=c,i=Nl(t,c))}return i===void 0?{error:"未找到对应技能文档",skillName:o,path:s,providedCurrentPath:a,attemptedPath:l}:{content:i,path:l}}}}}Te.AgentModelProvider=mM,Te.Ajv=Qf,Te.AuthClientProvider=k6,Te.ContentScriptServerTransport=W6,Te.ExtensionClientTransport=z0,Te.ExtensionPageServerTransport=G6,Te.InMemoryTransport=Fs,Te.MSG_PAGE_LEAVE=nw,Te.MSG_REMOTER_READY=ow,Te.MSG_ROUTE_STATE_INITIAL=sw,Te.QrCode=b2,Te.ResourceTemplate=M6,Te.UriTemplate=on,Te.WebMcpClient=j0,Te.WebMcpServer=L6,Te.completable=S6,Te.createMessageChannelClientTransport=V6,Te.createMessageChannelPairTransport=D6,Te.createMessageChannelServerTransport=j6,Te.createRemoter=$5,Te.createSSEClientTransport=Z6,Te.createSkillTools=DM,Te.createStreamableHTTPClientTransport=F6,Te.formatSkillsForSystemPrompt=qM,Te.getAISDKTools=X1,Te.getActiveRoutes=xM,Te.getDisplayName=q6,Te.getMainSkillPathByName=cw,Te.getMainSkillPaths=lw,Te.getSkillMdContent=Nl,Te.getSkillMdPaths=LM,Te.getSkillOverviews=AM,Te.getToolRouteMap=IM,Te.isMcpClient=J6,Te.isMcpServer=z6,Te.isMessageChannelClientTransport=B6,Te.isMessageChannelServerTransport=U6,Te.isSSEClientTransport=H6,Te.isStreamableHTTPClientTransport=D0,Te.parseSkillFrontMatter=vp,Te.registerNavigateTool=RM,Te.registerPageTool=OM,Te.setNavigator=EM,Te.withPageTools=MM,Te.z=u3,Object.defineProperty(Te,Symbol.toStringTag,{value:"Module"})}));
|