@opentiny/next-sdk 0.2.0 → 0.2.1
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/WebMcpClient.ts +17 -19
- package/WebMcpServer.ts +11 -8
- package/agent/AgentModelProvider.ts +2 -0
- package/agent/type.ts +1 -1
- package/dist/WebMcpClient.d.ts +176 -35
- package/dist/WebMcpServer.d.ts +43 -154
- package/dist/agent/type.d.ts +1 -0
- package/dist/index.es.dev.js +2433 -5635
- package/dist/index.es.js +13476 -16094
- package/dist/index.js +1 -1
- package/dist/index.umd.dev.js +2395 -5597
- package/dist/index.umd.js +52 -52
- package/dist/{mcpsdk@1.23.1.dev.js → mcpsdk@1.25.2.dev.js} +2047 -482
- package/dist/{mcpsdk@1.23.1.es.dev.js → mcpsdk@1.25.2.es.dev.js} +2047 -482
- package/dist/mcpsdk@1.25.2.es.js +16796 -0
- package/dist/mcpsdk@1.25.2.js +43 -0
- package/dist/webagent.dev.js +10248 -13732
- package/dist/webagent.es.dev.js +10231 -13715
- package/dist/webagent.es.js +13559 -16396
- package/dist/webagent.js +45 -45
- package/dist/webmcp-full.dev.js +2443 -5645
- package/dist/webmcp-full.es.dev.js +2422 -5624
- package/dist/webmcp-full.es.js +8284 -10901
- package/dist/webmcp-full.js +28 -28
- package/package.json +3 -3
- package/dist/mcpsdk@1.23.1.es.js +0 -15530
- package/dist/mcpsdk@1.23.1.js +0 -43
package/dist/index.umd.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
|
-
(function(Ae,pn){typeof exports=="object"&&typeof module<"u"?pn(exports):typeof define=="function"&&define.amd?define(["exports"],pn):(Ae=typeof globalThis<"u"?globalThis:Ae||self,pn(Ae.WebMCP={}))})(this,(function(Ae){"use strict";function pn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Bo={exports:{}},yc={},Er={},hn={},wc={},bc={},Sc={},$p;function Jo(){return $p||($p=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(g){if(super(),!t.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((y,b)=>`${y}${b}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((y,b)=>(b instanceof r&&(y[b.str]=(y[b.str]||0)+1),y),{})}}t._Code=n,t.nil=new n("");function s(w,...g){const y=[w[0]];let b=0;for(;b<g.length;)i(y,g[b]),y.push(w[++b]);return new n(y)}t._=s;const o=new n("+");function a(w,...g){const y=[p(w[0])];let b=0;for(;b<g.length;)y.push(o),i(y,g[b]),y.push(o,p(w[++b]));return c(y),new n(y)}t.str=a;function i(w,g){g instanceof n?w.push(...g._items):g instanceof r?w.push(g):w.push(h(g))}t.addCodeArg=i;function c(w){let g=1;for(;g<w.length-1;){if(w[g]===o){const y=l(w[g-1],w[g+1]);if(y!==void 0){w.splice(g-1,3,y);continue}w[g++]="+"}g++}}function l(w,g){if(g==='""')return w;if(w==='""')return g;if(typeof w=="string")return g instanceof r||w[w.length-1]!=='"'?void 0:typeof g!="string"?`${w.slice(0,-1)}${g}"`:g[0]==='"'?w.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(w instanceof r))return`"${w}${g.slice(1)}`}function u(w,g){return g.emptyStr()?w:w.emptyStr()?g:a`${w}${g}`}t.strConcat=u;function h(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:p(Array.isArray(w)?w.join(","):w)}function f(w){return new n(p(w))}t.stringify=f;function p(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=p;function m(w){return typeof w=="string"&&t.IDENTIFIER.test(w)?new n(`.${w}`):s`[${w}]`}t.getProperty=m;function v(w){if(typeof w=="string"&&t.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}t.getEsmExportName=v;function _(w){return new n(w.toString())}t.regexpCode=_})(Sc)),Sc}var kc={},Ep;function xp(){return Ep||(Ep=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=Jo();class r extends Error{constructor(l){super(`CodeGen: "code" for ${l} not defined`),this.value=l.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:l,parent:u}={}){this._names={},this._prefixes=l,this._parent=u}toName(l){return l instanceof e.Name?l:this.name(l)}name(l){return new e.Name(this._newName(l))}_newName(l){const u=this._names[l]||this._nameGroup(l);return`${l}${u.index++}`}_nameGroup(l){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(l)||this._prefixes&&!this._prefixes.has(l))throw new Error(`CodeGen: prefix "${l}" is not allowed in this scope`);return this._names[l]={prefix:l,index:0}}}t.Scope=s;class o extends e.Name{constructor(l,u){super(u),this.prefix=l}setValue(l,{property:u,itemIndex:h}){this.value=l,this.scopePath=(0,e._)`.${new e.Name(u)}[${h}]`}}t.ValueScopeName=o;const a=(0,e._)`\n`;class i extends s{constructor(l){super(l),this._values={},this._scope=l.scope,this.opts={...l,_n:l.lines?a:e.nil}}get(){return this._scope}name(l){return new o(l,this._newName(l))}value(l,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(l),{prefix:p}=f,m=(h=u.key)!==null&&h!==void 0?h:u.ref;let v=this._values[p];if(v){const g=v.get(m);if(g)return g}else v=this._values[p]=new Map;v.set(m,f);const _=this._scope[p]||(this._scope[p]=[]),w=_.length;return _[w]=u.ref,f.setValue(u,{property:p,itemIndex:w}),f}getValue(l,u){const h=this._values[l];if(h)return h.get(u)}scopeRefs(l,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${l}${h.scopePath}`})}scopeCode(l=this._values,u,h){return this._reduceValues(l,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},u,h)}_reduceValues(l,u,h={},f){let p=e.nil;for(const m in l){const v=l[m];if(!v)continue;const _=h[m]=h[m]||new Map;v.forEach(w=>{if(_.has(w))return;_.set(w,n.Started);let g=u(w);if(g){const y=this.opts.es5?t.varKinds.var:t.varKinds.const;p=(0,e._)`${p}${y} ${w} = ${g};${this.opts._n}`}else if(g=f?.(w))p=(0,e._)`${p}${g}${this.opts._n}`;else throw new r(w);_.set(w,n.Completed)})}return p}}t.ValueScope=i})(kc)),kc}var Ip;function Ee(){return Ip||(Ip=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Jo(),r=xp();var n=Jo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=xp();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class o{optimizeNodes(){return this}optimizeNames(E,R){return this}}class a extends o{constructor(E,R,$){super(),this.varKind=E,this.name=R,this.rhs=$}render({es5:E,_n:R}){const $=E?r.varKinds.var:this.varKind,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${B};`+R}optimizeNames(E,R){if(E[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,E,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(E,R,$){super(),this.lhs=E,this.rhs=R,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,R){if(!(this.lhs instanceof e.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,E,R),this}get names(){const E=this.lhs instanceof e.Name?{}:{...this.lhs.names};return D(E,this.rhs)}}class c extends i{constructor(E,R,$,B){super(E,$,B),this.op=R}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class l extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class h extends o{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class f extends o{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,R){return this.code=F(this.code,E,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class p extends o{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((R,$)=>R+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let R=E.length;for(;R--;){const $=E[R].optimizeNodes();Array.isArray($)?E.splice(R,1,...$):$?E[R]=$:E.splice(R,1)}return E.length>0?this:void 0}optimizeNames(E,R){const{nodes:$}=this;let B=$.length;for(;B--;){const G=$[B];G.optimizeNames(E,R)||(oe(E,G.names),$.splice(B,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,R)=>z(E,R.names),{})}}class m extends p{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends p{}class _ extends m{}_.kind="else";class w extends m{constructor(E,R){super(R),this.condition=E}render(E){let R=`if(${this.condition})`+super.render(E);return this.else&&(R+="else "+this.else.render(E)),R}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let R=this.else;if(R){const $=R.optimizeNodes();R=this.else=Array.isArray($)?new _($):$}if(R)return E===!1?R instanceof w?R:R.nodes:this.nodes.length?this:new w(fe(E),R instanceof w?[R]:R.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,R){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,R),!!(super.optimizeNames(E,R)||this.else))return this.condition=F(this.condition,E,R),this}get names(){const E=super.names;return D(E,this.condition),this.else&&z(E,this.else.names),E}}w.kind="if";class g extends m{}g.kind="for";class y extends g{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iteration=F(this.iteration,E,R),this}get names(){return z(super.names,this.iteration.names)}}class b extends g{constructor(E,R,$,B){super(),this.varKind=E,this.name=R,this.from=$,this.to=B}render(E){const R=E.es5?r.varKinds.var:this.varKind,{name:$,from:B,to:G}=this;return`for(${R} ${$}=${B}; ${$}<${G}; ${$}++)`+super.render(E)}get names(){const E=D(super.names,this.from);return D(E,this.to)}}class S extends g{constructor(E,R,$,B){super(),this.loop=E,this.varKind=R,this.name=$,this.iterable=B}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iterable=F(this.iterable,E,R),this}get names(){return z(super.names,this.iterable.names)}}class k extends m{constructor(E,R,$){super(),this.name=E,this.args=R,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}k.kind="func";class T extends p{render(E){return"return "+super.render(E)}}T.kind="return";class x extends m{render(E){let R="try"+super.render(E);return this.catch&&(R+=this.catch.render(E)),this.finally&&(R+=this.finally.render(E)),R}optimizeNodes(){var E,R;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(E,R){var $,B;return super.optimizeNames(E,R),($=this.catch)===null||$===void 0||$.optimizeNames(E,R),(B=this.finally)===null||B===void 0||B.optimizeNames(E,R),this}get names(){const E=super.names;return this.catch&&z(E,this.catch.names),this.finally&&z(E,this.finally.names),E}}class P extends m{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}P.kind="catch";class q extends m{render(E){return"finally"+super.render(E)}}q.kind="finally";class N{constructor(E,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.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,R){const $=this._extScope.value(E,R);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,R){return this._extScope.getValue(E,R)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,R,$,B){const G=this._scope.toName(R);return $!==void 0&&B&&(this._constants[G.str]=$),this._leafNode(new a(E,G,$)),G}const(E,R,$){return this._def(r.varKinds.const,E,R,$)}let(E,R,$){return this._def(r.varKinds.let,E,R,$)}var(E,R,$){return this._def(r.varKinds.var,E,R,$)}assign(E,R,$){return this._leafNode(new i(E,R,$))}add(E,R){return this._leafNode(new c(E,t.operators.ADD,R))}code(E){return typeof E=="function"?E():E!==e.nil&&this._leafNode(new f(E)),this}object(...E){const R=["{"];for(const[$,B]of E)R.length>1&&R.push(","),R.push($),($!==B||this.opts.es5)&&(R.push(":"),(0,e.addCodeArg)(R,B));return R.push("}"),new e._Code(R)}if(E,R,$){if(this._blockNode(new w(E)),R&&$)this.code(R).else().code($).endIf();else if(R)this.code(R).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new _)}endIf(){return this._endBlockNode(w,_)}_for(E,R){return this._blockNode(E),R&&this.code(R).endFor(),this}for(E,R){return this._for(new y(E),R)}forRange(E,R,$,B,G=this.opts.es5?r.varKinds.var:r.varKinds.let){const ve=this._scope.toName(E);return this._for(new b(G,ve,R,$),()=>B(ve))}forOf(E,R,$,B=r.varKinds.const){const G=this._scope.toName(E);if(this.opts.es5){const ve=R instanceof e.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,e._)`${ve}.length`,pe=>{this.var(G,(0,e._)`${ve}[${pe}]`),$(G)})}return this._for(new S("of",B,G,R),()=>$(G))}forIn(E,R,$,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,e._)`Object.keys(${R})`,$);const G=this._scope.toName(E);return this._for(new S("in",B,G,R),()=>$(G))}endFor(){return this._endBlockNode(g)}label(E){return this._leafNode(new l(E))}break(E){return this._leafNode(new u(E))}return(E){const R=new T;if(this._blockNode(R),this.code(E),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(E,R,$){if(!R&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new x;if(this._blockNode(B),this.code(E),R){const G=this.name("e");this._currNode=B.catch=new P(G),R(G)}return $&&(this._currNode=B.finally=new q,this.code($)),this._endBlockNode(P,q)}throw(E){return this._leafNode(new h(E))}block(E,R){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(R),this}endBlock(E){const R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-R;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=R,this}func(E,R=e.nil,$,B){return this._blockNode(new k(E,R,$)),B&&this.code(B).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,R){const $=this._currNode;if($ instanceof E||R&&$ instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${E.kind}/${R.kind}`:E.kind}"`)}_elseNode(E){const R=this._currNode;if(!(R instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const R=this._nodes;R[R.length-1]=E}}t.CodeGen=N;function z(j,E){for(const R in E)j[R]=(j[R]||0)+(E[R]||0);return j}function D(j,E){return E instanceof e._CodeOrName?z(j,E.names):j}function F(j,E,R){if(j instanceof e.Name)return $(j);if(!B(j))return j;return new e._Code(j._items.reduce((G,ve)=>(ve instanceof e.Name&&(ve=$(ve)),ve instanceof e._Code?G.push(...ve._items):G.push(ve),G),[]));function $(G){const ve=R[G.str];return ve===void 0||E[G.str]!==1?G:(delete E[G.str],ve)}function B(G){return G instanceof e._Code&&G._items.some(ve=>ve instanceof e.Name&&E[ve.str]===1&&R[ve.str]!==void 0)}}function oe(j,E){for(const R in E)j[R]=(j[R]||0)-(E[R]||0)}function fe(j){return typeof j=="boolean"||typeof j=="number"||j===null?!j:(0,e._)`!${V(j)}`}t.not=fe;const de=A(t.operators.AND);function se(...j){return j.reduce(de)}t.and=se;const _e=A(t.operators.OR);function H(...j){return j.reduce(_e)}t.or=H;function A(j){return(E,R)=>E===e.nil?R:R===e.nil?E:(0,e._)`${V(E)} ${j} ${V(R)}`}function V(j){return j instanceof e.Name?j:(0,e._)`(${j})`}})(bc)),bc}var xe={},Rp;function Le(){if(Rp)return xe;Rp=1,Object.defineProperty(xe,"__esModule",{value:!0}),xe.checkStrictMode=xe.getErrorPath=xe.Type=xe.useFunc=xe.setEvaluated=xe.evaluatedPropsToName=xe.mergeEvaluated=xe.eachItem=xe.unescapeJsonPointer=xe.escapeJsonPointer=xe.escapeFragment=xe.unescapeFragment=xe.schemaRefOrVal=xe.schemaHasRulesButRef=xe.schemaHasRules=xe.checkUnknownRules=xe.alwaysValidSchema=xe.toHash=void 0;const t=Ee(),e=Jo();function r(S){const k={};for(const T of S)k[T]=!0;return k}xe.toHash=r;function n(S,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(s(S,k),!o(k,S.self.RULES.all))}xe.alwaysValidSchema=n;function s(S,k=S.schema){const{opts:T,self:x}=S;if(!T.strictSchema||typeof k=="boolean")return;const P=x.RULES.keywords;for(const q in k)P[q]||b(S,`unknown keyword: "${q}"`)}xe.checkUnknownRules=s;function o(S,k){if(typeof S=="boolean")return!S;for(const T in S)if(k[T])return!0;return!1}xe.schemaHasRules=o;function a(S,k){if(typeof S=="boolean")return!S;for(const T in S)if(T!=="$ref"&&k.all[T])return!0;return!1}xe.schemaHasRulesButRef=a;function i({topSchemaRef:S,schemaPath:k},T,x,P){if(!P){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,t._)`${T}`}return(0,t._)`${S}${k}${(0,t.getProperty)(x)}`}xe.schemaRefOrVal=i;function c(S){return h(decodeURIComponent(S))}xe.unescapeFragment=c;function l(S){return encodeURIComponent(u(S))}xe.escapeFragment=l;function u(S){return typeof S=="number"?`${S}`:S.replace(/~/g,"~0").replace(/\//g,"~1")}xe.escapeJsonPointer=u;function h(S){return S.replace(/~1/g,"/").replace(/~0/g,"~")}xe.unescapeJsonPointer=h;function f(S,k){if(Array.isArray(S))for(const T of S)k(T);else k(S)}xe.eachItem=f;function p({mergeNames:S,mergeToName:k,mergeValues:T,resultToName:x}){return(P,q,N,z)=>{const D=N===void 0?q:N instanceof t.Name?(q instanceof t.Name?S(P,q,N):k(P,q,N),N):q instanceof t.Name?(k(P,N,q),q):T(q,N);return z===t.Name&&!(D instanceof t.Name)?x(P,D):D}}xe.mergeEvaluated={props:p({mergeNames:(S,k,T)=>S.if((0,t._)`${T} !== true && ${k} !== undefined`,()=>{S.if((0,t._)`${k} === true`,()=>S.assign(T,!0),()=>S.assign(T,(0,t._)`${T} || {}`).code((0,t._)`Object.assign(${T}, ${k})`))}),mergeToName:(S,k,T)=>S.if((0,t._)`${T} !== true`,()=>{k===!0?S.assign(T,!0):(S.assign(T,(0,t._)`${T} || {}`),v(S,T,k))}),mergeValues:(S,k)=>S===!0?!0:{...S,...k},resultToName:m}),items:p({mergeNames:(S,k,T)=>S.if((0,t._)`${T} !== true && ${k} !== undefined`,()=>S.assign(T,(0,t._)`${k} === true ? true : ${T} > ${k} ? ${T} : ${k}`)),mergeToName:(S,k,T)=>S.if((0,t._)`${T} !== true`,()=>S.assign(T,k===!0?!0:(0,t._)`${T} > ${k} ? ${T} : ${k}`)),mergeValues:(S,k)=>S===!0?!0:Math.max(S,k),resultToName:(S,k)=>S.var("items",k)})};function m(S,k){if(k===!0)return S.var("props",!0);const T=S.var("props",(0,t._)`{}`);return k!==void 0&&v(S,T,k),T}xe.evaluatedPropsToName=m;function v(S,k,T){Object.keys(T).forEach(x=>S.assign((0,t._)`${k}${(0,t.getProperty)(x)}`,!0))}xe.setEvaluated=v;const _={};function w(S,k){return S.scopeValue("func",{ref:k,code:_[k.code]||(_[k.code]=new e._Code(k.code))})}xe.useFunc=w;var g;(function(S){S[S.Num=0]="Num",S[S.Str=1]="Str"})(g||(xe.Type=g={}));function y(S,k,T){if(S instanceof t.Name){const x=k===g.Num;return T?x?(0,t._)`"[" + ${S} + "]"`:(0,t._)`"['" + ${S} + "']"`:x?(0,t._)`"/" + ${S}`:(0,t._)`"/" + ${S}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,t.getProperty)(S).toString():"/"+u(S)}xe.getErrorPath=y;function b(S,k,T=S.opts.strictSchema){if(T){if(k=`strict mode: ${k}`,T===!0)throw new Error(k);S.self.logger.warn(k)}}return xe.checkStrictMode=b,xe}var Wo={},Pp;function Fr(){if(Pp)return Wo;Pp=1,Object.defineProperty(Wo,"__esModule",{value:!0});const t=Ee(),e={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};return Wo.default=e,Wo}var Op;function Go(){return Op||(Op=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=Ee(),r=Le(),n=Fr();t.keywordError={message:({keyword:_})=>(0,e.str)`must pass "${_}" keyword validation`},t.keyword$DataError={message:({keyword:_,schemaType:w})=>w?(0,e.str)`"${_}" keyword must be ${w} ($data)`:(0,e.str)`"${_}" keyword is invalid ($data)`};function s(_,w=t.keywordError,g,y){const{it:b}=_,{gen:S,compositeRule:k,allErrors:T}=b,x=h(_,w,g);y??(k||T)?c(S,x):l(b,(0,e._)`[${x}]`)}t.reportError=s;function o(_,w=t.keywordError,g){const{it:y}=_,{gen:b,compositeRule:S,allErrors:k}=y,T=h(_,w,g);c(b,T),S||k||l(y,n.default.vErrors)}t.reportExtraError=o;function a(_,w){_.assign(n.default.errors,w),_.if((0,e._)`${n.default.vErrors} !== null`,()=>_.if(w,()=>_.assign((0,e._)`${n.default.vErrors}.length`,w),()=>_.assign(n.default.vErrors,null)))}t.resetErrorsCount=a;function i({gen:_,keyword:w,schemaValue:g,data:y,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");const k=_.name("err");_.forRange("i",b,n.default.errors,T=>{_.const(k,(0,e._)`${n.default.vErrors}[${T}]`),_.if((0,e._)`${k}.instancePath === undefined`,()=>_.assign((0,e._)`${k}.instancePath`,(0,e.strConcat)(n.default.instancePath,S.errorPath))),_.assign((0,e._)`${k}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${w}`),S.opts.verbose&&(_.assign((0,e._)`${k}.schema`,g),_.assign((0,e._)`${k}.data`,y))})}t.extendErrors=i;function c(_,w){const g=_.const("err",w);_.if((0,e._)`${n.default.vErrors} === null`,()=>_.assign(n.default.vErrors,(0,e._)`[${g}]`),(0,e._)`${n.default.vErrors}.push(${g})`),_.code((0,e._)`${n.default.errors}++`)}function l(_,w){const{gen:g,validateName:y,schemaEnv:b}=_;b.$async?g.throw((0,e._)`new ${_.ValidationError}(${w})`):(g.assign((0,e._)`${y}.errors`,w),g.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function h(_,w,g){const{createErrors:y}=_.it;return y===!1?(0,e._)`{}`:f(_,w,g)}function f(_,w,g={}){const{gen:y,it:b}=_,S=[p(b,g),m(_,g)];return v(_,w,S),y.object(...S)}function p({errorPath:_},{instancePath:w}){const g=w?(0,e.str)`${_}${(0,r.getErrorPath)(w,r.Type.Str)}`:_;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,g)]}function m({keyword:_,it:{errSchemaPath:w}},{schemaPath:g,parentSchema:y}){let b=y?w:(0,e.str)`${w}/${_}`;return g&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(g,r.Type.Str)}`),[u.schemaPath,b]}function v(_,{params:w,message:g},y){const{keyword:b,data:S,schemaValue:k,it:T}=_,{opts:x,propertyName:P,topSchemaRef:q,schemaPath:N}=T;y.push([u.keyword,b],[u.params,typeof w=="function"?w(_):w||(0,e._)`{}`]),x.messages&&y.push([u.message,typeof g=="function"?g(_):g]),x.verbose&&y.push([u.schema,k],[u.parentSchema,(0,e._)`${q}${N}`],[n.default.data,S]),P&&y.push([u.propertyName,P])}})(wc)),wc}var Ap;function ww(){if(Ap)return hn;Ap=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.boolOrEmptySchema=hn.topBoolOrEmptySchema=void 0;const t=Go(),e=Ee(),r=Fr(),n={message:"boolean schema is false"};function s(i){const{gen:c,schema:l,validateName:u}=i;l===!1?a(i,!1):typeof l=="object"&&l.$async===!0?c.return(r.default.data):(c.assign((0,e._)`${u}.errors`,null),c.return(!0))}hn.topBoolOrEmptySchema=s;function o(i,c){const{gen:l,schema:u}=i;u===!1?(l.var(c,!1),a(i)):l.var(c,!0)}hn.boolOrEmptySchema=o;function a(i,c){const{gen:l,data:u}=i,h={gen:l,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,t.reportError)(h,n,void 0,c)}return hn}var ot={},fn={},Mp;function Np(){if(Mp)return fn;Mp=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.getRules=fn.isJSONType=void 0;const t=["string","number","integer","boolean","null","object","array"],e=new Set(t);function r(s){return typeof s=="string"&&e.has(s)}fn.isJSONType=r;function n(){const s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}return fn.getRules=n,fn}var xr={},Lp;function qp(){if(Lp)return xr;Lp=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.shouldUseRule=xr.shouldUseGroup=xr.schemaHasRulesForType=void 0;function t({schema:n,self:s},o){const a=s.RULES.types[o];return a&&a!==!0&&e(n,a)}xr.schemaHasRulesForType=t;function e(n,s){return s.rules.some(o=>r(n,o))}xr.shouldUseGroup=e;function r(n,s){var o;return n[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>n[a]!==void 0))}return xr.shouldUseRule=r,xr}var jp;function Ko(){if(jp)return ot;jp=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.reportTypeError=ot.checkDataTypes=ot.checkDataType=ot.coerceAndCheckDataType=ot.getJSONTypes=ot.getSchemaTypes=ot.DataType=void 0;const t=Np(),e=qp(),r=Go(),n=Ee(),s=Le();var o;(function(g){g[g.Correct=0]="Correct",g[g.Wrong=1]="Wrong"})(o||(ot.DataType=o={}));function a(g){const y=i(g.type);if(y.includes("null")){if(g.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!y.length&&g.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');g.nullable===!0&&y.push("null")}return y}ot.getSchemaTypes=a;function i(g){const y=Array.isArray(g)?g:g?[g]:[];if(y.every(t.isJSONType))return y;throw new Error("type must be JSONType or JSONType[]: "+y.join(","))}ot.getJSONTypes=i;function c(g,y){const{gen:b,data:S,opts:k}=g,T=u(y,k.coerceTypes),x=y.length>0&&!(T.length===0&&y.length===1&&(0,e.schemaHasRulesForType)(g,y[0]));if(x){const P=m(y,S,k.strictNumbers,o.Wrong);b.if(P,()=>{T.length?h(g,y,T):_(g)})}return x}ot.coerceAndCheckDataType=c;const l=new Set(["string","number","integer","boolean","null"]);function u(g,y){return y?g.filter(b=>l.has(b)||y==="array"&&b==="array"):[]}function h(g,y,b){const{gen:S,data:k,opts:T}=g,x=S.let("dataType",(0,n._)`typeof ${k}`),P=S.let("coerced",(0,n._)`undefined`);T.coerceTypes==="array"&&S.if((0,n._)`${x} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>S.assign(k,(0,n._)`${k}[0]`).assign(x,(0,n._)`typeof ${k}`).if(m(y,k,T.strictNumbers),()=>S.assign(P,k))),S.if((0,n._)`${P} !== undefined`);for(const N of b)(l.has(N)||N==="array"&&T.coerceTypes==="array")&&q(N);S.else(),_(g),S.endIf(),S.if((0,n._)`${P} !== undefined`,()=>{S.assign(k,P),f(g,P)});function q(N){switch(N){case"string":S.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(P,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(P,(0,n._)`""`);return;case"number":S.elseIf((0,n._)`${x} == "boolean" || ${k} === null
|
|
3
|
-
|| (${x} == "string" && ${
|
|
4
|
-
|| (${x} === "string" && ${
|
|
5
|
-
|| ${x} === "boolean" || ${k} === null`).assign(P,(0,n._)`[${k}]`)}}}function f({gen:g,parentData:y,parentDataProperty:b},S){g.if((0,n._)`${y} !== undefined`,()=>g.assign((0,n._)`${y}[${b}]`,S))}function p(g,y,b,S=o.Correct){const k=S===o.Correct?n.operators.EQ:n.operators.NEQ;let T;switch(g){case"null":return(0,n._)`${y} ${k} null`;case"array":T=(0,n._)`Array.isArray(${y})`;break;case"object":T=(0,n._)`${y} && typeof ${y} == "object" && !Array.isArray(${y})`;break;case"integer":T=x((0,n._)`!(${y} % 1) && !isNaN(${y})`);break;case"number":T=x();break;default:return(0,n._)`typeof ${y} ${k} ${g}`}return S===o.Correct?T:(0,n.not)(T);function x(P=n.nil){return(0,n.and)((0,n._)`typeof ${y} == "number"`,P,b?(0,n._)`isFinite(${y})`:n.nil)}}ot.checkDataType=p;function m(g,y,b,S){if(g.length===1)return p(g[0],y,b,S);let k;const T=(0,s.toHash)(g);if(T.array&&T.object){const x=(0,n._)`typeof ${y} != "object"`;k=T.null?x:(0,n._)`!${y} || ${x}`,delete T.null,delete T.array,delete T.object}else k=n.nil;T.number&&delete T.integer;for(const x in T)k=(0,n.and)(k,p(x,y,b,S));return k}ot.checkDataTypes=m;const v={message:({schema:g})=>`must be ${g}`,params:({schema:g,schemaValue:y})=>typeof g=="string"?(0,n._)`{type: ${g}}`:(0,n._)`{type: ${y}}`};function _(g){const y=w(g);(0,r.reportError)(y,v)}ot.reportTypeError=_;function w(g){const{gen:y,data:b,schema:S}=g,k=(0,s.schemaRefOrVal)(g,S,"type");return{gen:y,keyword:"type",data:b,schema:S.type,schemaCode:k,schemaValue:k,parentSchema:S,params:{},it:g}}return ot}var Ts={},Up;function bw(){if(Up)return Ts;Up=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.assignDefaults=void 0;const t=Ee(),e=Le();function r(s,o){const{properties:a,items:i}=s.schema;if(o==="object"&&a)for(const c in a)n(s,c,a[c].default);else o==="array"&&Array.isArray(i)&&i.forEach((c,l)=>n(s,l,c.default))}Ts.assignDefaults=r;function n(s,o,a){const{gen:i,compositeRule:c,data:l,opts:u}=s;if(a===void 0)return;const h=(0,t._)`${l}${(0,t.getProperty)(o)}`;if(c){(0,e.checkStrictMode)(s,`default is ignored for: ${h}`);return}let f=(0,t._)`${h} === undefined`;u.useDefaults==="empty"&&(f=(0,t._)`${f} || ${h} === null || ${h} === ""`),i.if(f,(0,t._)`${h} = ${(0,t.stringify)(a)}`)}return Ts}var Gt={},ze={},zp;function Kt(){if(zp)return ze;zp=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.validateUnion=ze.validateArray=ze.usePattern=ze.callValidateCode=ze.schemaProperties=ze.allSchemaProperties=ze.noPropertyInData=ze.propertyInData=ze.isOwnProperty=ze.hasPropFunc=ze.reportMissingProp=ze.checkMissingProp=ze.checkReportMissingProp=void 0;const t=Ee(),e=Le(),r=Fr(),n=Le();function s(g,y){const{gen:b,data:S,it:k}=g;b.if(u(b,S,y,k.opts.ownProperties),()=>{g.setParams({missingProperty:(0,t._)`${y}`},!0),g.error()})}ze.checkReportMissingProp=s;function o({gen:g,data:y,it:{opts:b}},S,k){return(0,t.or)(...S.map(T=>(0,t.and)(u(g,y,T,b.ownProperties),(0,t._)`${k} = ${T}`)))}ze.checkMissingProp=o;function a(g,y){g.setParams({missingProperty:y},!0),g.error()}ze.reportMissingProp=a;function i(g){return g.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}ze.hasPropFunc=i;function c(g,y,b){return(0,t._)`${i(g)}.call(${y}, ${b})`}ze.isOwnProperty=c;function l(g,y,b,S){const k=(0,t._)`${y}${(0,t.getProperty)(b)} !== undefined`;return S?(0,t._)`${k} && ${c(g,y,b)}`:k}ze.propertyInData=l;function u(g,y,b,S){const k=(0,t._)`${y}${(0,t.getProperty)(b)} === undefined`;return S?(0,t.or)(k,(0,t.not)(c(g,y,b))):k}ze.noPropertyInData=u;function h(g){return g?Object.keys(g).filter(y=>y!=="__proto__"):[]}ze.allSchemaProperties=h;function f(g,y){return h(y).filter(b=>!(0,e.alwaysValidSchema)(g,y[b]))}ze.schemaProperties=f;function p({schemaCode:g,data:y,it:{gen:b,topSchemaRef:S,schemaPath:k,errorPath:T},it:x},P,q,N){const z=N?(0,t._)`${g}, ${y}, ${S}${k}`:y,D=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,T)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&D.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const F=(0,t._)`${z}, ${b.object(...D)}`;return q!==t.nil?(0,t._)`${P}.call(${q}, ${F})`:(0,t._)`${P}(${F})`}ze.callValidateCode=p;const m=(0,t._)`new RegExp`;function v({gen:g,it:{opts:y}},b){const S=y.unicodeRegExp?"u":"",{regExp:k}=y.code,T=k(b,S);return g.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,t._)`${k.code==="new RegExp"?m:(0,n.useFunc)(g,k)}(${b}, ${S})`})}ze.usePattern=v;function _(g){const{gen:y,data:b,keyword:S,it:k}=g,T=y.name("valid");if(k.allErrors){const P=y.let("valid",!0);return x(()=>y.assign(P,!1)),P}return y.var(T,!0),x(()=>y.break()),T;function x(P){const q=y.const("len",(0,t._)`${b}.length`);y.forRange("i",0,q,N=>{g.subschema({keyword:S,dataProp:N,dataPropType:e.Type.Num},T),y.if((0,t.not)(T),P)})}}ze.validateArray=_;function w(g){const{gen:y,schema:b,keyword:S,it:k}=g;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(q=>(0,e.alwaysValidSchema)(k,q))&&!k.opts.unevaluated)return;const x=y.let("valid",!1),P=y.name("_valid");y.block(()=>b.forEach((q,N)=>{const z=g.subschema({keyword:S,schemaProp:N,compositeRule:!0},P);y.assign(x,(0,t._)`${x} || ${P}`),g.mergeValidEvaluated(z,P)||y.if((0,t.not)(x))})),g.result(x,()=>g.reset(),()=>g.error(!0))}return ze.validateUnion=w,ze}var Dp;function Sw(){if(Dp)return Gt;Dp=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.validateKeywordUsage=Gt.validSchemaType=Gt.funcKeywordCode=Gt.macroKeywordCode=void 0;const t=Ee(),e=Fr(),r=Kt(),n=Go();function s(f,p){const{gen:m,keyword:v,schema:_,parentSchema:w,it:g}=f,y=p.macro.call(g.self,_,w,g),b=l(m,v,y);g.opts.validateSchema!==!1&&g.self.validateSchema(y,!0);const S=m.name("valid");f.subschema({schema:y,schemaPath:t.nil,errSchemaPath:`${g.errSchemaPath}/${v}`,topSchemaRef:b,compositeRule:!0},S),f.pass(S,()=>f.error(!0))}Gt.macroKeywordCode=s;function o(f,p){var m;const{gen:v,keyword:_,schema:w,parentSchema:g,$data:y,it:b}=f;c(b,p);const S=!y&&p.compile?p.compile.call(b.self,w,g,b):p.validate,k=l(v,_,S),T=v.let("valid");f.block$data(T,x),f.ok((m=p.valid)!==null&&m!==void 0?m:T);function x(){if(p.errors===!1)N(),p.modifying&&a(f),z(()=>f.error());else{const D=p.async?P():q();p.modifying&&a(f),z(()=>i(f,D))}}function P(){const D=v.let("ruleErrs",null);return v.try(()=>N((0,t._)`await `),F=>v.assign(T,!1).if((0,t._)`${F} instanceof ${b.ValidationError}`,()=>v.assign(D,(0,t._)`${F}.errors`),()=>v.throw(F))),D}function q(){const D=(0,t._)`${k}.errors`;return v.assign(D,null),N(t.nil),D}function N(D=p.async?(0,t._)`await `:t.nil){const F=b.opts.passContext?e.default.this:e.default.self,oe=!("compile"in p&&!y||p.schema===!1);v.assign(T,(0,t._)`${D}${(0,r.callValidateCode)(f,k,F,oe)}`,p.modifying)}function z(D){var F;v.if((0,t.not)((F=p.valid)!==null&&F!==void 0?F:T),D)}}Gt.funcKeywordCode=o;function a(f){const{gen:p,data:m,it:v}=f;p.if(v.parentData,()=>p.assign(m,(0,t._)`${v.parentData}[${v.parentDataProperty}]`))}function i(f,p){const{gen:m}=f;m.if((0,t._)`Array.isArray(${p})`,()=>{m.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${p} : ${e.default.vErrors}.concat(${p})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(f)},()=>f.error())}function c({schemaEnv:f},p){if(p.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,p,m){if(m===void 0)throw new Error(`keyword "${p}" failed to compile`);return f.scopeValue("keyword",typeof m=="function"?{ref:m}:{ref:m,code:(0,t.stringify)(m)})}function u(f,p,m=!1){return!p.length||p.some(v=>v==="array"?Array.isArray(f):v==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==v||m&&typeof f>"u")}Gt.validSchemaType=u;function h({schema:f,opts:p,self:m,errSchemaPath:v},_,w){if(Array.isArray(_.keyword)?!_.keyword.includes(w):_.keyword!==w)throw new Error("ajv implementation error");const g=_.dependencies;if(g?.some(y=>!Object.prototype.hasOwnProperty.call(f,y)))throw new Error(`parent schema must have dependencies of ${w}: ${g.join(",")}`);if(_.validateSchema&&!_.validateSchema(f[w])){const b=`keyword "${w}" value is invalid at path "${v}": `+m.errorsText(_.validateSchema.errors);if(p.validateSchema==="log")m.logger.error(b);else throw new Error(b)}}return Gt.validateKeywordUsage=h,Gt}var Ir={},Zp;function kw(){if(Zp)return Ir;Zp=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.extendSubschemaMode=Ir.extendSubschemaData=Ir.getSubschema=void 0;const t=Ee(),e=Le();function r(o,{keyword:a,schemaProp:i,schema:c,schemaPath:l,errSchemaPath:u,topSchemaRef:h}){if(a!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const f=o.schema[a];return i===void 0?{schema:f,schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:f[i],schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}${(0,t.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,e.escapeFragment)(i)}`}}if(c!==void 0){if(l===void 0||u===void 0||h===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:l,topSchemaRef:h,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Ir.getSubschema=r;function n(o,a,{dataProp:i,dataPropType:c,data:l,dataTypes:u,propertyName:h}){if(l!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:f}=a;if(i!==void 0){const{errorPath:m,dataPathArr:v,opts:_}=a,w=f.let("data",(0,t._)`${a.data}${(0,t.getProperty)(i)}`,!0);p(w),o.errorPath=(0,t.str)`${m}${(0,e.getErrorPath)(i,c,_.jsPropertySyntax)}`,o.parentDataProperty=(0,t._)`${i}`,o.dataPathArr=[...v,o.parentDataProperty]}if(l!==void 0){const m=l instanceof t.Name?l:f.let("data",l,!0);p(m),h!==void 0&&(o.propertyName=h)}u&&(o.dataTypes=u);function p(m){o.data=m,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,m]}}Ir.extendSubschemaData=n;function s(o,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:c,createErrors:l,allErrors:u}){c!==void 0&&(o.compositeRule=c),l!==void 0&&(o.createErrors=l),u!==void 0&&(o.allErrors=u),o.jtdDiscriminator=a,o.jtdMetadata=i}return Ir.extendSubschemaMode=s,Ir}var _t={},Cc,Vp;function Fp(){return Vp||(Vp=1,Cc=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var a=o[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}),Cc}var Tc={exports:{}},Hp;function Cw(){if(Hp)return Tc.exports;Hp=1;var t=Tc.exports=function(n,s,o){typeof s=="function"&&(o=s,s={}),o=s.cb||o;var a=typeof o=="function"?o:o.pre||function(){},i=o.post||function(){};e(s,a,i,n,"",n)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function e(n,s,o,a,i,c,l,u,h,f){if(a&&typeof a=="object"&&!Array.isArray(a)){s(a,i,c,l,u,h,f);for(var p in a){var m=a[p];if(Array.isArray(m)){if(p in t.arrayKeywords)for(var v=0;v<m.length;v++)e(n,s,o,m[v],i+"/"+p+"/"+v,c,i,p,a,v)}else if(p in t.propsKeywords){if(m&&typeof m=="object")for(var _ in m)e(n,s,o,m[_],i+"/"+p+"/"+r(_),c,i,p,a,_)}else(p in t.keywords||n.allKeys&&!(p in t.skipKeywords))&&e(n,s,o,m,i+"/"+p,c,i,p,a)}o(a,i,c,l,u,h,f)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Tc.exports}var Bp;function Yo(){if(Bp)return _t;Bp=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.getSchemaRefs=_t.resolveUrl=_t.normalizeId=_t._getFullPath=_t.getFullPath=_t.inlineRef=void 0;const t=Le(),e=Fp(),r=Cw(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(v,_=!0){return typeof v=="boolean"?!0:_===!0?!a(v):_?i(v)<=_:!1}_t.inlineRef=s;const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const _ in v){if(o.has(_))return!0;const w=v[_];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let _=0;for(const w in v){if(w==="$ref")return 1/0;if(_++,!n.has(w)&&(typeof v[w]=="object"&&(0,t.eachItem)(v[w],g=>_+=i(g)),_===1/0))return 1/0}return _}function c(v,_="",w){w!==!1&&(_=h(_));const g=v.parse(_);return l(v,g)}_t.getFullPath=c;function l(v,_){return v.serialize(_).split("#")[0]+"#"}_t._getFullPath=l;const u=/#\/?$/;function h(v){return v?v.replace(u,""):""}_t.normalizeId=h;function f(v,_,w){return w=h(w),v.resolve(_,w)}_t.resolveUrl=f;const p=/^[a-z_][-a-z0-9._]*$/i;function m(v,_){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:g}=this.opts,y=h(v[w]||_),b={"":y},S=c(g,y,!1),k={},T=new Set;return r(v,{allKeys:!0},(q,N,z,D)=>{if(D===void 0)return;const F=S+N;let oe=b[D];typeof q[w]=="string"&&(oe=fe.call(this,q[w])),de.call(this,q.$anchor),de.call(this,q.$dynamicAnchor),b[N]=oe;function fe(se){const _e=this.opts.uriResolver.resolve;if(se=h(oe?_e(oe,se):se),T.has(se))throw P(se);T.add(se);let H=this.refs[se];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(q,H.schema,se):se!==h(F)&&(se[0]==="#"?(x(q,k[se],se),k[se]=q):this.refs[se]=F),se}function de(se){if(typeof se=="string"){if(!p.test(se))throw new Error(`invalid anchor "${se}"`);fe.call(this,`#${se}`)}}}),k;function x(q,N,z){if(N!==void 0&&!e(q,N))throw P(z)}function P(q){return new Error(`reference "${q}" resolves to more than one schema`)}}return _t.getSchemaRefs=m,_t}var Jp;function Qo(){if(Jp)return Er;Jp=1,Object.defineProperty(Er,"__esModule",{value:!0}),Er.getData=Er.KeywordCxt=Er.validateFunctionCode=void 0;const t=ww(),e=Ko(),r=qp(),n=Ko(),s=bw(),o=Sw(),a=kw(),i=Ee(),c=Fr(),l=Yo(),u=Le(),h=Go();function f(L){if(S(L)&&(T(L),b(L))){_(L);return}p(L,()=>(0,t.topBoolOrEmptySchema)(L))}Er.validateFunctionCode=f;function p({gen:L,validateName:Z,schema:W,schemaEnv:K,opts:X},ue){X.code.es5?L.func(Z,(0,i._)`${c.default.data}, ${c.default.valCxt}`,K.$async,()=>{L.code((0,i._)`"use strict"; ${g(W,X)}`),v(L,X),L.code(ue)}):L.func(Z,(0,i._)`${c.default.data}, ${m(X)}`,K.$async,()=>L.code(g(W,X)).code(ue))}function m(L){return(0,i._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${L.dynamicRef?(0,i._)`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}function v(L,Z){L.if(c.default.valCxt,()=>{L.var(c.default.instancePath,(0,i._)`${c.default.valCxt}.${c.default.instancePath}`),L.var(c.default.parentData,(0,i._)`${c.default.valCxt}.${c.default.parentData}`),L.var(c.default.parentDataProperty,(0,i._)`${c.default.valCxt}.${c.default.parentDataProperty}`),L.var(c.default.rootData,(0,i._)`${c.default.valCxt}.${c.default.rootData}`),Z.dynamicRef&&L.var(c.default.dynamicAnchors,(0,i._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{L.var(c.default.instancePath,(0,i._)`""`),L.var(c.default.parentData,(0,i._)`undefined`),L.var(c.default.parentDataProperty,(0,i._)`undefined`),L.var(c.default.rootData,c.default.data),Z.dynamicRef&&L.var(c.default.dynamicAnchors,(0,i._)`{}`)})}function _(L){const{schema:Z,opts:W,gen:K}=L;p(L,()=>{W.$comment&&Z.$comment&&D(L),q(L),K.let(c.default.vErrors,null),K.let(c.default.errors,0),W.unevaluated&&w(L),x(L),F(L)})}function w(L){const{gen:Z,validateName:W}=L;L.evaluated=Z.const("evaluated",(0,i._)`${W}.evaluated`),Z.if((0,i._)`${L.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${L.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${L.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${L.evaluated}.items`,(0,i._)`undefined`))}function g(L,Z){const W=typeof L=="object"&&L[Z.schemaId];return W&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${W} */`:i.nil}function y(L,Z){if(S(L)&&(T(L),b(L))){k(L,Z);return}(0,t.boolOrEmptySchema)(L,Z)}function b({schema:L,self:Z}){if(typeof L=="boolean")return!L;for(const W in L)if(Z.RULES.all[W])return!0;return!1}function S(L){return typeof L.schema!="boolean"}function k(L,Z){const{schema:W,gen:K,opts:X}=L;X.$comment&&W.$comment&&D(L),N(L),z(L);const ue=K.const("_errs",c.default.errors);x(L,ue),K.var(Z,(0,i._)`${ue} === ${c.default.errors}`)}function T(L){(0,u.checkUnknownRules)(L),P(L)}function x(L,Z){if(L.opts.jtd)return fe(L,[],!1,Z);const W=(0,e.getSchemaTypes)(L.schema),K=(0,e.coerceAndCheckDataType)(L,W);fe(L,W,!K,Z)}function P(L){const{schema:Z,errSchemaPath:W,opts:K,self:X}=L;Z.$ref&&K.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,X.RULES)&&X.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function q(L){const{schema:Z,opts:W}=L;Z.default!==void 0&&W.useDefaults&&W.strictSchema&&(0,u.checkStrictMode)(L,"default is ignored in the schema root")}function N(L){const Z=L.schema[L.opts.schemaId];Z&&(L.baseId=(0,l.resolveUrl)(L.opts.uriResolver,L.baseId,Z))}function z(L){if(L.schema.$async&&!L.schemaEnv.$async)throw new Error("async schema in sync schema")}function D({gen:L,schemaEnv:Z,schema:W,errSchemaPath:K,opts:X}){const ue=W.$comment;if(X.$comment===!0)L.code((0,i._)`${c.default.self}.logger.log(${ue})`);else if(typeof X.$comment=="function"){const me=(0,i.str)`${K}/$comment`,Je=L.scopeValue("root",{ref:Z.root});L.code((0,i._)`${c.default.self}.opts.$comment(${ue}, ${me}, ${Je}.schema)`)}}function F(L){const{gen:Z,schemaEnv:W,validateName:K,ValidationError:X,opts:ue}=L;W.$async?Z.if((0,i._)`${c.default.errors} === 0`,()=>Z.return(c.default.data),()=>Z.throw((0,i._)`new ${X}(${c.default.vErrors})`)):(Z.assign((0,i._)`${K}.errors`,c.default.vErrors),ue.unevaluated&&oe(L),Z.return((0,i._)`${c.default.errors} === 0`))}function oe({gen:L,evaluated:Z,props:W,items:K}){W instanceof i.Name&&L.assign((0,i._)`${Z}.props`,W),K instanceof i.Name&&L.assign((0,i._)`${Z}.items`,K)}function fe(L,Z,W,K){const{gen:X,schema:ue,data:me,allErrors:Je,opts:Ge,self:te}=L,{RULES:ke}=te;if(ue.$ref&&(Ge.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ue,ke))){X.block(()=>B(L,"$ref",ke.all.$ref.definition));return}Ge.jtd||se(L,Z),X.block(()=>{for(const Ie of ke.rules)Ct(Ie);Ct(ke.post)});function Ct(Ie){(0,r.shouldUseGroup)(ue,Ie)&&(Ie.type?(X.if((0,n.checkDataType)(Ie.type,me,Ge.strictNumbers)),de(L,Ie),Z.length===1&&Z[0]===Ie.type&&W&&(X.else(),(0,n.reportTypeError)(L)),X.endIf()):de(L,Ie),Je||X.if((0,i._)`${c.default.errors} === ${K||0}`))}}function de(L,Z){const{gen:W,schema:K,opts:{useDefaults:X}}=L;X&&(0,s.assignDefaults)(L,Z.type),W.block(()=>{for(const ue of Z.rules)(0,r.shouldUseRule)(K,ue)&&B(L,ue.keyword,ue.definition,Z.type)})}function se(L,Z){L.schemaEnv.meta||!L.opts.strictTypes||(_e(L,Z),L.opts.allowUnionTypes||H(L,Z),A(L,L.dataTypes))}function _e(L,Z){if(Z.length){if(!L.dataTypes.length){L.dataTypes=Z;return}Z.forEach(W=>{j(L.dataTypes,W)||R(L,`type "${W}" not allowed by context "${L.dataTypes.join(",")}"`)}),E(L,Z)}}function H(L,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&R(L,"use allowUnionTypes to allow union type keyword")}function A(L,Z){const W=L.self.RULES.all;for(const K in W){const X=W[K];if(typeof X=="object"&&(0,r.shouldUseRule)(L.schema,X)){const{type:ue}=X.definition;ue.length&&!ue.some(me=>V(Z,me))&&R(L,`missing type "${ue.join(",")}" for keyword "${K}"`)}}}function V(L,Z){return L.includes(Z)||Z==="number"&&L.includes("integer")}function j(L,Z){return L.includes(Z)||Z==="integer"&&L.includes("number")}function E(L,Z){const W=[];for(const K of L.dataTypes)j(Z,K)?W.push(K):Z.includes("integer")&&K==="number"&&W.push("integer");L.dataTypes=W}function R(L,Z){const W=L.schemaEnv.baseId+L.errSchemaPath;Z+=` at "${W}" (strictTypes)`,(0,u.checkStrictMode)(L,Z,L.opts.strictTypes)}class ${constructor(Z,W,K){if((0,o.validateKeywordUsage)(Z,W,K),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=K,this.data=Z.data,this.schema=Z.schema[K],this.$data=W.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,K,this.$data),this.schemaType=W.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=W,this.$data)this.schemaCode=Z.gen.const("vSchema",pe(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,W.schemaType,W.allowUndefined))throw new Error(`${K} value must be ${JSON.stringify(W.schemaType)}`);("code"in W?W.trackErrors:W.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",c.default.errors))}result(Z,W,K){this.failResult((0,i.not)(Z),W,K)}failResult(Z,W,K){this.gen.if(Z),K?K():this.error(),W?(this.gen.else(),W(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,W){this.failResult((0,i.not)(Z),void 0,W)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:W}=this;this.fail((0,i._)`${W} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,W,K){if(W){this.setParams(W),this._error(Z,K),this.setParams({});return}this._error(Z,K)}_error(Z,W){(Z?h.reportExtraError:h.reportError)(this,this.def.error,W)}$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(Z){this.allErrors||this.gen.if(Z)}setParams(Z,W){W?Object.assign(this.params,Z):this.params=Z}block$data(Z,W,K=i.nil){this.gen.block(()=>{this.check$data(Z,K),W()})}check$data(Z=i.nil,W=i.nil){if(!this.$data)return;const{gen:K,schemaCode:X,schemaType:ue,def:me}=this;K.if((0,i.or)((0,i._)`${X} === undefined`,W)),Z!==i.nil&&K.assign(Z,!0),(ue.length||me.validateSchema)&&(K.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&K.assign(Z,!1)),K.else()}invalid$data(){const{gen:Z,schemaCode:W,schemaType:K,def:X,it:ue}=this;return(0,i.or)(me(),Je());function me(){if(K.length){if(!(W instanceof i.Name))throw new Error("ajv implementation error");const Ge=Array.isArray(K)?K:[K];return(0,i._)`${(0,n.checkDataTypes)(Ge,W,ue.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Je(){if(X.validateSchema){const Ge=Z.scopeValue("validate$data",{ref:X.validateSchema});return(0,i._)`!${Ge}(${W})`}return i.nil}}subschema(Z,W){const K=(0,a.getSubschema)(this.it,Z);(0,a.extendSubschemaData)(K,this.it,Z),(0,a.extendSubschemaMode)(K,Z);const X={...this.it,...K,items:void 0,props:void 0};return y(X,W),X}mergeEvaluated(Z,W){const{it:K,gen:X}=this;K.opts.unevaluated&&(K.props!==!0&&Z.props!==void 0&&(K.props=u.mergeEvaluated.props(X,Z.props,K.props,W)),K.items!==!0&&Z.items!==void 0&&(K.items=u.mergeEvaluated.items(X,Z.items,K.items,W)))}mergeValidEvaluated(Z,W){const{it:K,gen:X}=this;if(K.opts.unevaluated&&(K.props!==!0||K.items!==!0))return X.if(W,()=>this.mergeEvaluated(Z,i.Name)),!0}}Er.KeywordCxt=$;function B(L,Z,W,K){const X=new $(L,W,Z);"code"in W?W.code(X,K):X.$data&&W.validate?(0,o.funcKeywordCode)(X,W):"macro"in W?(0,o.macroKeywordCode)(X,W):(W.compile||W.validate)&&(0,o.funcKeywordCode)(X,W)}const G=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(L,{dataLevel:Z,dataNames:W,dataPathArr:K}){let X,ue;if(L==="")return c.default.rootData;if(L[0]==="/"){if(!G.test(L))throw new Error(`Invalid JSON-pointer: ${L}`);X=L,ue=c.default.rootData}else{const te=ve.exec(L);if(!te)throw new Error(`Invalid JSON-pointer: ${L}`);const ke=+te[1];if(X=te[2],X==="#"){if(ke>=Z)throw new Error(Ge("property/index",ke));return K[Z-ke]}if(ke>Z)throw new Error(Ge("data",ke));if(ue=W[Z-ke],!X)return ue}let me=ue;const Je=X.split("/");for(const te of Je)te&&(ue=(0,i._)`${ue}${(0,i.getProperty)((0,u.unescapeJsonPointer)(te))}`,me=(0,i._)`${me} && ${ue}`);return me;function Ge(te,ke){return`Cannot access ${te} ${ke} levels up, current level is ${Z}`}}return Er.getData=pe,Er}var Xo={},Wp;function $c(){if(Wp)return Xo;Wp=1,Object.defineProperty(Xo,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Xo.default=t,Xo}var ea={},Gp;function ta(){if(Gp)return ea;Gp=1,Object.defineProperty(ea,"__esModule",{value:!0});const t=Yo();class e extends Error{constructor(n,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,o),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return ea.default=e,ea}var At={},Kp;function Ec(){if(Kp)return At;Kp=1,Object.defineProperty(At,"__esModule",{value:!0}),At.resolveSchema=At.getCompilingSchema=At.resolveRef=At.compileSchema=At.SchemaEnv=void 0;const t=Ee(),e=$c(),r=Fr(),n=Yo(),s=Le(),o=Qo();class a{constructor(w){var g;this.refs={},this.dynamicAnchors={};let y;typeof w.schema=="object"&&(y=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(g=w.baseId)!==null&&g!==void 0?g:(0,n.normalizeId)(y?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=y?.$async,this.refs={}}}At.SchemaEnv=a;function i(_){const w=u.call(this,_);if(w)return w;const g=(0,n.getFullPath)(this.opts.uriResolver,_.root.baseId),{es5:y,lines:b}=this.opts.code,{ownProperties:S}=this.opts,k=new t.CodeGen(this.scope,{es5:y,lines:b,ownProperties:S});let T;_.$async&&(T=k.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const x=k.scopeName("validate");_.validateName=x;const P={gen:k,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:k.scopeValue("schema",this.opts.code.source===!0?{ref:_.schema,code:(0,t.stringify)(_.schema)}:{ref:_.schema}),validateName:x,ValidationError:T,schema:_.schema,schemaEnv:_,rootId:g,baseId:_.baseId||g,schemaPath:t.nil,errSchemaPath:_.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let q;try{this._compilations.add(_),(0,o.validateFunctionCode)(P),k.optimize(this.opts.code.optimize);const N=k.toString();q=`${k.scopeRefs(r.default.scope)}return ${N}`,this.opts.code.process&&(q=this.opts.code.process(q,_));const D=new Function(`${r.default.self}`,`${r.default.scope}`,q)(this,this.scope.get());if(this.scope.value(x,{ref:D}),D.errors=null,D.schema=_.schema,D.schemaEnv=_,_.$async&&(D.$async=!0),this.opts.code.source===!0&&(D.source={validateName:x,validateCode:N,scopeValues:k._values}),this.opts.unevaluated){const{props:F,items:oe}=P;D.evaluated={props:F instanceof t.Name?void 0:F,items:oe instanceof t.Name?void 0:oe,dynamicProps:F instanceof t.Name,dynamicItems:oe instanceof t.Name},D.source&&(D.source.evaluated=(0,t.stringify)(D.evaluated))}return _.validate=D,_}catch(N){throw delete _.validate,delete _.validateName,q&&this.logger.error("Error compiling schema, function code:",q),N}finally{this._compilations.delete(_)}}At.compileSchema=i;function c(_,w,g){var y;g=(0,n.resolveUrl)(this.opts.uriResolver,w,g);const b=_.refs[g];if(b)return b;let S=f.call(this,_,g);if(S===void 0){const k=(y=_.localRefs)===null||y===void 0?void 0:y[g],{schemaId:T}=this.opts;k&&(S=new a({schema:k,schemaId:T,root:_,baseId:w}))}if(S!==void 0)return _.refs[g]=l.call(this,S)}At.resolveRef=c;function l(_){return(0,n.inlineRef)(_.schema,this.opts.inlineRefs)?_.schema:_.validate?_:i.call(this,_)}function u(_){for(const w of this._compilations)if(h(w,_))return w}At.getCompilingSchema=u;function h(_,w){return _.schema===w.schema&&_.root===w.root&&_.baseId===w.baseId}function f(_,w){let g;for(;typeof(g=this.refs[w])=="string";)w=g;return g||this.schemas[w]||p.call(this,_,w)}function p(_,w){const g=this.opts.uriResolver.parse(w),y=(0,n._getFullPath)(this.opts.uriResolver,g);let b=(0,n.getFullPath)(this.opts.uriResolver,_.baseId,void 0);if(Object.keys(_.schema).length>0&&y===b)return v.call(this,g,_);const S=(0,n.normalizeId)(y),k=this.refs[S]||this.schemas[S];if(typeof k=="string"){const T=p.call(this,_,k);return typeof T?.schema!="object"?void 0:v.call(this,g,T)}if(typeof k?.schema=="object"){if(k.validate||i.call(this,k),S===(0,n.normalizeId)(w)){const{schema:T}=k,{schemaId:x}=this.opts,P=T[x];return P&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,P)),new a({schema:T,schemaId:x,root:_,baseId:b})}return v.call(this,g,k)}}At.resolveSchema=p;const m=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(_,{baseId:w,schema:g,root:y}){var b;if(((b=_.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const T of _.fragment.slice(1).split("/")){if(typeof g=="boolean")return;const x=g[(0,s.unescapeFragment)(T)];if(x===void 0)return;g=x;const P=typeof g=="object"&&g[this.opts.schemaId];!m.has(T)&&P&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,P))}let S;if(typeof g!="boolean"&&g.$ref&&!(0,s.schemaHasRulesButRef)(g,this.RULES)){const T=(0,n.resolveUrl)(this.opts.uriResolver,w,g.$ref);S=p.call(this,y,T)}const{schemaId:k}=this.opts;if(S=S||new a({schema:g,schemaId:k,root:y,baseId:w}),S.schema!==S.root.schema)return S}return At}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 ra={},$s={exports:{}},xc,Yp;function Qp(){if(Yp)return xc;Yp=1;const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),e=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(f){let p="",m=0,v=0;for(v=0;v<f.length;v++)if(m=f[v].charCodeAt(0),m!==48){if(!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";p+=f[v];break}for(v+=1;v<f.length;v++){if(m=f[v].charCodeAt(0),!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";p+=f[v]}return p}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(f){return f.length=0,!0}function o(f,p,m){if(f.length){const v=r(f);if(v!=="")p.push(v);else return m.error=!0,!1;f.length=0}return!0}function a(f){let p=0;const m={error:!1,address:"",zone:""},v=[],_=[];let w=!1,g=!1,y=o;for(let b=0;b<f.length;b++){const S=f[b];if(!(S==="["||S==="]"))if(S===":"){if(w===!0&&(g=!0),!y(_,v,m))break;if(++p>7){m.error=!0;break}b>0&&f[b-1]===":"&&(w=!0),v.push(":");continue}else if(S==="%"){if(!y(_,v,m))break;y=s}else{_.push(S);continue}}return _.length&&(y===s?m.zone=_.join(""):g?v.push(_.join("")):v.push(r(_))),m.address=v.join(""),m}function i(f){if(c(f,":")<2)return{host:f,isIPV6:!1};const p=a(f);if(p.error)return{host:f,isIPV6:!1};{let m=p.address,v=p.address;return p.zone&&(m+="%"+p.zone,v+="%25"+p.zone),{host:m,isIPV6:!0,escapedHost:v}}}function c(f,p){let m=0;for(let v=0;v<f.length;v++)f[v]===p&&m++;return m}function l(f){let p=f;const m=[];let v=-1,_=0;for(;_=p.length;){if(_===1){if(p===".")break;if(p==="/"){m.push("/");break}else{m.push(p);break}}else if(_===2){if(p[0]==="."){if(p[1]===".")break;if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&(p[1]==="."||p[1]==="/")){m.push("/");break}}else if(_===3&&p==="/.."){m.length!==0&&m.pop(),m.push("/");break}if(p[0]==="."){if(p[1]==="."){if(p[2]==="/"){p=p.slice(3);continue}}else if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&p[1]==="."){if(p[2]==="/"){p=p.slice(2);continue}else if(p[2]==="."&&p[3]==="/"){p=p.slice(3),m.length!==0&&m.pop();continue}}if((v=p.indexOf("/",1))===-1){m.push(p);break}else m.push(p.slice(0,v)),p=p.slice(v)}return m.join("")}function u(f,p){const m=p!==!0?escape:unescape;return f.scheme!==void 0&&(f.scheme=m(f.scheme)),f.userinfo!==void 0&&(f.userinfo=m(f.userinfo)),f.host!==void 0&&(f.host=m(f.host)),f.path!==void 0&&(f.path=m(f.path)),f.query!==void 0&&(f.query=m(f.query)),f.fragment!==void 0&&(f.fragment=m(f.fragment)),f}function h(f){const p=[];if(f.userinfo!==void 0&&(p.push(f.userinfo),p.push("@")),f.host!==void 0){let m=unescape(f.host);if(!e(m)){const v=i(m);v.isIPV6===!0?m=`[${v.escapedHost}]`:m=f.host}p.push(m)}return(typeof f.port=="number"||typeof f.port=="string")&&(p.push(":"),p.push(String(f.port))),p.length?p.join(""):void 0}return xc={nonSimpleDomain:n,recomposeAuthority:h,normalizeComponentEncoding:u,removeDotSegments:l,isIPv4:e,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:r},xc}var Ic,Xp;function $w(){if(Xp)return Ic;Xp=1;const{isUUID:t}=Qp(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(S){return r.indexOf(S)!==-1}function s(S){return S.secure===!0?!0:S.secure===!1?!1:S.scheme?S.scheme.length===3&&(S.scheme[0]==="w"||S.scheme[0]==="W")&&(S.scheme[1]==="s"||S.scheme[1]==="S")&&(S.scheme[2]==="s"||S.scheme[2]==="S"):!1}function o(S){return S.host||(S.error=S.error||"HTTP URIs must have a host."),S}function a(S){const k=String(S.scheme).toLowerCase()==="https";return(S.port===(k?443:80)||S.port==="")&&(S.port=void 0),S.path||(S.path="/"),S}function i(S){return S.secure=s(S),S.resourceName=(S.path||"/")+(S.query?"?"+S.query:""),S.path=void 0,S.query=void 0,S}function c(S){if((S.port===(s(S)?443:80)||S.port==="")&&(S.port=void 0),typeof S.secure=="boolean"&&(S.scheme=S.secure?"wss":"ws",S.secure=void 0),S.resourceName){const[k,T]=S.resourceName.split("?");S.path=k&&k!=="/"?k:void 0,S.query=T,S.resourceName=void 0}return S.fragment=void 0,S}function l(S,k){if(!S.path)return S.error="URN can not be parsed",S;const T=S.path.match(e);if(T){const x=k.scheme||S.scheme||"urn";S.nid=T[1].toLowerCase(),S.nss=T[2];const P=`${x}:${k.nid||S.nid}`,q=b(P);S.path=void 0,q&&(S=q.parse(S,k))}else S.error=S.error||"URN can not be parsed.";return S}function u(S,k){if(S.nid===void 0)throw new Error("URN without nid cannot be serialized");const T=k.scheme||S.scheme||"urn",x=S.nid.toLowerCase(),P=`${T}:${k.nid||x}`,q=b(P);q&&(S=q.serialize(S,k));const N=S,z=S.nss;return N.path=`${x||k.nid}:${z}`,k.skipEscape=!0,N}function h(S,k){const T=S;return T.uuid=T.nss,T.nss=void 0,!k.tolerant&&(!T.uuid||!t(T.uuid))&&(T.error=T.error||"UUID is not valid."),T}function f(S){const k=S;return k.nss=(S.uuid||"").toLowerCase(),k}const p={scheme:"http",domainHost:!0,parse:o,serialize:a},m={scheme:"https",domainHost:p.domainHost,parse:o,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:c},_={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},y={http:p,https:m,ws:v,wss:_,urn:{scheme:"urn",parse:l,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h,serialize:f,skipNormalize:!0}};Object.setPrototypeOf(y,null);function b(S){return S&&(y[S]||y[S.toLowerCase()])||void 0}return Ic={wsIsSecure:s,SCHEMES:y,isValidSchemeName:n,getSchemeHandler:b},Ic}var eh;function Ew(){if(eh)return $s.exports;eh=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:o}=Qp(),{SCHEMES:a,getSchemeHandler:i}=$w();function c(_,w){return typeof _=="string"?_=f(m(_,w),w):typeof _=="object"&&(_=m(f(_,w),w)),_}function l(_,w,g){const y=g?Object.assign({scheme:"null"},g):{scheme:"null"},b=u(m(_,y),m(w,y),y,!0);return y.skipEscape=!0,f(b,y)}function u(_,w,g,y){const b={};return y||(_=m(f(_,g),g),w=m(f(w,g),g)),g=g||{},!g.tolerant&&w.scheme?(b.scheme=w.scheme,b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.path?(w.path[0]==="/"?b.path=e(w.path):((_.userinfo!==void 0||_.host!==void 0||_.port!==void 0)&&!_.path?b.path="/"+w.path:_.path?b.path=_.path.slice(0,_.path.lastIndexOf("/")+1)+w.path:b.path=w.path,b.path=e(b.path)),b.query=w.query):(b.path=_.path,w.query!==void 0?b.query=w.query:b.query=_.query),b.userinfo=_.userinfo,b.host=_.host,b.port=_.port),b.scheme=_.scheme),b.fragment=w.fragment,b}function h(_,w,g){return typeof _=="string"?(_=unescape(_),_=f(n(m(_,g),!0),{...g,skipEscape:!0})):typeof _=="object"&&(_=f(n(_,!0),{...g,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=f(n(m(w,g),!0),{...g,skipEscape:!0})):typeof w=="object"&&(w=f(n(w,!0),{...g,skipEscape:!0})),_.toLowerCase()===w.toLowerCase()}function f(_,w){const g={host:_.host,scheme:_.scheme,userinfo:_.userinfo,port:_.port,path:_.path,query:_.query,nid:_.nid,nss:_.nss,uuid:_.uuid,fragment:_.fragment,reference:_.reference,resourceName:_.resourceName,secure:_.secure,error:""},y=Object.assign({},w),b=[],S=i(y.scheme||g.scheme);S&&S.serialize&&S.serialize(g,y),g.path!==void 0&&(y.skipEscape?g.path=unescape(g.path):(g.path=escape(g.path),g.scheme!==void 0&&(g.path=g.path.split("%3A").join(":")))),y.reference!=="suffix"&&g.scheme&&b.push(g.scheme,":");const k=r(g);if(k!==void 0&&(y.reference!=="suffix"&&b.push("//"),b.push(k),g.path&&g.path[0]!=="/"&&b.push("/")),g.path!==void 0){let T=g.path;!y.absolutePath&&(!S||!S.absolutePath)&&(T=e(T)),k===void 0&&T[0]==="/"&&T[1]==="/"&&(T="/%2F"+T.slice(2)),b.push(T)}return g.query!==void 0&&b.push("?",g.query),g.fragment!==void 0&&b.push("#",g.fragment),b.join("")}const p=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(_,w){const g=Object.assign({},w),y={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;g.reference==="suffix"&&(g.scheme?_=g.scheme+":"+_:_="//"+_);const S=_.match(p);if(S){if(y.scheme=S[1],y.userinfo=S[3],y.host=S[4],y.port=parseInt(S[5],10),y.path=S[6]||"",y.query=S[7],y.fragment=S[8],isNaN(y.port)&&(y.port=S[5]),y.host)if(s(y.host)===!1){const x=t(y.host);y.host=x.host.toLowerCase(),b=x.isIPV6}else b=!0;y.scheme===void 0&&y.userinfo===void 0&&y.host===void 0&&y.port===void 0&&y.query===void 0&&!y.path?y.reference="same-document":y.scheme===void 0?y.reference="relative":y.fragment===void 0?y.reference="absolute":y.reference="uri",g.reference&&g.reference!=="suffix"&&g.reference!==y.reference&&(y.error=y.error||"URI is not a "+g.reference+" reference.");const k=i(g.scheme||y.scheme);if(!g.unicodeSupport&&(!k||!k.unicodeSupport)&&y.host&&(g.domainHost||k&&k.domainHost)&&b===!1&&o(y.host))try{y.host=URL.domainToASCII(y.host.toLowerCase())}catch(T){y.error=y.error||"Host's domain name can not be converted to ASCII: "+T}(!k||k&&!k.skipNormalize)&&(_.indexOf("%")!==-1&&(y.scheme!==void 0&&(y.scheme=unescape(y.scheme)),y.host!==void 0&&(y.host=unescape(y.host))),y.path&&(y.path=escape(unescape(y.path))),y.fragment&&(y.fragment=encodeURI(decodeURIComponent(y.fragment)))),k&&k.parse&&k.parse(y,g)}else y.error=y.error||"URI can not be parsed.";return y}const v={SCHEMES:a,normalize:c,resolve:l,resolveComponent:u,equal:h,serialize:f,parse:m};return $s.exports=v,$s.exports.default=v,$s.exports.fastUri=v,$s.exports}var th;function xw(){if(th)return ra;th=1,Object.defineProperty(ra,"__esModule",{value:!0});const t=Ew();return t.code='require("ajv/dist/runtime/uri").default',ra.default=t,ra}var rh;function Iw(){return rh||(rh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Qo();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Ee();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=$c(),s=ta(),o=Np(),a=Ec(),i=Ee(),c=Yo(),l=Ko(),u=Le(),h=Tw,f=xw(),p=(H,A)=>new RegExp(H,A);p.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"]),_={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.'},g=200;function y(H){var A,V,j,E,R,$,B,G,ve,pe,L,Z,W,K,X,ue,me,Je,Ge,te,ke,Ct,Ie,Pt,zr;const Ot=H.strict,pt=(A=H.code)===null||A===void 0?void 0:A.optimize,Wt=pt===!0||pt===void 0?1:pt||0,un=(j=(V=H.code)===null||V===void 0?void 0:V.regExp)!==null&&j!==void 0?j:p,dn=(E=H.uriResolver)!==null&&E!==void 0?E:f.default;return{strictSchema:($=(R=H.strictSchema)!==null&&R!==void 0?R:Ot)!==null&&$!==void 0?$:!0,strictNumbers:(G=(B=H.strictNumbers)!==null&&B!==void 0?B:Ot)!==null&&G!==void 0?G:!0,strictTypes:(pe=(ve=H.strictTypes)!==null&&ve!==void 0?ve:Ot)!==null&&pe!==void 0?pe:"log",strictTuples:(Z=(L=H.strictTuples)!==null&&L!==void 0?L:Ot)!==null&&Z!==void 0?Z:"log",strictRequired:(K=(W=H.strictRequired)!==null&&W!==void 0?W:Ot)!==null&&K!==void 0?K:!1,code:H.code?{...H.code,optimize:Wt,regExp:un}:{optimize:Wt,regExp:un},loopRequired:(X=H.loopRequired)!==null&&X!==void 0?X:g,loopEnum:(ue=H.loopEnum)!==null&&ue!==void 0?ue:g,meta:(me=H.meta)!==null&&me!==void 0?me:!0,messages:(Je=H.messages)!==null&&Je!==void 0?Je:!0,inlineRefs:(Ge=H.inlineRefs)!==null&&Ge!==void 0?Ge:!0,schemaId:(te=H.schemaId)!==null&&te!==void 0?te:"$id",addUsedSchema:(ke=H.addUsedSchema)!==null&&ke!==void 0?ke:!0,validateSchema:(Ct=H.validateSchema)!==null&&Ct!==void 0?Ct:!0,validateFormats:(Ie=H.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(Pt=H.unicodeRegExp)!==null&&Pt!==void 0?Pt:!0,int32range:(zr=H.int32range)!==null&&zr!==void 0?zr:!0,uriResolver:dn}}class b{constructor(A={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,A=this.opts={...A,...y(A)};const{es5:V,lines:j}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:V,lines:j}),this.logger=z(A.logger);const E=A.validateFormats;A.validateFormats=!1,this.RULES=(0,o.getRules)(),S.call(this,_,A,"NOT SUPPORTED"),S.call(this,w,A,"DEPRECATED","warn"),this._metaOpts=q.call(this),A.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),A.keywords&&P.call(this,A.keywords),typeof A.meta=="object"&&this.addMetaSchema(A.meta),T.call(this),A.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:A,meta:V,schemaId:j}=this.opts;let E=h;j==="id"&&(E={...h},E.id=E.$id,delete E.$id),V&&A&&this.addMetaSchema(E,E[j],!1)}defaultMeta(){const{meta:A,schemaId:V}=this.opts;return this.opts.defaultMeta=typeof A=="object"?A[V]||A:void 0}validate(A,V){let j;if(typeof A=="string"){if(j=this.getSchema(A),!j)throw new Error(`no schema with key or ref "${A}"`)}else j=this.compile(A);const E=j(V);return"$async"in j||(this.errors=j.errors),E}compile(A,V){const j=this._addSchema(A,V);return j.validate||this._compileSchemaEnv(j)}compileAsync(A,V){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:j}=this.opts;return E.call(this,A,V);async function E(pe,L){await R.call(this,pe.$schema);const Z=this._addSchema(pe,L);return Z.validate||$.call(this,Z)}async function R(pe){pe&&!this.getSchema(pe)&&await E.call(this,{$ref:pe},!0)}async function $(pe){try{return this._compileSchemaEnv(pe)}catch(L){if(!(L instanceof s.default))throw L;return B.call(this,L),await G.call(this,L.missingSchema),$.call(this,pe)}}function B({missingSchema:pe,missingRef:L}){if(this.refs[pe])throw new Error(`AnySchema ${pe} is loaded but ${L} cannot be resolved`)}async function G(pe){const L=await ve.call(this,pe);this.refs[pe]||await R.call(this,L.$schema),this.refs[pe]||this.addSchema(L,pe,V)}async function ve(pe){const L=this._loading[pe];if(L)return L;try{return await(this._loading[pe]=j(pe))}finally{delete this._loading[pe]}}}addSchema(A,V,j,E=this.opts.validateSchema){if(Array.isArray(A)){for(const $ of A)this.addSchema($,void 0,j,E);return this}let R;if(typeof A=="object"){const{schemaId:$}=this.opts;if(R=A[$],R!==void 0&&typeof R!="string")throw new Error(`schema ${$} must be string`)}return V=(0,c.normalizeId)(V||R),this._checkUnique(V),this.schemas[V]=this._addSchema(A,j,V,E,!0),this}addMetaSchema(A,V,j=this.opts.validateSchema){return this.addSchema(A,V,!0,j),this}validateSchema(A,V){if(typeof A=="boolean")return!0;let j;if(j=A.$schema,j!==void 0&&typeof j!="string")throw new Error("$schema must be a string");if(j=j||this.opts.defaultMeta||this.defaultMeta(),!j)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(j,A);if(!E&&V){const R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return E}getSchema(A){let V;for(;typeof(V=k.call(this,A))=="string";)A=V;if(V===void 0){const{schemaId:j}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:j});if(V=a.resolveSchema.call(this,E,A),!V)return;this.refs[A]=V}return V.validate||this._compileSchemaEnv(V)}removeSchema(A){if(A instanceof RegExp)return this._removeAllSchemas(this.schemas,A),this._removeAllSchemas(this.refs,A),this;switch(typeof A){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const V=k.call(this,A);return typeof V=="object"&&this._cache.delete(V.schema),delete this.schemas[A],delete this.refs[A],this}case"object":{const V=A;this._cache.delete(V);let j=A[this.opts.schemaId];return j&&(j=(0,c.normalizeId)(j),delete this.schemas[j],delete this.refs[j]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(A){for(const V of A)this.addKeyword(V);return this}addKeyword(A,V){let j;if(typeof A=="string")j=A,typeof V=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),V.keyword=j);else if(typeof A=="object"&&V===void 0){if(V=A,j=V.keyword,Array.isArray(j)&&!j.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(F.call(this,j,V),!V)return(0,u.eachItem)(j,R=>oe.call(this,R)),this;de.call(this,V);const E={...V,type:(0,l.getJSONTypes)(V.type),schemaType:(0,l.getJSONTypes)(V.schemaType)};return(0,u.eachItem)(j,E.type.length===0?R=>oe.call(this,R,E):R=>E.type.forEach($=>oe.call(this,R,E,$))),this}getKeyword(A){const V=this.RULES.all[A];return typeof V=="object"?V.definition:!!V}removeKeyword(A){const{RULES:V}=this;delete V.keywords[A],delete V.all[A];for(const j of V.rules){const E=j.rules.findIndex(R=>R.keyword===A);E>=0&&j.rules.splice(E,1)}return this}addFormat(A,V){return typeof V=="string"&&(V=new RegExp(V)),this.formats[A]=V,this}errorsText(A=this.errors,{separator:V=", ",dataVar:j="data"}={}){return!A||A.length===0?"No errors":A.map(E=>`${j}${E.instancePath} ${E.message}`).reduce((E,R)=>E+V+R)}$dataMetaSchema(A,V){const j=this.RULES.all;A=JSON.parse(JSON.stringify(A));for(const E of V){const R=E.split("/").slice(1);let $=A;for(const B of R)$=$[B];for(const B in j){const G=j[B];if(typeof G!="object")continue;const{$data:ve}=G.definition,pe=$[B];ve&&pe&&($[B]=_e(pe))}}return A}_removeAllSchemas(A,V){for(const j in A){const E=A[j];(!V||V.test(j))&&(typeof E=="string"?delete A[j]:E&&!E.meta&&(this._cache.delete(E.schema),delete A[j]))}}_addSchema(A,V,j,E=this.opts.validateSchema,R=this.opts.addUsedSchema){let $;const{schemaId:B}=this.opts;if(typeof A=="object")$=A[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof A!="boolean")throw new Error("schema must be object or boolean")}let G=this._cache.get(A);if(G!==void 0)return G;j=(0,c.normalizeId)($||j);const ve=c.getSchemaRefs.call(this,A,j);return G=new a.SchemaEnv({schema:A,schemaId:B,meta:V,baseId:j,localRefs:ve}),this._cache.set(G.schema,G),R&&!j.startsWith("#")&&(j&&this._checkUnique(j),this.refs[j]=G),E&&this.validateSchema(A,!0),G}_checkUnique(A){if(this.schemas[A]||this.refs[A])throw new Error(`schema with key or id "${A}" already exists`)}_compileSchemaEnv(A){if(A.meta?this._compileMetaSchema(A):a.compileSchema.call(this,A),!A.validate)throw new Error("ajv implementation error");return A.validate}_compileMetaSchema(A){const V=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,A)}finally{this.opts=V}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function S(H,A,V,j="error"){for(const E in H){const R=E;R in A&&this.logger[j](`${V}: option ${E}. ${H[R]}`)}}function k(H){return H=(0,c.normalizeId)(H),this.schemas[H]||this.refs[H]}function T(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const A in H)this.addSchema(H[A],A)}function x(){for(const H in this.opts.formats){const A=this.opts.formats[H];A&&this.addFormat(H,A)}}function P(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const A in H){const V=H[A];V.keyword||(V.keyword=A),this.addKeyword(V)}}function q(){const H={...this.opts};for(const A of m)delete H[A];return H}const N={log(){},warn(){},error(){}};function z(H){if(H===!1)return N;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const D=/^[a-z_$][a-z0-9_$:-]*$/i;function F(H,A){const{RULES:V}=this;if((0,u.eachItem)(H,j=>{if(V.keywords[j])throw new Error(`Keyword ${j} is already defined`);if(!D.test(j))throw new Error(`Keyword ${j} has invalid name`)}),!!A&&A.$data&&!("code"in A||"validate"in A))throw new Error('$data keyword must have "code" or "validate" function')}function oe(H,A,V){var j;const E=A?.post;if(V&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:R}=this;let $=E?R.post:R.rules.find(({type:G})=>G===V);if($||($={type:V,rules:[]},R.rules.push($)),R.keywords[H]=!0,!A)return;const B={keyword:H,definition:{...A,type:(0,l.getJSONTypes)(A.type),schemaType:(0,l.getJSONTypes)(A.schemaType)}};A.before?fe.call(this,$,B,A.before):$.rules.push(B),R.all[H]=B,(j=A.implements)===null||j===void 0||j.forEach(G=>this.addKeyword(G))}function fe(H,A,V){const j=H.rules.findIndex(E=>E.keyword===V);j>=0?H.rules.splice(j,0,A):(H.rules.push(A),this.logger.warn(`rule ${V} is not defined`))}function de(H){let{metaSchema:A}=H;A!==void 0&&(H.$data&&this.opts.$data&&(A=_e(A)),H.validateSchema=this.compile(A,!0))}const se={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _e(H){return{anyOf:[H,se]}}})(yc)),yc}var na={},sa={},oa={},nh;function Rw(){if(nh)return oa;nh=1,Object.defineProperty(oa,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return oa.default=t,oa}var Hr={},sh;function Pw(){if(sh)return Hr;sh=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.callRef=Hr.getValidate=void 0;const t=ta(),e=Kt(),r=Ee(),n=Fr(),s=Ec(),o=Le(),a={keyword:"$ref",schemaType:"string",code(l){const{gen:u,schema:h,it:f}=l,{baseId:p,schemaEnv:m,validateName:v,opts:_,self:w}=f,{root:g}=m;if((h==="#"||h==="#/")&&p===g.baseId)return b();const y=s.resolveRef.call(w,g,p,h);if(y===void 0)throw new t.default(f.opts.uriResolver,p,h);if(y instanceof s.SchemaEnv)return S(y);return k(y);function b(){if(m===g)return c(l,v,m,m.$async);const T=u.scopeValue("root",{ref:g});return c(l,(0,r._)`${T}.validate`,g,g.$async)}function S(T){const x=i(l,T);c(l,x,T,T.$async)}function k(T){const x=u.scopeValue("schema",_.code.source===!0?{ref:T,code:(0,r.stringify)(T)}:{ref:T}),P=u.name("valid"),q=l.subschema({schema:T,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:h},P);l.mergeEvaluated(q),l.ok(P)}}};function i(l,u){const{gen:h}=l;return u.validate?h.scopeValue("validate",{ref:u.validate}):(0,r._)`${h.scopeValue("wrapper",{ref:u})}.validate`}Hr.getValidate=i;function c(l,u,h,f){const{gen:p,it:m}=l,{allErrors:v,schemaEnv:_,opts:w}=m,g=w.passContext?n.default.this:r.nil;f?y():b();function y(){if(!_.$async)throw new Error("async schema referenced by sync schema");const T=p.let("valid");p.try(()=>{p.code((0,r._)`await ${(0,e.callValidateCode)(l,u,g)}`),k(u),v||p.assign(T,!0)},x=>{p.if((0,r._)`!(${x} instanceof ${m.ValidationError})`,()=>p.throw(x)),S(x),v||p.assign(T,!1)}),l.ok(T)}function b(){l.result((0,e.callValidateCode)(l,u,g),()=>k(u),()=>S(u))}function S(T){const x=(0,r._)`${T}.errors`;p.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),p.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(T){var x;if(!m.opts.unevaluated)return;const P=(x=h?.validate)===null||x===void 0?void 0:x.evaluated;if(m.props!==!0)if(P&&!P.dynamicProps)P.props!==void 0&&(m.props=o.mergeEvaluated.props(p,P.props,m.props));else{const q=p.var("props",(0,r._)`${T}.evaluated.props`);m.props=o.mergeEvaluated.props(p,q,m.props,r.Name)}if(m.items!==!0)if(P&&!P.dynamicItems)P.items!==void 0&&(m.items=o.mergeEvaluated.items(p,P.items,m.items));else{const q=p.var("items",(0,r._)`${T}.evaluated.items`);m.items=o.mergeEvaluated.items(p,q,m.items,r.Name)}}}return Hr.callRef=c,Hr.default=a,Hr}var oh;function Ow(){if(oh)return sa;oh=1,Object.defineProperty(sa,"__esModule",{value:!0});const t=Rw(),e=Pw(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return sa.default=r,sa}var aa={},ia={},ah;function Aw(){if(ah)return ia;ah=1,Object.defineProperty(ia,"__esModule",{value:!0});const t=Ee(),e=t.operators,r={maximum:{okStr:"<=",ok:e.LTE,fail:e.GT},minimum:{okStr:">=",ok:e.GTE,fail:e.LT},exclusiveMaximum:{okStr:"<",ok:e.LT,fail:e.GTE},exclusiveMinimum:{okStr:">",ok:e.GT,fail:e.LTE}},n={message:({keyword:o,schemaCode:a})=>(0,t.str)`must be ${r[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,t._)`{comparison: ${r[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(o){const{keyword:a,data:i,schemaCode:c}=o;o.fail$data((0,t._)`${i} ${r[a].fail} ${c} || isNaN(${i})`)}};return ia.default=s,ia}var ca={},ih;function Mw(){if(ih)return ca;ih=1,Object.defineProperty(ca,"__esModule",{value:!0});const t=Ee(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){const{gen:s,data:o,schemaCode:a,it:i}=n,c=i.opts.multipleOfPrecision,l=s.let("res"),u=c?(0,t._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${c}`:(0,t._)`${l} !== parseInt(${l})`;n.fail$data((0,t._)`(${a} === 0 || (${l} = ${o}/${a}, ${u}))`)}};return ca.default=r,ca}var la={},ua={},ch;function Nw(){if(ch)return ua;ch=1,Object.defineProperty(ua,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,o;for(;s<r;)n++,o=e.charCodeAt(s++),o>=55296&&o<=56319&&s<r&&(o=e.charCodeAt(s),(o&64512)===56320&&s++);return n}return ua.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',ua}var lh;function Lw(){if(lh)return la;lh=1,Object.defineProperty(la,"__esModule",{value:!0});const t=Ee(),e=Le(),r=Nw(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:o,schemaCode:a}){const i=o==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:o})=>(0,t._)`{limit: ${o}}`},code(o){const{keyword:a,data:i,schemaCode:c,it:l}=o,u=a==="maxLength"?t.operators.GT:t.operators.LT,h=l.opts.unicode===!1?(0,t._)`${i}.length`:(0,t._)`${(0,e.useFunc)(o.gen,r.default)}(${i})`;o.fail$data((0,t._)`${h} ${u} ${c}`)}};return la.default=s,la}var da={},uh;function qw(){if(uh)return da;uh=1,Object.defineProperty(da,"__esModule",{value:!0});const t=Kt(),e=Ee(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,e.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,e._)`{pattern: ${s}}`},code(s){const{data:o,$data:a,schema:i,schemaCode:c,it:l}=s,u=l.opts.unicodeRegExp?"u":"",h=a?(0,e._)`(new RegExp(${c}, ${u}))`:(0,t.usePattern)(s,i);s.fail$data((0,e._)`!${h}.test(${o})`)}};return da.default=n,da}var pa={},dh;function jw(){if(dh)return pa;dh=1,Object.defineProperty(pa,"__esModule",{value:!0});const t=Ee(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${o}).length ${i} ${a}`)}};return pa.default=r,pa}var ha={},ph;function Uw(){if(ph)return ha;ph=1,Object.defineProperty(ha,"__esModule",{value:!0});const t=Kt(),e=Ee(),r=Le(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:o}})=>(0,e.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,e._)`{missingProperty: ${o}}`},code(o){const{gen:a,schema:i,schemaCode:c,data:l,$data:u,it:h}=o,{opts:f}=h;if(!u&&i.length===0)return;const p=i.length>=f.loopRequired;if(h.allErrors?m():v(),f.strictRequired){const g=o.parentSchema.properties,{definedProperties:y}=o.it;for(const b of i)if(g?.[b]===void 0&&!y.has(b)){const S=h.schemaEnv.baseId+h.errSchemaPath,k=`required property "${b}" is not defined at "${S}" (strictRequired)`;(0,r.checkStrictMode)(h,k,h.opts.strictRequired)}}function m(){if(p||u)o.block$data(e.nil,_);else for(const g of i)(0,t.checkReportMissingProp)(o,g)}function v(){const g=a.let("missing");if(p||u){const y=a.let("valid",!0);o.block$data(y,()=>w(g,y)),o.ok(y)}else a.if((0,t.checkMissingProp)(o,i,g)),(0,t.reportMissingProp)(o,g),a.else()}function _(){a.forOf("prop",c,g=>{o.setParams({missingProperty:g}),a.if((0,t.noPropertyInData)(a,l,g,f.ownProperties),()=>o.error())})}function w(g,y){o.setParams({missingProperty:g}),a.forOf(g,c,()=>{a.assign(y,(0,t.propertyInData)(a,l,g,f.ownProperties)),a.if((0,e.not)(y),()=>{o.error(),a.break()})},e.nil)}}};return ha.default=s,ha}var fa={},hh;function zw(){if(hh)return fa;hh=1,Object.defineProperty(fa,"__esModule",{value:!0});const t=Ee(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${o}.length ${i} ${a}`)}};return fa.default=r,fa}var ma={},ga={},fh;function Rc(){if(fh)return ga;fh=1,Object.defineProperty(ga,"__esModule",{value:!0});const t=Fp();return t.code='require("ajv/dist/runtime/equal").default',ga.default=t,ga}var mh;function Dw(){if(mh)return ma;mh=1,Object.defineProperty(ma,"__esModule",{value:!0});const t=Ko(),e=Ee(),r=Le(),n=Rc(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,e.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,e._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:c,$data:l,schema:u,parentSchema:h,schemaCode:f,it:p}=a;if(!l&&!u)return;const m=i.let("valid"),v=h.items?(0,t.getSchemaTypes)(h.items):[];a.block$data(m,_,(0,e._)`${f} === false`),a.ok(m);function _(){const b=i.let("i",(0,e._)`${c}.length`),S=i.let("j");a.setParams({i:b,j:S}),i.assign(m,!0),i.if((0,e._)`${b} > 1`,()=>(w()?g:y)(b,S))}function w(){return v.length>0&&!v.some(b=>b==="object"||b==="array")}function g(b,S){const k=i.name("item"),T=(0,t.checkDataTypes)(v,k,p.opts.strictNumbers,t.DataType.Wrong),x=i.const("indices",(0,e._)`{}`);i.for((0,e._)`;${b}--;`,()=>{i.let(k,(0,e._)`${c}[${b}]`),i.if(T,(0,e._)`continue`),v.length>1&&i.if((0,e._)`typeof ${k} == "string"`,(0,e._)`${k} += "_"`),i.if((0,e._)`typeof ${x}[${k}] == "number"`,()=>{i.assign(S,(0,e._)`${x}[${k}]`),a.error(),i.assign(m,!1).break()}).code((0,e._)`${x}[${k}] = ${b}`)})}function y(b,S){const k=(0,r.useFunc)(i,n.default),T=i.name("outer");i.label(T).for((0,e._)`;${b}--;`,()=>i.for((0,e._)`${S} = ${b}; ${S}--;`,()=>i.if((0,e._)`${k}(${c}[${b}], ${c}[${S}])`,()=>{a.error(),i.assign(m,!1).break(T)})))}}};return ma.default=o,ma}var _a={},gh;function Zw(){if(gh)return _a;gh=1,Object.defineProperty(_a,"__esModule",{value:!0});const t=Ee(),e=Le(),r=Rc(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:o})=>(0,t._)`{allowedValue: ${o}}`},code(o){const{gen:a,data:i,$data:c,schemaCode:l,schema:u}=o;c||u&&typeof u=="object"?o.fail$data((0,t._)`!${(0,e.useFunc)(a,r.default)}(${i}, ${l})`):o.fail((0,t._)`${u} !== ${i}`)}};return _a.default=s,_a}var va={},_h;function Vw(){if(_h)return va;_h=1,Object.defineProperty(va,"__esModule",{value:!0});const t=Ee(),e=Le(),r=Rc(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,t._)`{allowedValues: ${o}}`},code(o){const{gen:a,data:i,$data:c,schema:l,schemaCode:u,it:h}=o;if(!c&&l.length===0)throw new Error("enum must have non-empty array");const f=l.length>=h.opts.loopEnum;let p;const m=()=>p??(p=(0,e.useFunc)(a,r.default));let v;if(f||c)v=a.let("valid"),o.block$data(v,_);else{if(!Array.isArray(l))throw new Error("ajv implementation error");const g=a.const("vSchema",u);v=(0,t.or)(...l.map((y,b)=>w(g,b)))}o.pass(v);function _(){a.assign(v,!1),a.forOf("v",u,g=>a.if((0,t._)`${m()}(${i}, ${g})`,()=>a.assign(v,!0).break()))}function w(g,y){const b=l[y];return typeof b=="object"&&b!==null?(0,t._)`${m()}(${i}, ${g}[${y}])`:(0,t._)`${i} === ${b}`}}};return va.default=s,va}var vh;function Fw(){if(vh)return aa;vh=1,Object.defineProperty(aa,"__esModule",{value:!0});const t=Aw(),e=Mw(),r=Lw(),n=qw(),s=jw(),o=Uw(),a=zw(),i=Dw(),c=Zw(),l=Vw(),u=[t.default,e.default,r.default,n.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return aa.default=u,aa}var ya={},Un={},yh;function wh(){if(yh)return Un;yh=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.validateAdditionalItems=void 0;const t=Ee(),e=Le(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){const{parentSchema:a,it:i}=o,{items:c}=a;if(!Array.isArray(c)){(0,e.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,c)}};function s(o,a){const{gen:i,schema:c,data:l,keyword:u,it:h}=o;h.items=!0;const f=i.const("len",(0,t._)`${l}.length`);if(c===!1)o.setParams({len:a.length}),o.pass((0,t._)`${f} <= ${a.length}`);else if(typeof c=="object"&&!(0,e.alwaysValidSchema)(h,c)){const m=i.var("valid",(0,t._)`${f} <= ${a.length}`);i.if((0,t.not)(m),()=>p(m)),o.ok(m)}function p(m){i.forRange("i",a.length,f,v=>{o.subschema({keyword:u,dataProp:v,dataPropType:e.Type.Num},m),h.allErrors||i.if((0,t.not)(m),()=>i.break())})}}return Un.validateAdditionalItems=s,Un.default=n,Un}var wa={},zn={},bh;function Sh(){if(bh)return zn;bh=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.validateTuple=void 0;const t=Ee(),e=Le(),r=Kt(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:a,it:i}=o;if(Array.isArray(a))return s(o,"additionalItems",a);i.items=!0,!(0,e.alwaysValidSchema)(i,a)&&o.ok((0,r.validateArray)(o))}};function s(o,a,i=o.schema){const{gen:c,parentSchema:l,data:u,keyword:h,it:f}=o;v(l),f.opts.unevaluated&&i.length&&f.items!==!0&&(f.items=e.mergeEvaluated.items(c,i.length,f.items));const p=c.name("valid"),m=c.const("len",(0,t._)`${u}.length`);i.forEach((_,w)=>{(0,e.alwaysValidSchema)(f,_)||(c.if((0,t._)`${m} > ${w}`,()=>o.subschema({keyword:h,schemaProp:w,dataProp:w},p)),o.ok(p))});function v(_){const{opts:w,errSchemaPath:g}=f,y=i.length,b=y===_.minItems&&(y===_.maxItems||_[a]===!1);if(w.strictTuples&&!b){const S=`"${h}" is ${y}-tuple, but minItems or maxItems/${a} are not specified or different at path "${g}"`;(0,e.checkStrictMode)(f,S,w.strictTuples)}}}return zn.validateTuple=s,zn.default=n,zn}var kh;function Hw(){if(kh)return wa;kh=1,Object.defineProperty(wa,"__esModule",{value:!0});const t=Sh(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return wa.default=e,wa}var ba={},Ch;function Bw(){if(Ch)return ba;Ch=1,Object.defineProperty(ba,"__esModule",{value:!0});const t=Ee(),e=Le(),r=Kt(),n=wh(),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:c,it:l}=a,{prefixItems:u}=c;l.items=!0,!(0,e.alwaysValidSchema)(l,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return ba.default=o,ba}var Sa={},Th;function Jw(){if(Th)return Sa;Th=1,Object.defineProperty(Sa,"__esModule",{value:!0});const t=Ee(),e=Le(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:o}})=>o===void 0?(0,t.str)`must contain at least ${s} valid item(s)`:(0,t.str)`must contain at least ${s} and no more than ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${o}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:c,it:l}=s;let u,h;const{minContains:f,maxContains:p}=i;l.opts.next?(u=f===void 0?1:f,h=p):u=1;const m=o.const("len",(0,t._)`${c}.length`);if(s.setParams({min:u,max:h}),h===void 0&&u===0){(0,e.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(h!==void 0&&u>h){(0,e.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(l,a)){let y=(0,t._)`${m} >= ${u}`;h!==void 0&&(y=(0,t._)`${y} && ${m} <= ${h}`),s.pass(y);return}l.items=!0;const v=o.name("valid");h===void 0&&u===1?w(v,()=>o.if(v,()=>o.break())):u===0?(o.let(v,!0),h!==void 0&&o.if((0,t._)`${c}.length > 0`,_)):(o.let(v,!1),_()),s.result(v,()=>s.reset());function _(){const y=o.name("_valid"),b=o.let("count",0);w(y,()=>o.if(y,()=>g(b)))}function w(y,b){o.forRange("i",0,m,S=>{s.subschema({keyword:"contains",dataProp:S,dataPropType:e.Type.Num,compositeRule:!0},y),b()})}function g(y){o.code((0,t._)`${y}++`),h===void 0?o.if((0,t._)`${y} >= ${u}`,()=>o.assign(v,!0).break()):(o.if((0,t._)`${y} > ${h}`,()=>o.assign(v,!1).break()),u===1?o.assign(v,!0):o.if((0,t._)`${y} >= ${u}`,()=>o.assign(v,!0)))}}};return Sa.default=n,Sa}var Pc={},$h;function Ww(){return $h||($h=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Ee(),r=Le(),n=Kt();t.error={message:({params:{property:c,depsCount:l,deps:u}})=>{const h=l===1?"property":"properties";return(0,e.str)`must have ${h} ${u} when property ${c} is present`},params:({params:{property:c,depsCount:l,deps:u,missingProperty:h}})=>(0,e._)`{property: ${c},
|
|
6
|
-
missingProperty: ${
|
|
1
|
+
(function(Oe,rn){typeof exports=="object"&&typeof module<"u"?rn(exports):typeof define=="function"&&define.amd?define(["exports"],rn):(Oe=typeof globalThis<"u"?globalThis:Oe||self,rn(Oe.WebMCP={}))})(this,(function(Oe){"use strict";function rn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Po={exports:{}},Zi={},_r={},nn={},Fi={},Vi={},Hi={},bd;function Oo(){return bd||(bd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(g){if(super(),!t.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((_,b)=>`${_}${b}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((_,b)=>(b instanceof r&&(_[b.str]=(_[b.str]||0)+1),_),{})}}t._Code=n,t.nil=new n("");function s(w,...g){const _=[w[0]];let b=0;for(;b<g.length;)i(_,g[b]),_.push(w[++b]);return new n(_)}t._=s;const o=new n("+");function a(w,...g){const _=[d(w[0])];let b=0;for(;b<g.length;)_.push(o),i(_,g[b]),_.push(o,d(w[++b]));return c(_),new n(_)}t.str=a;function i(w,g){g instanceof n?w.push(...g._items):g instanceof r?w.push(g):w.push(p(g))}t.addCodeArg=i;function c(w){let g=1;for(;g<w.length-1;){if(w[g]===o){const _=l(w[g-1],w[g+1]);if(_!==void 0){w.splice(g-1,3,_);continue}w[g++]="+"}g++}}function l(w,g){if(g==='""')return w;if(w==='""')return g;if(typeof w=="string")return g instanceof r||w[w.length-1]!=='"'?void 0:typeof g!="string"?`${w.slice(0,-1)}${g}"`:g[0]==='"'?w.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(w instanceof r))return`"${w}${g.slice(1)}`}function u(w,g){return g.emptyStr()?w:w.emptyStr()?g:a`${w}${g}`}t.strConcat=u;function p(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:d(Array.isArray(w)?w.join(","):w)}function h(w){return new n(d(w))}t.stringify=h;function d(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function f(w){return typeof w=="string"&&t.IDENTIFIER.test(w)?new n(`.${w}`):s`[${w}]`}t.getProperty=f;function v(w){if(typeof w=="string"&&t.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}t.getEsmExportName=v;function y(w){return new n(w.toString())}t.regexpCode=y})(Hi)),Hi}var Bi={},kd;function Sd(){return kd||(kd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=Oo();class r extends Error{constructor(l){super(`CodeGen: "code" for ${l} not defined`),this.value=l.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:l,parent:u}={}){this._names={},this._prefixes=l,this._parent=u}toName(l){return l instanceof e.Name?l:this.name(l)}name(l){return new e.Name(this._newName(l))}_newName(l){const u=this._names[l]||this._nameGroup(l);return`${l}${u.index++}`}_nameGroup(l){var u,p;if(!((p=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||p===void 0)&&p.has(l)||this._prefixes&&!this._prefixes.has(l))throw new Error(`CodeGen: prefix "${l}" is not allowed in this scope`);return this._names[l]={prefix:l,index:0}}}t.Scope=s;class o extends e.Name{constructor(l,u){super(u),this.prefix=l}setValue(l,{property:u,itemIndex:p}){this.value=l,this.scopePath=(0,e._)`.${new e.Name(u)}[${p}]`}}t.ValueScopeName=o;const a=(0,e._)`\n`;class i extends s{constructor(l){super(l),this._values={},this._scope=l.scope,this.opts={...l,_n:l.lines?a:e.nil}}get(){return this._scope}name(l){return new o(l,this._newName(l))}value(l,u){var p;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(l),{prefix:d}=h,f=(p=u.key)!==null&&p!==void 0?p:u.ref;let v=this._values[d];if(v){const g=v.get(f);if(g)return g}else v=this._values[d]=new Map;v.set(f,h);const y=this._scope[d]||(this._scope[d]=[]),w=y.length;return y[w]=u.ref,h.setValue(u,{property:d,itemIndex:w}),h}getValue(l,u){const p=this._values[l];if(p)return p.get(u)}scopeRefs(l,u=this._values){return this._reduceValues(u,p=>{if(p.scopePath===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return(0,e._)`${l}${p.scopePath}`})}scopeCode(l=this._values,u,p){return this._reduceValues(l,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,p)}_reduceValues(l,u,p={},h){let d=e.nil;for(const f in l){const v=l[f];if(!v)continue;const y=p[f]=p[f]||new Map;v.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let g=u(w);if(g){const _=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${_} ${w} = ${g};${this.opts._n}`}else if(g=h?.(w))d=(0,e._)`${d}${g}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return d}}t.ValueScope=i})(Bi)),Bi}var Cd;function Te(){return Cd||(Cd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Oo(),r=Sd();var n=Oo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=Sd();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class o{optimizeNodes(){return this}optimizeNames(E,I){return this}}class a extends o{constructor(E,I,$){super(),this.varKind=E,this.name=I,this.rhs=$}render({es5:E,_n:I}){const $=E?r.varKinds.var:this.varKind,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${B};`+I}optimizeNames(E,I){if(E[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,E,I)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(E,I,$){super(),this.lhs=E,this.rhs=I,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,I){if(!(this.lhs instanceof e.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,E,I),this}get names(){const E=this.lhs instanceof e.Name?{}:{...this.lhs.names};return U(E,this.rhs)}}class c extends i{constructor(E,I,$,B){super(E,$,B),this.op=I}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class l extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class p extends o{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends o{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,I){return this.code=V(this.code,E,I),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends o{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((I,$)=>I+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let I=E.length;for(;I--;){const $=E[I].optimizeNodes();Array.isArray($)?E.splice(I,1,...$):$?E[I]=$:E.splice(I,1)}return E.length>0?this:void 0}optimizeNames(E,I){const{nodes:$}=this;let B=$.length;for(;B--;){const G=$[B];G.optimizeNames(E,I)||(ne(E,G.names),$.splice(B,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,I)=>D(E,I.names),{})}}class f extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends d{}class y extends f{}y.kind="else";class w extends f{constructor(E,I){super(I),this.condition=E}render(E){let I=`if(${this.condition})`+super.render(E);return this.else&&(I+="else "+this.else.render(E)),I}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let I=this.else;if(I){const $=I.optimizeNodes();I=this.else=Array.isArray($)?new y($):$}if(I)return E===!1?I instanceof w?I:I.nodes:this.nodes.length?this:new w(fe(E),I instanceof w?[I]:I.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,I){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,I),!!(super.optimizeNames(E,I)||this.else))return this.condition=V(this.condition,E,I),this}get names(){const E=super.names;return U(E,this.condition),this.else&&D(E,this.else.names),E}}w.kind="if";class g extends f{}g.kind="for";class _ extends g{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,I){if(super.optimizeNames(E,I))return this.iteration=V(this.iteration,E,I),this}get names(){return D(super.names,this.iteration.names)}}class b extends g{constructor(E,I,$,B){super(),this.varKind=E,this.name=I,this.from=$,this.to=B}render(E){const I=E.es5?r.varKinds.var:this.varKind,{name:$,from:B,to:G}=this;return`for(${I} ${$}=${B}; ${$}<${G}; ${$}++)`+super.render(E)}get names(){const E=U(super.names,this.from);return U(E,this.to)}}class k extends g{constructor(E,I,$,B){super(),this.loop=E,this.varKind=I,this.name=$,this.iterable=B}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,I){if(super.optimizeNames(E,I))return this.iterable=V(this.iterable,E,I),this}get names(){return D(super.names,this.iterable.names)}}class S extends f{constructor(E,I,$){super(),this.name=E,this.args=I,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class C extends d{render(E){return"return "+super.render(E)}}C.kind="return";class x extends f{render(E){let I="try"+super.render(E);return this.catch&&(I+=this.catch.render(E)),this.finally&&(I+=this.finally.render(E)),I}optimizeNodes(){var E,I;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(I=this.finally)===null||I===void 0||I.optimizeNodes(),this}optimizeNames(E,I){var $,B;return super.optimizeNames(E,I),($=this.catch)===null||$===void 0||$.optimizeNames(E,I),(B=this.finally)===null||B===void 0||B.optimizeNames(E,I),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class R extends f{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}R.kind="catch";class j extends f{render(E){return"finally"+super.render(E)}}j.kind="finally";class O{constructor(E,I={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...I,_n:I.lines?`
|
|
2
|
+
`:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,I){const $=this._extScope.value(E,I);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,I){return this._extScope.getValue(E,I)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,I,$,B){const G=this._scope.toName(I);return $!==void 0&&B&&(this._constants[G.str]=$),this._leafNode(new a(E,G,$)),G}const(E,I,$){return this._def(r.varKinds.const,E,I,$)}let(E,I,$){return this._def(r.varKinds.let,E,I,$)}var(E,I,$){return this._def(r.varKinds.var,E,I,$)}assign(E,I,$){return this._leafNode(new i(E,I,$))}add(E,I){return this._leafNode(new c(E,t.operators.ADD,I))}code(E){return typeof E=="function"?E():E!==e.nil&&this._leafNode(new h(E)),this}object(...E){const I=["{"];for(const[$,B]of E)I.length>1&&I.push(","),I.push($),($!==B||this.opts.es5)&&(I.push(":"),(0,e.addCodeArg)(I,B));return I.push("}"),new e._Code(I)}if(E,I,$){if(this._blockNode(new w(E)),I&&$)this.code(I).else().code($).endIf();else if(I)this.code(I).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,I){return this._blockNode(E),I&&this.code(I).endFor(),this}for(E,I){return this._for(new _(E),I)}forRange(E,I,$,B,G=this.opts.es5?r.varKinds.var:r.varKinds.let){const _e=this._scope.toName(E);return this._for(new b(G,_e,I,$),()=>B(_e))}forOf(E,I,$,B=r.varKinds.const){const G=this._scope.toName(E);if(this.opts.es5){const _e=I instanceof e.Name?I:this.var("_arr",I);return this.forRange("_i",0,(0,e._)`${_e}.length`,pe=>{this.var(G,(0,e._)`${_e}[${pe}]`),$(G)})}return this._for(new k("of",B,G,I),()=>$(G))}forIn(E,I,$,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,e._)`Object.keys(${I})`,$);const G=this._scope.toName(E);return this._for(new k("in",B,G,I),()=>$(G))}endFor(){return this._endBlockNode(g)}label(E){return this._leafNode(new l(E))}break(E){return this._leafNode(new u(E))}return(E){const I=new C;if(this._blockNode(I),this.code(E),I.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(E,I,$){if(!I&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new x;if(this._blockNode(B),this.code(E),I){const G=this.name("e");this._currNode=B.catch=new R(G),I(G)}return $&&(this._currNode=B.finally=new j,this.code($)),this._endBlockNode(R,j)}throw(E){return this._leafNode(new p(E))}block(E,I){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(I),this}endBlock(E){const I=this._blockStarts.pop();if(I===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-I;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=I,this}func(E,I=e.nil,$,B){return this._blockNode(new S(E,I,$)),B&&this.code(B).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,I){const $=this._currNode;if($ instanceof E||I&&$ instanceof I)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${I?`${E.kind}/${I.kind}`:E.kind}"`)}_elseNode(E){const I=this._currNode;if(!(I instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=I.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const I=this._nodes;I[I.length-1]=E}}t.CodeGen=O;function D(q,E){for(const I in E)q[I]=(q[I]||0)+(E[I]||0);return q}function U(q,E){return E instanceof e._CodeOrName?D(q,E.names):q}function V(q,E,I){if(q instanceof e.Name)return $(q);if(!B(q))return q;return new e._Code(q._items.reduce((G,_e)=>(_e instanceof e.Name&&(_e=$(_e)),_e instanceof e._Code?G.push(..._e._items):G.push(_e),G),[]));function $(G){const _e=I[G.str];return _e===void 0||E[G.str]!==1?G:(delete E[G.str],_e)}function B(G){return G instanceof e._Code&&G._items.some(_e=>_e instanceof e.Name&&E[_e.str]===1&&I[_e.str]!==void 0)}}function ne(q,E){for(const I in E)q[I]=(q[I]||0)-(E[I]||0)}function fe(q){return typeof q=="boolean"||typeof q=="number"||q===null?!q:(0,e._)`!${F(q)}`}t.not=fe;const de=P(t.operators.AND);function te(...q){return q.reduce(de)}t.and=te;const ye=P(t.operators.OR);function H(...q){return q.reduce(ye)}t.or=H;function P(q){return(E,I)=>E===e.nil?I:I===e.nil?E:(0,e._)`${F(E)} ${q} ${F(I)}`}function F(q){return q instanceof e.Name?q:(0,e._)`(${q})`}})(Vi)),Vi}var $e={},Td;function Ae(){if(Td)return $e;Td=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.checkStrictMode=$e.getErrorPath=$e.Type=$e.useFunc=$e.setEvaluated=$e.evaluatedPropsToName=$e.mergeEvaluated=$e.eachItem=$e.unescapeJsonPointer=$e.escapeJsonPointer=$e.escapeFragment=$e.unescapeFragment=$e.schemaRefOrVal=$e.schemaHasRulesButRef=$e.schemaHasRules=$e.checkUnknownRules=$e.alwaysValidSchema=$e.toHash=void 0;const t=Te(),e=Oo();function r(k){const S={};for(const C of k)S[C]=!0;return S}$e.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(s(k,S),!o(S,k.self.RULES.all))}$e.alwaysValidSchema=n;function s(k,S=k.schema){const{opts:C,self:x}=k;if(!C.strictSchema||typeof S=="boolean")return;const R=x.RULES.keywords;for(const j in S)R[j]||b(k,`unknown keyword: "${j}"`)}$e.checkUnknownRules=s;function o(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(S[C])return!0;return!1}$e.schemaHasRules=o;function a(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(C!=="$ref"&&S.all[C])return!0;return!1}$e.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},C,x,R){if(!R){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,t._)`${C}`}return(0,t._)`${k}${S}${(0,t.getProperty)(x)}`}$e.schemaRefOrVal=i;function c(k){return p(decodeURIComponent(k))}$e.unescapeFragment=c;function l(k){return encodeURIComponent(u(k))}$e.escapeFragment=l;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}$e.escapeJsonPointer=u;function p(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}$e.unescapeJsonPointer=p;function h(k,S){if(Array.isArray(k))for(const C of k)S(C);else S(k)}$e.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:C,resultToName:x}){return(R,j,O,D)=>{const U=O===void 0?j:O instanceof t.Name?(j instanceof t.Name?k(R,j,O):S(R,j,O),O):j instanceof t.Name?(S(R,O,j),j):C(j,O);return D===t.Name&&!(U instanceof t.Name)?x(R,U):U}}$e.mergeEvaluated={props:d({mergeNames:(k,S,C)=>k.if((0,t._)`${C} !== true && ${S} !== undefined`,()=>{k.if((0,t._)`${S} === true`,()=>k.assign(C,!0),()=>k.assign(C,(0,t._)`${C} || {}`).code((0,t._)`Object.assign(${C}, ${S})`))}),mergeToName:(k,S,C)=>k.if((0,t._)`${C} !== true`,()=>{S===!0?k.assign(C,!0):(k.assign(C,(0,t._)`${C} || {}`),v(k,C,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:f}),items:d({mergeNames:(k,S,C)=>k.if((0,t._)`${C} !== true && ${S} !== undefined`,()=>k.assign(C,(0,t._)`${S} === true ? true : ${C} > ${S} ? ${C} : ${S}`)),mergeToName:(k,S,C)=>k.if((0,t._)`${C} !== true`,()=>k.assign(C,S===!0?!0:(0,t._)`${C} > ${S} ? ${C} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function f(k,S){if(S===!0)return k.var("props",!0);const C=k.var("props",(0,t._)`{}`);return S!==void 0&&v(k,C,S),C}$e.evaluatedPropsToName=f;function v(k,S,C){Object.keys(C).forEach(x=>k.assign((0,t._)`${S}${(0,t.getProperty)(x)}`,!0))}$e.setEvaluated=v;const y={};function w(k,S){return k.scopeValue("func",{ref:S,code:y[S.code]||(y[S.code]=new e._Code(S.code))})}$e.useFunc=w;var g;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(g||($e.Type=g={}));function _(k,S,C){if(k instanceof t.Name){const x=S===g.Num;return C?x?(0,t._)`"[" + ${k} + "]"`:(0,t._)`"['" + ${k} + "']"`:x?(0,t._)`"/" + ${k}`:(0,t._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,t.getProperty)(k).toString():"/"+u(k)}$e.getErrorPath=_;function b(k,S,C=k.opts.strictSchema){if(C){if(S=`strict mode: ${S}`,C===!0)throw new Error(S);k.self.logger.warn(S)}}return $e.checkStrictMode=b,$e}var Ao={},$d;function Lr(){if($d)return Ao;$d=1,Object.defineProperty(Ao,"__esModule",{value:!0});const t=Te(),e={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};return Ao.default=e,Ao}var Ed;function Mo(){return Ed||(Ed=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=Te(),r=Ae(),n=Lr();t.keywordError={message:({keyword:y})=>(0,e.str)`must pass "${y}" keyword validation`},t.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,e.str)`"${y}" keyword must be ${w} ($data)`:(0,e.str)`"${y}" keyword is invalid ($data)`};function s(y,w=t.keywordError,g,_){const{it:b}=y,{gen:k,compositeRule:S,allErrors:C}=b,x=p(y,w,g);_??(S||C)?c(k,x):l(b,(0,e._)`[${x}]`)}t.reportError=s;function o(y,w=t.keywordError,g){const{it:_}=y,{gen:b,compositeRule:k,allErrors:S}=_,C=p(y,w,g);c(b,C),k||S||l(_,n.default.vErrors)}t.reportExtraError=o;function a(y,w){y.assign(n.default.errors,w),y.if((0,e._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,e._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}t.resetErrorsCount=a;function i({gen:y,keyword:w,schemaValue:g,data:_,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=y.name("err");y.forRange("i",b,n.default.errors,C=>{y.const(S,(0,e._)`${n.default.vErrors}[${C}]`),y.if((0,e._)`${S}.instancePath === undefined`,()=>y.assign((0,e._)`${S}.instancePath`,(0,e.strConcat)(n.default.instancePath,k.errorPath))),y.assign((0,e._)`${S}.schemaPath`,(0,e.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(y.assign((0,e._)`${S}.schema`,g),y.assign((0,e._)`${S}.data`,_))})}t.extendErrors=i;function c(y,w){const g=y.const("err",w);y.if((0,e._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,e._)`[${g}]`),(0,e._)`${n.default.vErrors}.push(${g})`),y.code((0,e._)`${n.default.errors}++`)}function l(y,w){const{gen:g,validateName:_,schemaEnv:b}=y;b.$async?g.throw((0,e._)`new ${y.ValidationError}(${w})`):(g.assign((0,e._)`${_}.errors`,w),g.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function p(y,w,g){const{createErrors:_}=y.it;return _===!1?(0,e._)`{}`:h(y,w,g)}function h(y,w,g={}){const{gen:_,it:b}=y,k=[d(b,g),f(y,g)];return v(y,w,k),_.object(...k)}function d({errorPath:y},{instancePath:w}){const g=w?(0,e.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,g)]}function f({keyword:y,it:{errSchemaPath:w}},{schemaPath:g,parentSchema:_}){let b=_?w:(0,e.str)`${w}/${y}`;return g&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(g,r.Type.Str)}`),[u.schemaPath,b]}function v(y,{params:w,message:g},_){const{keyword:b,data:k,schemaValue:S,it:C}=y,{opts:x,propertyName:R,topSchemaRef:j,schemaPath:O}=C;_.push([u.keyword,b],[u.params,typeof w=="function"?w(y):w||(0,e._)`{}`]),x.messages&&_.push([u.message,typeof g=="function"?g(y):g]),x.verbose&&_.push([u.schema,S],[u.parentSchema,(0,e._)`${j}${O}`],[n.default.data,k]),R&&_.push([u.propertyName,R])}})(Fi)),Fi}var xd;function T_(){if(xd)return nn;xd=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.boolOrEmptySchema=nn.topBoolOrEmptySchema=void 0;const t=Mo(),e=Te(),r=Lr(),n={message:"boolean schema is false"};function s(i){const{gen:c,schema:l,validateName:u}=i;l===!1?a(i,!1):typeof l=="object"&&l.$async===!0?c.return(r.default.data):(c.assign((0,e._)`${u}.errors`,null),c.return(!0))}nn.topBoolOrEmptySchema=s;function o(i,c){const{gen:l,schema:u}=i;u===!1?(l.var(c,!1),a(i)):l.var(c,!0)}nn.boolOrEmptySchema=o;function a(i,c){const{gen:l,data:u}=i,p={gen:l,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,t.reportError)(p,n,void 0,c)}return nn}var nt={},sn={},Id;function Rd(){if(Id)return sn;Id=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.getRules=sn.isJSONType=void 0;const t=["string","number","integer","boolean","null","object","array"],e=new Set(t);function r(s){return typeof s=="string"&&e.has(s)}sn.isJSONType=r;function n(){const s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}return sn.getRules=n,sn}var vr={},Pd;function Od(){if(Pd)return vr;Pd=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.shouldUseRule=vr.shouldUseGroup=vr.schemaHasRulesForType=void 0;function t({schema:n,self:s},o){const a=s.RULES.types[o];return a&&a!==!0&&e(n,a)}vr.schemaHasRulesForType=t;function e(n,s){return s.rules.some(o=>r(n,o))}vr.shouldUseGroup=e;function r(n,s){var o;return n[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>n[a]!==void 0))}return vr.shouldUseRule=r,vr}var Ad;function No(){if(Ad)return nt;Ad=1,Object.defineProperty(nt,"__esModule",{value:!0}),nt.reportTypeError=nt.checkDataTypes=nt.checkDataType=nt.coerceAndCheckDataType=nt.getJSONTypes=nt.getSchemaTypes=nt.DataType=void 0;const t=Rd(),e=Od(),r=Mo(),n=Te(),s=Ae();var o;(function(g){g[g.Correct=0]="Correct",g[g.Wrong=1]="Wrong"})(o||(nt.DataType=o={}));function a(g){const _=i(g.type);if(_.includes("null")){if(g.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!_.length&&g.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');g.nullable===!0&&_.push("null")}return _}nt.getSchemaTypes=a;function i(g){const _=Array.isArray(g)?g:g?[g]:[];if(_.every(t.isJSONType))return _;throw new Error("type must be JSONType or JSONType[]: "+_.join(","))}nt.getJSONTypes=i;function c(g,_){const{gen:b,data:k,opts:S}=g,C=u(_,S.coerceTypes),x=_.length>0&&!(C.length===0&&_.length===1&&(0,e.schemaHasRulesForType)(g,_[0]));if(x){const R=f(_,k,S.strictNumbers,o.Wrong);b.if(R,()=>{C.length?p(g,_,C):y(g)})}return x}nt.coerceAndCheckDataType=c;const l=new Set(["string","number","integer","boolean","null"]);function u(g,_){return _?g.filter(b=>l.has(b)||_==="array"&&b==="array"):[]}function p(g,_,b){const{gen:k,data:S,opts:C}=g,x=k.let("dataType",(0,n._)`typeof ${S}`),R=k.let("coerced",(0,n._)`undefined`);C.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(x,(0,n._)`typeof ${S}`).if(f(_,S,C.strictNumbers),()=>k.assign(R,S))),k.if((0,n._)`${R} !== undefined`);for(const O of b)(l.has(O)||O==="array"&&C.coerceTypes==="array")&&j(O);k.else(),y(g),k.endIf(),k.if((0,n._)`${R} !== undefined`,()=>{k.assign(S,R),h(g,R)});function j(O){switch(O){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(R,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(R,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${S} === null
|
|
3
|
+
|| (${x} == "string" && ${S} && ${S} == +${S})`).assign(R,(0,n._)`+${S}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${S} === null
|
|
4
|
+
|| (${x} === "string" && ${S} && ${S} == +${S} && !(${S} % 1))`).assign(R,(0,n._)`+${S}`);return;case"boolean":k.elseIf((0,n._)`${S} === "false" || ${S} === 0 || ${S} === null`).assign(R,!1).elseIf((0,n._)`${S} === "true" || ${S} === 1`).assign(R,!0);return;case"null":k.elseIf((0,n._)`${S} === "" || ${S} === 0 || ${S} === false`),k.assign(R,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
|
|
5
|
+
|| ${x} === "boolean" || ${S} === null`).assign(R,(0,n._)`[${S}]`)}}}function h({gen:g,parentData:_,parentDataProperty:b},k){g.if((0,n._)`${_} !== undefined`,()=>g.assign((0,n._)`${_}[${b}]`,k))}function d(g,_,b,k=o.Correct){const S=k===o.Correct?n.operators.EQ:n.operators.NEQ;let C;switch(g){case"null":return(0,n._)`${_} ${S} null`;case"array":C=(0,n._)`Array.isArray(${_})`;break;case"object":C=(0,n._)`${_} && typeof ${_} == "object" && !Array.isArray(${_})`;break;case"integer":C=x((0,n._)`!(${_} % 1) && !isNaN(${_})`);break;case"number":C=x();break;default:return(0,n._)`typeof ${_} ${S} ${g}`}return k===o.Correct?C:(0,n.not)(C);function x(R=n.nil){return(0,n.and)((0,n._)`typeof ${_} == "number"`,R,b?(0,n._)`isFinite(${_})`:n.nil)}}nt.checkDataType=d;function f(g,_,b,k){if(g.length===1)return d(g[0],_,b,k);let S;const C=(0,s.toHash)(g);if(C.array&&C.object){const x=(0,n._)`typeof ${_} != "object"`;S=C.null?x:(0,n._)`!${_} || ${x}`,delete C.null,delete C.array,delete C.object}else S=n.nil;C.number&&delete C.integer;for(const x in C)S=(0,n.and)(S,d(x,_,b,k));return S}nt.checkDataTypes=f;const v={message:({schema:g})=>`must be ${g}`,params:({schema:g,schemaValue:_})=>typeof g=="string"?(0,n._)`{type: ${g}}`:(0,n._)`{type: ${_}}`};function y(g){const _=w(g);(0,r.reportError)(_,v)}nt.reportTypeError=y;function w(g){const{gen:_,data:b,schema:k}=g,S=(0,s.schemaRefOrVal)(g,k,"type");return{gen:_,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:g}}return nt}var fs={},Md;function $_(){if(Md)return fs;Md=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.assignDefaults=void 0;const t=Te(),e=Ae();function r(s,o){const{properties:a,items:i}=s.schema;if(o==="object"&&a)for(const c in a)n(s,c,a[c].default);else o==="array"&&Array.isArray(i)&&i.forEach((c,l)=>n(s,l,c.default))}fs.assignDefaults=r;function n(s,o,a){const{gen:i,compositeRule:c,data:l,opts:u}=s;if(a===void 0)return;const p=(0,t._)`${l}${(0,t.getProperty)(o)}`;if(c){(0,e.checkStrictMode)(s,`default is ignored for: ${p}`);return}let h=(0,t._)`${p} === undefined`;u.useDefaults==="empty"&&(h=(0,t._)`${h} || ${p} === null || ${p} === ""`),i.if(h,(0,t._)`${p} = ${(0,t.stringify)(a)}`)}return fs}var Ft={},je={},Nd;function Vt(){if(Nd)return je;Nd=1,Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const t=Te(),e=Ae(),r=Lr(),n=Ae();function s(g,_){const{gen:b,data:k,it:S}=g;b.if(u(b,k,_,S.opts.ownProperties),()=>{g.setParams({missingProperty:(0,t._)`${_}`},!0),g.error()})}je.checkReportMissingProp=s;function o({gen:g,data:_,it:{opts:b}},k,S){return(0,t.or)(...k.map(C=>(0,t.and)(u(g,_,C,b.ownProperties),(0,t._)`${S} = ${C}`)))}je.checkMissingProp=o;function a(g,_){g.setParams({missingProperty:_},!0),g.error()}je.reportMissingProp=a;function i(g){return g.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=i;function c(g,_,b){return(0,t._)`${i(g)}.call(${_}, ${b})`}je.isOwnProperty=c;function l(g,_,b,k){const S=(0,t._)`${_}${(0,t.getProperty)(b)} !== undefined`;return k?(0,t._)`${S} && ${c(g,_,b)}`:S}je.propertyInData=l;function u(g,_,b,k){const S=(0,t._)`${_}${(0,t.getProperty)(b)} === undefined`;return k?(0,t.or)(S,(0,t.not)(c(g,_,b))):S}je.noPropertyInData=u;function p(g){return g?Object.keys(g).filter(_=>_!=="__proto__"):[]}je.allSchemaProperties=p;function h(g,_){return p(_).filter(b=>!(0,e.alwaysValidSchema)(g,_[b]))}je.schemaProperties=h;function d({schemaCode:g,data:_,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:C},it:x},R,j,O){const D=O?(0,t._)`${g}, ${_}, ${k}${S}`:_,U=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,C)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const V=(0,t._)`${D}, ${b.object(...U)}`;return j!==t.nil?(0,t._)`${R}.call(${j}, ${V})`:(0,t._)`${R}(${V})`}je.callValidateCode=d;const f=(0,t._)`new RegExp`;function v({gen:g,it:{opts:_}},b){const k=_.unicodeRegExp?"u":"",{regExp:S}=_.code,C=S(b,k);return g.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,t._)`${S.code==="new RegExp"?f:(0,n.useFunc)(g,S)}(${b}, ${k})`})}je.usePattern=v;function y(g){const{gen:_,data:b,keyword:k,it:S}=g,C=_.name("valid");if(S.allErrors){const R=_.let("valid",!0);return x(()=>_.assign(R,!1)),R}return _.var(C,!0),x(()=>_.break()),C;function x(R){const j=_.const("len",(0,t._)`${b}.length`);_.forRange("i",0,j,O=>{g.subschema({keyword:k,dataProp:O,dataPropType:e.Type.Num},C),_.if((0,t.not)(C),R)})}}je.validateArray=y;function w(g){const{gen:_,schema:b,keyword:k,it:S}=g;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(j=>(0,e.alwaysValidSchema)(S,j))&&!S.opts.unevaluated)return;const x=_.let("valid",!1),R=_.name("_valid");_.block(()=>b.forEach((j,O)=>{const D=g.subschema({keyword:k,schemaProp:O,compositeRule:!0},R);_.assign(x,(0,t._)`${x} || ${R}`),g.mergeValidEvaluated(D,R)||_.if((0,t.not)(x))})),g.result(x,()=>g.reset(),()=>g.error(!0))}return je.validateUnion=w,je}var Ld;function E_(){if(Ld)return Ft;Ld=1,Object.defineProperty(Ft,"__esModule",{value:!0}),Ft.validateKeywordUsage=Ft.validSchemaType=Ft.funcKeywordCode=Ft.macroKeywordCode=void 0;const t=Te(),e=Lr(),r=Vt(),n=Mo();function s(h,d){const{gen:f,keyword:v,schema:y,parentSchema:w,it:g}=h,_=d.macro.call(g.self,y,w,g),b=l(f,v,_);g.opts.validateSchema!==!1&&g.self.validateSchema(_,!0);const k=f.name("valid");h.subschema({schema:_,schemaPath:t.nil,errSchemaPath:`${g.errSchemaPath}/${v}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Ft.macroKeywordCode=s;function o(h,d){var f;const{gen:v,keyword:y,schema:w,parentSchema:g,$data:_,it:b}=h;c(b,d);const k=!_&&d.compile?d.compile.call(b.self,w,g,b):d.validate,S=l(v,y,k),C=v.let("valid");h.block$data(C,x),h.ok((f=d.valid)!==null&&f!==void 0?f:C);function x(){if(d.errors===!1)O(),d.modifying&&a(h),D(()=>h.error());else{const U=d.async?R():j();d.modifying&&a(h),D(()=>i(h,U))}}function R(){const U=v.let("ruleErrs",null);return v.try(()=>O((0,t._)`await `),V=>v.assign(C,!1).if((0,t._)`${V} instanceof ${b.ValidationError}`,()=>v.assign(U,(0,t._)`${V}.errors`),()=>v.throw(V))),U}function j(){const U=(0,t._)`${S}.errors`;return v.assign(U,null),O(t.nil),U}function O(U=d.async?(0,t._)`await `:t.nil){const V=b.opts.passContext?e.default.this:e.default.self,ne=!("compile"in d&&!_||d.schema===!1);v.assign(C,(0,t._)`${U}${(0,r.callValidateCode)(h,S,V,ne)}`,d.modifying)}function D(U){var V;v.if((0,t.not)((V=d.valid)!==null&&V!==void 0?V:C),U)}}Ft.funcKeywordCode=o;function a(h){const{gen:d,data:f,it:v}=h;d.if(v.parentData,()=>d.assign(f,(0,t._)`${v.parentData}[${v.parentDataProperty}]`))}function i(h,d){const{gen:f}=h;f.if((0,t._)`Array.isArray(${d})`,()=>{f.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${d} : ${e.default.vErrors}.concat(${d})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function c({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function l(h,d,f){if(f===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,t.stringify)(f)})}function u(h,d,f=!1){return!d.length||d.some(v=>v==="array"?Array.isArray(h):v==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==v||f&&typeof h>"u")}Ft.validSchemaType=u;function p({schema:h,opts:d,self:f,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const g=y.dependencies;if(g?.some(_=>!Object.prototype.hasOwnProperty.call(h,_)))throw new Error(`parent schema must have dependencies of ${w}: ${g.join(",")}`);if(y.validateSchema&&!y.validateSchema(h[w])){const b=`keyword "${w}" value is invalid at path "${v}": `+f.errorsText(y.validateSchema.errors);if(d.validateSchema==="log")f.logger.error(b);else throw new Error(b)}}return Ft.validateKeywordUsage=p,Ft}var wr={},jd;function x_(){if(jd)return wr;jd=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;const t=Te(),e=Ae();function r(o,{keyword:a,schemaProp:i,schema:c,schemaPath:l,errSchemaPath:u,topSchemaRef:p}){if(a!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const h=o.schema[a];return i===void 0?{schema:h,schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:h[i],schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}${(0,t.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,e.escapeFragment)(i)}`}}if(c!==void 0){if(l===void 0||u===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:l,topSchemaRef:p,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}wr.getSubschema=r;function n(o,a,{dataProp:i,dataPropType:c,data:l,dataTypes:u,propertyName:p}){if(l!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=a;if(i!==void 0){const{errorPath:f,dataPathArr:v,opts:y}=a,w=h.let("data",(0,t._)`${a.data}${(0,t.getProperty)(i)}`,!0);d(w),o.errorPath=(0,t.str)`${f}${(0,e.getErrorPath)(i,c,y.jsPropertySyntax)}`,o.parentDataProperty=(0,t._)`${i}`,o.dataPathArr=[...v,o.parentDataProperty]}if(l!==void 0){const f=l instanceof t.Name?l:h.let("data",l,!0);d(f),p!==void 0&&(o.propertyName=p)}u&&(o.dataTypes=u);function d(f){o.data=f,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,f]}}wr.extendSubschemaData=n;function s(o,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:c,createErrors:l,allErrors:u}){c!==void 0&&(o.compositeRule=c),l!==void 0&&(o.createErrors=l),u!==void 0&&(o.allErrors=u),o.jtdDiscriminator=a,o.jtdMetadata=i}return wr.extendSubschemaMode=s,wr}var pt={},Ji,qd;function zd(){return qd||(qd=1,Ji=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var a=o[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}),Ji}var Wi={exports:{}},Dd;function I_(){if(Dd)return Wi.exports;Dd=1;var t=Wi.exports=function(n,s,o){typeof s=="function"&&(o=s,s={}),o=s.cb||o;var a=typeof o=="function"?o:o.pre||function(){},i=o.post||function(){};e(s,a,i,n,"",n)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function e(n,s,o,a,i,c,l,u,p,h){if(a&&typeof a=="object"&&!Array.isArray(a)){s(a,i,c,l,u,p,h);for(var d in a){var f=a[d];if(Array.isArray(f)){if(d in t.arrayKeywords)for(var v=0;v<f.length;v++)e(n,s,o,f[v],i+"/"+d+"/"+v,c,i,d,a,v)}else if(d in t.propsKeywords){if(f&&typeof f=="object")for(var y in f)e(n,s,o,f[y],i+"/"+d+"/"+r(y),c,i,d,a,y)}else(d in t.keywords||n.allKeys&&!(d in t.skipKeywords))&&e(n,s,o,f,i+"/"+d,c,i,d,a)}o(a,i,c,l,u,p,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Wi.exports}var Ud;function Lo(){if(Ud)return pt;Ud=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;const t=Ae(),e=zd(),r=I_(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(v,y=!0){return typeof v=="boolean"?!0:y===!0?!a(v):y?i(v)<=y:!1}pt.inlineRef=s;const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const y in v){if(o.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,t.eachItem)(v[w],g=>y+=i(g)),y===1/0))return 1/0}return y}function c(v,y="",w){w!==!1&&(y=p(y));const g=v.parse(y);return l(v,g)}pt.getFullPath=c;function l(v,y){return v.serialize(y).split("#")[0]+"#"}pt._getFullPath=l;const u=/#\/?$/;function p(v){return v?v.replace(u,""):""}pt.normalizeId=p;function h(v,y,w){return w=p(w),v.resolve(y,w)}pt.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function f(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:g}=this.opts,_=p(v[w]||y),b={"":_},k=c(g,_,!1),S={},C=new Set;return r(v,{allKeys:!0},(j,O,D,U)=>{if(U===void 0)return;const V=k+O;let ne=b[U];typeof j[w]=="string"&&(ne=fe.call(this,j[w])),de.call(this,j.$anchor),de.call(this,j.$dynamicAnchor),b[O]=ne;function fe(te){const ye=this.opts.uriResolver.resolve;if(te=p(ne?ye(ne,te):te),C.has(te))throw R(te);C.add(te);let H=this.refs[te];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(j,H.schema,te):te!==p(V)&&(te[0]==="#"?(x(j,S[te],te),S[te]=j):this.refs[te]=V),te}function de(te){if(typeof te=="string"){if(!d.test(te))throw new Error(`invalid anchor "${te}"`);fe.call(this,`#${te}`)}}}),S;function x(j,O,D){if(O!==void 0&&!e(j,O))throw R(D)}function R(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return pt.getSchemaRefs=f,pt}var Zd;function jo(){if(Zd)return _r;Zd=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.getData=_r.KeywordCxt=_r.validateFunctionCode=void 0;const t=T_(),e=No(),r=Od(),n=No(),s=$_(),o=E_(),a=x_(),i=Te(),c=Lr(),l=Lo(),u=Ae(),p=Mo();function h(A){if(k(A)&&(C(A),b(A))){y(A);return}d(A,()=>(0,t.topBoolOrEmptySchema)(A))}_r.validateFunctionCode=h;function d({gen:A,validateName:Z,schema:W,schemaEnv:K,opts:Q},ue){Q.code.es5?A.func(Z,(0,i._)`${c.default.data}, ${c.default.valCxt}`,K.$async,()=>{A.code((0,i._)`"use strict"; ${g(W,Q)}`),v(A,Q),A.code(ue)}):A.func(Z,(0,i._)`${c.default.data}, ${f(Q)}`,K.$async,()=>A.code(g(W,Q)).code(ue))}function f(A){return(0,i._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${A.dynamicRef?(0,i._)`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}function v(A,Z){A.if(c.default.valCxt,()=>{A.var(c.default.instancePath,(0,i._)`${c.default.valCxt}.${c.default.instancePath}`),A.var(c.default.parentData,(0,i._)`${c.default.valCxt}.${c.default.parentData}`),A.var(c.default.parentDataProperty,(0,i._)`${c.default.valCxt}.${c.default.parentDataProperty}`),A.var(c.default.rootData,(0,i._)`${c.default.valCxt}.${c.default.rootData}`),Z.dynamicRef&&A.var(c.default.dynamicAnchors,(0,i._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{A.var(c.default.instancePath,(0,i._)`""`),A.var(c.default.parentData,(0,i._)`undefined`),A.var(c.default.parentDataProperty,(0,i._)`undefined`),A.var(c.default.rootData,c.default.data),Z.dynamicRef&&A.var(c.default.dynamicAnchors,(0,i._)`{}`)})}function y(A){const{schema:Z,opts:W,gen:K}=A;d(A,()=>{W.$comment&&Z.$comment&&U(A),j(A),K.let(c.default.vErrors,null),K.let(c.default.errors,0),W.unevaluated&&w(A),x(A),V(A)})}function w(A){const{gen:Z,validateName:W}=A;A.evaluated=Z.const("evaluated",(0,i._)`${W}.evaluated`),Z.if((0,i._)`${A.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${A.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${A.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${A.evaluated}.items`,(0,i._)`undefined`))}function g(A,Z){const W=typeof A=="object"&&A[Z.schemaId];return W&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${W} */`:i.nil}function _(A,Z){if(k(A)&&(C(A),b(A))){S(A,Z);return}(0,t.boolOrEmptySchema)(A,Z)}function b({schema:A,self:Z}){if(typeof A=="boolean")return!A;for(const W in A)if(Z.RULES.all[W])return!0;return!1}function k(A){return typeof A.schema!="boolean"}function S(A,Z){const{schema:W,gen:K,opts:Q}=A;Q.$comment&&W.$comment&&U(A),O(A),D(A);const ue=K.const("_errs",c.default.errors);x(A,ue),K.var(Z,(0,i._)`${ue} === ${c.default.errors}`)}function C(A){(0,u.checkUnknownRules)(A),R(A)}function x(A,Z){if(A.opts.jtd)return fe(A,[],!1,Z);const W=(0,e.getSchemaTypes)(A.schema),K=(0,e.coerceAndCheckDataType)(A,W);fe(A,W,!K,Z)}function R(A){const{schema:Z,errSchemaPath:W,opts:K,self:Q}=A;Z.$ref&&K.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,Q.RULES)&&Q.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function j(A){const{schema:Z,opts:W}=A;Z.default!==void 0&&W.useDefaults&&W.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function O(A){const Z=A.schema[A.opts.schemaId];Z&&(A.baseId=(0,l.resolveUrl)(A.opts.uriResolver,A.baseId,Z))}function D(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:A,schemaEnv:Z,schema:W,errSchemaPath:K,opts:Q}){const ue=W.$comment;if(Q.$comment===!0)A.code((0,i._)`${c.default.self}.logger.log(${ue})`);else if(typeof Q.$comment=="function"){const he=(0,i.str)`${K}/$comment`,Ve=A.scopeValue("root",{ref:Z.root});A.code((0,i._)`${c.default.self}.opts.$comment(${ue}, ${he}, ${Ve}.schema)`)}}function V(A){const{gen:Z,schemaEnv:W,validateName:K,ValidationError:Q,opts:ue}=A;W.$async?Z.if((0,i._)`${c.default.errors} === 0`,()=>Z.return(c.default.data),()=>Z.throw((0,i._)`new ${Q}(${c.default.vErrors})`)):(Z.assign((0,i._)`${K}.errors`,c.default.vErrors),ue.unevaluated&&ne(A),Z.return((0,i._)`${c.default.errors} === 0`))}function ne({gen:A,evaluated:Z,props:W,items:K}){W instanceof i.Name&&A.assign((0,i._)`${Z}.props`,W),K instanceof i.Name&&A.assign((0,i._)`${Z}.items`,K)}function fe(A,Z,W,K){const{gen:Q,schema:ue,data:he,allErrors:Ve,opts:Be,self:X}=A,{RULES:ke}=X;if(ue.$ref&&(Be.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ue,ke))){Q.block(()=>B(A,"$ref",ke.all.$ref.definition));return}Be.jtd||te(A,Z),Q.block(()=>{for(const Ee of ke.rules)wt(Ee);wt(ke.post)});function wt(Ee){(0,r.shouldUseGroup)(ue,Ee)&&(Ee.type?(Q.if((0,n.checkDataType)(Ee.type,he,Be.strictNumbers)),de(A,Ee),Z.length===1&&Z[0]===Ee.type&&W&&(Q.else(),(0,n.reportTypeError)(A)),Q.endIf()):de(A,Ee),Ve||Q.if((0,i._)`${c.default.errors} === ${K||0}`))}}function de(A,Z){const{gen:W,schema:K,opts:{useDefaults:Q}}=A;Q&&(0,s.assignDefaults)(A,Z.type),W.block(()=>{for(const ue of Z.rules)(0,r.shouldUseRule)(K,ue)&&B(A,ue.keyword,ue.definition,Z.type)})}function te(A,Z){A.schemaEnv.meta||!A.opts.strictTypes||(ye(A,Z),A.opts.allowUnionTypes||H(A,Z),P(A,A.dataTypes))}function ye(A,Z){if(Z.length){if(!A.dataTypes.length){A.dataTypes=Z;return}Z.forEach(W=>{q(A.dataTypes,W)||I(A,`type "${W}" not allowed by context "${A.dataTypes.join(",")}"`)}),E(A,Z)}}function H(A,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&I(A,"use allowUnionTypes to allow union type keyword")}function P(A,Z){const W=A.self.RULES.all;for(const K in W){const Q=W[K];if(typeof Q=="object"&&(0,r.shouldUseRule)(A.schema,Q)){const{type:ue}=Q.definition;ue.length&&!ue.some(he=>F(Z,he))&&I(A,`missing type "${ue.join(",")}" for keyword "${K}"`)}}}function F(A,Z){return A.includes(Z)||Z==="number"&&A.includes("integer")}function q(A,Z){return A.includes(Z)||Z==="integer"&&A.includes("number")}function E(A,Z){const W=[];for(const K of A.dataTypes)q(Z,K)?W.push(K):Z.includes("integer")&&K==="number"&&W.push("integer");A.dataTypes=W}function I(A,Z){const W=A.schemaEnv.baseId+A.errSchemaPath;Z+=` at "${W}" (strictTypes)`,(0,u.checkStrictMode)(A,Z,A.opts.strictTypes)}class ${constructor(Z,W,K){if((0,o.validateKeywordUsage)(Z,W,K),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=K,this.data=Z.data,this.schema=Z.schema[K],this.$data=W.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,K,this.$data),this.schemaType=W.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=W,this.$data)this.schemaCode=Z.gen.const("vSchema",pe(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,W.schemaType,W.allowUndefined))throw new Error(`${K} value must be ${JSON.stringify(W.schemaType)}`);("code"in W?W.trackErrors:W.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",c.default.errors))}result(Z,W,K){this.failResult((0,i.not)(Z),W,K)}failResult(Z,W,K){this.gen.if(Z),K?K():this.error(),W?(this.gen.else(),W(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,W){this.failResult((0,i.not)(Z),void 0,W)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:W}=this;this.fail((0,i._)`${W} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,W,K){if(W){this.setParams(W),this._error(Z,K),this.setParams({});return}this._error(Z,K)}_error(Z,W){(Z?p.reportExtraError:p.reportError)(this,this.def.error,W)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,W){W?Object.assign(this.params,Z):this.params=Z}block$data(Z,W,K=i.nil){this.gen.block(()=>{this.check$data(Z,K),W()})}check$data(Z=i.nil,W=i.nil){if(!this.$data)return;const{gen:K,schemaCode:Q,schemaType:ue,def:he}=this;K.if((0,i.or)((0,i._)`${Q} === undefined`,W)),Z!==i.nil&&K.assign(Z,!0),(ue.length||he.validateSchema)&&(K.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&K.assign(Z,!1)),K.else()}invalid$data(){const{gen:Z,schemaCode:W,schemaType:K,def:Q,it:ue}=this;return(0,i.or)(he(),Ve());function he(){if(K.length){if(!(W instanceof i.Name))throw new Error("ajv implementation error");const Be=Array.isArray(K)?K:[K];return(0,i._)`${(0,n.checkDataTypes)(Be,W,ue.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Ve(){if(Q.validateSchema){const Be=Z.scopeValue("validate$data",{ref:Q.validateSchema});return(0,i._)`!${Be}(${W})`}return i.nil}}subschema(Z,W){const K=(0,a.getSubschema)(this.it,Z);(0,a.extendSubschemaData)(K,this.it,Z),(0,a.extendSubschemaMode)(K,Z);const Q={...this.it,...K,items:void 0,props:void 0};return _(Q,W),Q}mergeEvaluated(Z,W){const{it:K,gen:Q}=this;K.opts.unevaluated&&(K.props!==!0&&Z.props!==void 0&&(K.props=u.mergeEvaluated.props(Q,Z.props,K.props,W)),K.items!==!0&&Z.items!==void 0&&(K.items=u.mergeEvaluated.items(Q,Z.items,K.items,W)))}mergeValidEvaluated(Z,W){const{it:K,gen:Q}=this;if(K.opts.unevaluated&&(K.props!==!0||K.items!==!0))return Q.if(W,()=>this.mergeEvaluated(Z,i.Name)),!0}}_r.KeywordCxt=$;function B(A,Z,W,K){const Q=new $(A,W,Z);"code"in W?W.code(Q,K):Q.$data&&W.validate?(0,o.funcKeywordCode)(Q,W):"macro"in W?(0,o.macroKeywordCode)(Q,W):(W.compile||W.validate)&&(0,o.funcKeywordCode)(Q,W)}const G=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(A,{dataLevel:Z,dataNames:W,dataPathArr:K}){let Q,ue;if(A==="")return c.default.rootData;if(A[0]==="/"){if(!G.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);Q=A,ue=c.default.rootData}else{const X=_e.exec(A);if(!X)throw new Error(`Invalid JSON-pointer: ${A}`);const ke=+X[1];if(Q=X[2],Q==="#"){if(ke>=Z)throw new Error(Be("property/index",ke));return K[Z-ke]}if(ke>Z)throw new Error(Be("data",ke));if(ue=W[Z-ke],!Q)return ue}let he=ue;const Ve=Q.split("/");for(const X of Ve)X&&(ue=(0,i._)`${ue}${(0,i.getProperty)((0,u.unescapeJsonPointer)(X))}`,he=(0,i._)`${he} && ${ue}`);return he;function Be(X,ke){return`Cannot access ${X} ${ke} levels up, current level is ${Z}`}}return _r.getData=pe,_r}var qo={},Fd;function Gi(){if(Fd)return qo;Fd=1,Object.defineProperty(qo,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return qo.default=t,qo}var zo={},Vd;function Do(){if(Vd)return zo;Vd=1,Object.defineProperty(zo,"__esModule",{value:!0});const t=Lo();class e extends Error{constructor(n,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,o),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return zo.default=e,zo}var xt={},Hd;function Ki(){if(Hd)return xt;Hd=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.resolveSchema=xt.getCompilingSchema=xt.resolveRef=xt.compileSchema=xt.SchemaEnv=void 0;const t=Te(),e=Gi(),r=Lr(),n=Lo(),s=Ae(),o=jo();class a{constructor(w){var g;this.refs={},this.dynamicAnchors={};let _;typeof w.schema=="object"&&(_=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(g=w.baseId)!==null&&g!==void 0?g:(0,n.normalizeId)(_?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=_?.$async,this.refs={}}}xt.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const g=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:_,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new t.CodeGen(this.scope,{es5:_,lines:b,ownProperties:k});let C;y.$async&&(C=S.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const x=S.scopeName("validate");y.validateName=x;const R={gen:S,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:S.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,t.stringify)(y.schema)}:{ref:y.schema}),validateName:x,ValidationError:C,schema:y.schema,schemaEnv:y,rootId:g,baseId:y.baseId||g,schemaPath:t.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,o.validateFunctionCode)(R),S.optimize(this.opts.code.optimize);const O=S.toString();j=`${S.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const U=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(x,{ref:U}),U.errors=null,U.schema=y.schema,U.schemaEnv=y,y.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:x,validateCode:O,scopeValues:S._values}),this.opts.unevaluated){const{props:V,items:ne}=R;U.evaluated={props:V instanceof t.Name?void 0:V,items:ne instanceof t.Name?void 0:ne,dynamicProps:V instanceof t.Name,dynamicItems:ne instanceof t.Name},U.source&&(U.source.evaluated=(0,t.stringify)(U.evaluated))}return y.validate=U,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)}}xt.compileSchema=i;function c(y,w,g){var _;g=(0,n.resolveUrl)(this.opts.uriResolver,w,g);const b=y.refs[g];if(b)return b;let k=h.call(this,y,g);if(k===void 0){const S=(_=y.localRefs)===null||_===void 0?void 0:_[g],{schemaId:C}=this.opts;S&&(k=new a({schema:S,schemaId:C,root:y,baseId:w}))}if(k!==void 0)return y.refs[g]=l.call(this,k)}xt.resolveRef=c;function l(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(p(w,y))return w}xt.getCompilingSchema=u;function p(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function h(y,w){let g;for(;typeof(g=this.refs[w])=="string";)w=g;return g||this.schemas[w]||d.call(this,y,w)}function d(y,w){const g=this.opts.uriResolver.parse(w),_=(0,n._getFullPath)(this.opts.uriResolver,g);let b=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&_===b)return v.call(this,g,y);const k=(0,n.normalizeId)(_),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const C=d.call(this,y,S);return typeof C?.schema!="object"?void 0:v.call(this,g,C)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(w)){const{schema:C}=S,{schemaId:x}=this.opts,R=C[x];return R&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,R)),new a({schema:C,schemaId:x,root:y,baseId:b})}return v.call(this,g,S)}}xt.resolveSchema=d;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:g,root:_}){var b;if(((b=y.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const C of y.fragment.slice(1).split("/")){if(typeof g=="boolean")return;const x=g[(0,s.unescapeFragment)(C)];if(x===void 0)return;g=x;const R=typeof g=="object"&&g[this.opts.schemaId];!f.has(C)&&R&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,R))}let k;if(typeof g!="boolean"&&g.$ref&&!(0,s.schemaHasRulesButRef)(g,this.RULES)){const C=(0,n.resolveUrl)(this.opts.uriResolver,w,g.$ref);k=d.call(this,_,C)}const{schemaId:S}=this.opts;if(k=k||new a({schema:g,schemaId:S,root:_,baseId:w}),k.schema!==k.root.schema)return k}return xt}const R_={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Uo={},hs={exports:{}},Yi,Bd;function Jd(){if(Bd)return Yi;Bd=1;const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),e=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(h){let d="",f=0,v=0;for(v=0;v<h.length;v++)if(f=h[v].charCodeAt(0),f!==48){if(!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[v];break}for(v+=1;v<h.length;v++){if(f=h[v].charCodeAt(0),!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[v]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(h){return h.length=0,!0}function o(h,d,f){if(h.length){const v=r(h);if(v!=="")d.push(v);else return f.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const f={error:!1,address:"",zone:""},v=[],y=[];let w=!1,g=!1,_=o;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(g=!0),!_(y,v,f))break;if(++d>7){f.error=!0;break}b>0&&h[b-1]===":"&&(w=!0),v.push(":");continue}else if(k==="%"){if(!_(y,v,f))break;_=s}else{y.push(k);continue}}return y.length&&(_===s?f.zone=y.join(""):g?v.push(y.join("")):v.push(r(y))),f.address=v.join(""),f}function i(h){if(c(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let f=d.address,v=d.address;return d.zone&&(f+="%"+d.zone,v+="%25"+d.zone),{host:f,isIPV6:!0,escapedHost:v}}}function c(h,d){let f=0;for(let v=0;v<h.length;v++)h[v]===d&&f++;return f}function l(h){let d=h;const f=[];let v=-1,y=0;for(;y=d.length;){if(y===1){if(d===".")break;if(d==="/"){f.push("/");break}else{f.push(d);break}}else if(y===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){f.push("/");break}}else if(y===3&&d==="/.."){f.length!==0&&f.pop(),f.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),f.length!==0&&f.pop();continue}}if((v=d.indexOf("/",1))===-1){f.push(d);break}else f.push(d.slice(0,v)),d=d.slice(v)}return f.join("")}function u(h,d){const f=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=f(h.scheme)),h.userinfo!==void 0&&(h.userinfo=f(h.userinfo)),h.host!==void 0&&(h.host=f(h.host)),h.path!==void 0&&(h.path=f(h.path)),h.query!==void 0&&(h.query=f(h.query)),h.fragment!==void 0&&(h.fragment=f(h.fragment)),h}function p(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let f=unescape(h.host);if(!e(f)){const v=i(f);v.isIPV6===!0?f=`[${v.escapedHost}]`:f=h.host}d.push(f)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return Yi={nonSimpleDomain:n,recomposeAuthority:p,normalizeComponentEncoding:u,removeDotSegments:l,isIPv4:e,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:r},Yi}var Qi,Wd;function P_(){if(Wd)return Qi;Wd=1;const{isUUID:t}=Jd(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function s(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function o(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=s(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function c(k){if((k.port===(s(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[S,C]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=C,k.resourceName=void 0}return k.fragment=void 0,k}function l(k,S){if(!k.path)return k.error="URN can not be parsed",k;const C=k.path.match(e);if(C){const x=S.scheme||k.scheme||"urn";k.nid=C[1].toLowerCase(),k.nss=C[2];const R=`${x}:${S.nid||k.nid}`,j=b(R);k.path=void 0,j&&(k=j.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const C=S.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),R=`${C}:${S.nid||x}`,j=b(R);j&&(k=j.serialize(k,S));const O=k,D=k.nss;return O.path=`${x||S.nid}:${D}`,S.skipEscape=!0,O}function p(k,S){const C=k;return C.uuid=C.nss,C.nss=void 0,!S.tolerant&&(!C.uuid||!t(C.uuid))&&(C.error=C.error||"UUID is not valid."),C}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:o,serialize:a},f={scheme:"https",domainHost:d.domainHost,parse:o,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:c},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},_={http:d,https:f,ws:v,wss:y,urn:{scheme:"urn",parse:l,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:p,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(_,null);function b(k){return k&&(_[k]||_[k.toLowerCase()])||void 0}return Qi={wsIsSecure:s,SCHEMES:_,isValidSchemeName:n,getSchemeHandler:b},Qi}var Gd;function O_(){if(Gd)return hs.exports;Gd=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:o}=Jd(),{SCHEMES:a,getSchemeHandler:i}=P_();function c(y,w){return typeof y=="string"?y=h(f(y,w),w):typeof y=="object"&&(y=f(h(y,w),w)),y}function l(y,w,g){const _=g?Object.assign({scheme:"null"},g):{scheme:"null"},b=u(f(y,_),f(w,_),_,!0);return _.skipEscape=!0,h(b,_)}function u(y,w,g,_){const b={};return _||(y=f(h(y,g),g),w=f(h(w,g),g)),g=g||{},!g.tolerant&&w.scheme?(b.scheme=w.scheme,b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=e(w.path||""),b.query=w.query):(w.path?(w.path[0]==="/"?b.path=e(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?b.path="/"+w.path:y.path?b.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:b.path=w.path,b.path=e(b.path)),b.query=w.query):(b.path=y.path,w.query!==void 0?b.query=w.query:b.query=y.query),b.userinfo=y.userinfo,b.host=y.host,b.port=y.port),b.scheme=y.scheme),b.fragment=w.fragment,b}function p(y,w,g){return typeof y=="string"?(y=unescape(y),y=h(n(f(y,g),!0),{...g,skipEscape:!0})):typeof y=="object"&&(y=h(n(y,!0),{...g,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=h(n(f(w,g),!0),{...g,skipEscape:!0})):typeof w=="object"&&(w=h(n(w,!0),{...g,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function h(y,w){const g={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:""},_=Object.assign({},w),b=[],k=i(_.scheme||g.scheme);k&&k.serialize&&k.serialize(g,_),g.path!==void 0&&(_.skipEscape?g.path=unescape(g.path):(g.path=escape(g.path),g.scheme!==void 0&&(g.path=g.path.split("%3A").join(":")))),_.reference!=="suffix"&&g.scheme&&b.push(g.scheme,":");const S=r(g);if(S!==void 0&&(_.reference!=="suffix"&&b.push("//"),b.push(S),g.path&&g.path[0]!=="/"&&b.push("/")),g.path!==void 0){let C=g.path;!_.absolutePath&&(!k||!k.absolutePath)&&(C=e(C)),S===void 0&&C[0]==="/"&&C[1]==="/"&&(C="/%2F"+C.slice(2)),b.push(C)}return g.query!==void 0&&b.push("?",g.query),g.fragment!==void 0&&b.push("#",g.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(y,w){const g=Object.assign({},w),_={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;g.reference==="suffix"&&(g.scheme?y=g.scheme+":"+y:y="//"+y);const k=y.match(d);if(k){if(_.scheme=k[1],_.userinfo=k[3],_.host=k[4],_.port=parseInt(k[5],10),_.path=k[6]||"",_.query=k[7],_.fragment=k[8],isNaN(_.port)&&(_.port=k[5]),_.host)if(s(_.host)===!1){const x=t(_.host);_.host=x.host.toLowerCase(),b=x.isIPV6}else b=!0;_.scheme===void 0&&_.userinfo===void 0&&_.host===void 0&&_.port===void 0&&_.query===void 0&&!_.path?_.reference="same-document":_.scheme===void 0?_.reference="relative":_.fragment===void 0?_.reference="absolute":_.reference="uri",g.reference&&g.reference!=="suffix"&&g.reference!==_.reference&&(_.error=_.error||"URI is not a "+g.reference+" reference.");const S=i(g.scheme||_.scheme);if(!g.unicodeSupport&&(!S||!S.unicodeSupport)&&_.host&&(g.domainHost||S&&S.domainHost)&&b===!1&&o(_.host))try{_.host=URL.domainToASCII(_.host.toLowerCase())}catch(C){_.error=_.error||"Host's domain name can not be converted to ASCII: "+C}(!S||S&&!S.skipNormalize)&&(y.indexOf("%")!==-1&&(_.scheme!==void 0&&(_.scheme=unescape(_.scheme)),_.host!==void 0&&(_.host=unescape(_.host))),_.path&&(_.path=escape(unescape(_.path))),_.fragment&&(_.fragment=encodeURI(decodeURIComponent(_.fragment)))),S&&S.parse&&S.parse(_,g)}else _.error=_.error||"URI can not be parsed.";return _}const v={SCHEMES:a,normalize:c,resolve:l,resolveComponent:u,equal:p,serialize:h,parse:f};return hs.exports=v,hs.exports.default=v,hs.exports.fastUri=v,hs.exports}var Kd;function A_(){if(Kd)return Uo;Kd=1,Object.defineProperty(Uo,"__esModule",{value:!0});const t=O_();return t.code='require("ajv/dist/runtime/uri").default',Uo.default=t,Uo}var Yd;function M_(){return Yd||(Yd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=jo();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Te();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Gi(),s=Do(),o=Rd(),a=Ki(),i=Te(),c=Lo(),l=No(),u=Ae(),p=R_,h=A_(),d=(H,P)=>new RegExp(H,P);d.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),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.'},g=200;function _(H){var P,F,q,E,I,$,B,G,_e,pe,A,Z,W,K,Q,ue,he,Ve,Be,X,ke,wt,Ee,$t,Or;const Et=H.strict,ct=(P=H.code)===null||P===void 0?void 0:P.optimize,Zt=ct===!0||ct===void 0?1:ct||0,en=(q=(F=H.code)===null||F===void 0?void 0:F.regExp)!==null&&q!==void 0?q:d,tn=(E=H.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(I=H.strictSchema)!==null&&I!==void 0?I:Et)!==null&&$!==void 0?$:!0,strictNumbers:(G=(B=H.strictNumbers)!==null&&B!==void 0?B:Et)!==null&&G!==void 0?G:!0,strictTypes:(pe=(_e=H.strictTypes)!==null&&_e!==void 0?_e:Et)!==null&&pe!==void 0?pe:"log",strictTuples:(Z=(A=H.strictTuples)!==null&&A!==void 0?A:Et)!==null&&Z!==void 0?Z:"log",strictRequired:(K=(W=H.strictRequired)!==null&&W!==void 0?W:Et)!==null&&K!==void 0?K:!1,code:H.code?{...H.code,optimize:Zt,regExp:en}:{optimize:Zt,regExp:en},loopRequired:(Q=H.loopRequired)!==null&&Q!==void 0?Q:g,loopEnum:(ue=H.loopEnum)!==null&&ue!==void 0?ue:g,meta:(he=H.meta)!==null&&he!==void 0?he:!0,messages:(Ve=H.messages)!==null&&Ve!==void 0?Ve:!0,inlineRefs:(Be=H.inlineRefs)!==null&&Be!==void 0?Be:!0,schemaId:(X=H.schemaId)!==null&&X!==void 0?X:"$id",addUsedSchema:(ke=H.addUsedSchema)!==null&&ke!==void 0?ke:!0,validateSchema:(wt=H.validateSchema)!==null&&wt!==void 0?wt:!0,validateFormats:(Ee=H.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:($t=H.unicodeRegExp)!==null&&$t!==void 0?$t:!0,int32range:(Or=H.int32range)!==null&&Or!==void 0?Or:!0,uriResolver:tn}}class b{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,..._(P)};const{es5:F,lines:q}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:F,lines:q}),this.logger=D(P.logger);const E=P.validateFormats;P.validateFormats=!1,this.RULES=(0,o.getRules)(),k.call(this,y,P,"NOT SUPPORTED"),k.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&R.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),C.call(this),P.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:F,schemaId:q}=this.opts;let E=p;q==="id"&&(E={...p},E.id=E.$id,delete E.$id),F&&P&&this.addMetaSchema(E,E[q],!1)}defaultMeta(){const{meta:P,schemaId:F}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[F]||P:void 0}validate(P,F){let q;if(typeof P=="string"){if(q=this.getSchema(P),!q)throw new Error(`no schema with key or ref "${P}"`)}else q=this.compile(P);const E=q(F);return"$async"in q||(this.errors=q.errors),E}compile(P,F){const q=this._addSchema(P,F);return q.validate||this._compileSchemaEnv(q)}compileAsync(P,F){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:q}=this.opts;return E.call(this,P,F);async function E(pe,A){await I.call(this,pe.$schema);const Z=this._addSchema(pe,A);return Z.validate||$.call(this,Z)}async function I(pe){pe&&!this.getSchema(pe)&&await E.call(this,{$ref:pe},!0)}async function $(pe){try{return this._compileSchemaEnv(pe)}catch(A){if(!(A instanceof s.default))throw A;return B.call(this,A),await G.call(this,A.missingSchema),$.call(this,pe)}}function B({missingSchema:pe,missingRef:A}){if(this.refs[pe])throw new Error(`AnySchema ${pe} is loaded but ${A} cannot be resolved`)}async function G(pe){const A=await _e.call(this,pe);this.refs[pe]||await I.call(this,A.$schema),this.refs[pe]||this.addSchema(A,pe,F)}async function _e(pe){const A=this._loading[pe];if(A)return A;try{return await(this._loading[pe]=q(pe))}finally{delete this._loading[pe]}}}addSchema(P,F,q,E=this.opts.validateSchema){if(Array.isArray(P)){for(const $ of P)this.addSchema($,void 0,q,E);return this}let I;if(typeof P=="object"){const{schemaId:$}=this.opts;if(I=P[$],I!==void 0&&typeof I!="string")throw new Error(`schema ${$} must be string`)}return F=(0,c.normalizeId)(F||I),this._checkUnique(F),this.schemas[F]=this._addSchema(P,q,F,E,!0),this}addMetaSchema(P,F,q=this.opts.validateSchema){return this.addSchema(P,F,!0,q),this}validateSchema(P,F){if(typeof P=="boolean")return!0;let q;if(q=P.$schema,q!==void 0&&typeof q!="string")throw new Error("$schema must be a string");if(q=q||this.opts.defaultMeta||this.defaultMeta(),!q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(q,P);if(!E&&F){const I="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(I);else throw new Error(I)}return E}getSchema(P){let F;for(;typeof(F=S.call(this,P))=="string";)P=F;if(F===void 0){const{schemaId:q}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:q});if(F=a.resolveSchema.call(this,E,P),!F)return;this.refs[P]=F}return F.validate||this._compileSchemaEnv(F)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const F=S.call(this,P);return typeof F=="object"&&this._cache.delete(F.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const F=P;this._cache.delete(F);let q=P[this.opts.schemaId];return q&&(q=(0,c.normalizeId)(q),delete this.schemas[q],delete this.refs[q]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(P){for(const F of P)this.addKeyword(F);return this}addKeyword(P,F){let q;if(typeof P=="string")q=P,typeof F=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),F.keyword=q);else if(typeof P=="object"&&F===void 0){if(F=P,q=F.keyword,Array.isArray(q)&&!q.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(V.call(this,q,F),!F)return(0,u.eachItem)(q,I=>ne.call(this,I)),this;de.call(this,F);const E={...F,type:(0,l.getJSONTypes)(F.type),schemaType:(0,l.getJSONTypes)(F.schemaType)};return(0,u.eachItem)(q,E.type.length===0?I=>ne.call(this,I,E):I=>E.type.forEach($=>ne.call(this,I,E,$))),this}getKeyword(P){const F=this.RULES.all[P];return typeof F=="object"?F.definition:!!F}removeKeyword(P){const{RULES:F}=this;delete F.keywords[P],delete F.all[P];for(const q of F.rules){const E=q.rules.findIndex(I=>I.keyword===P);E>=0&&q.rules.splice(E,1)}return this}addFormat(P,F){return typeof F=="string"&&(F=new RegExp(F)),this.formats[P]=F,this}errorsText(P=this.errors,{separator:F=", ",dataVar:q="data"}={}){return!P||P.length===0?"No errors":P.map(E=>`${q}${E.instancePath} ${E.message}`).reduce((E,I)=>E+F+I)}$dataMetaSchema(P,F){const q=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const E of F){const I=E.split("/").slice(1);let $=P;for(const B of I)$=$[B];for(const B in q){const G=q[B];if(typeof G!="object")continue;const{$data:_e}=G.definition,pe=$[B];_e&&pe&&($[B]=ye(pe))}}return P}_removeAllSchemas(P,F){for(const q in P){const E=P[q];(!F||F.test(q))&&(typeof E=="string"?delete P[q]:E&&!E.meta&&(this._cache.delete(E.schema),delete P[q]))}}_addSchema(P,F,q,E=this.opts.validateSchema,I=this.opts.addUsedSchema){let $;const{schemaId:B}=this.opts;if(typeof P=="object")$=P[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let G=this._cache.get(P);if(G!==void 0)return G;q=(0,c.normalizeId)($||q);const _e=c.getSchemaRefs.call(this,P,q);return G=new a.SchemaEnv({schema:P,schemaId:B,meta:F,baseId:q,localRefs:_e}),this._cache.set(G.schema,G),I&&!q.startsWith("#")&&(q&&this._checkUnique(q),this.refs[q]=G),E&&this.validateSchema(P,!0),G}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){const F=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=F}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function k(H,P,F,q="error"){for(const E in H){const I=E;I in P&&this.logger[q](`${F}: option ${E}. ${H[I]}`)}}function S(H){return H=(0,c.normalizeId)(H),this.schemas[H]||this.refs[H]}function C(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const P in H)this.addSchema(H[P],P)}function x(){for(const H in this.opts.formats){const P=this.opts.formats[H];P&&this.addFormat(H,P)}}function R(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in H){const F=H[P];F.keyword||(F.keyword=P),this.addKeyword(F)}}function j(){const H={...this.opts};for(const P of f)delete H[P];return H}const O={log(){},warn(){},error(){}};function D(H){if(H===!1)return O;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function V(H,P){const{RULES:F}=this;if((0,u.eachItem)(H,q=>{if(F.keywords[q])throw new Error(`Keyword ${q} is already defined`);if(!U.test(q))throw new Error(`Keyword ${q} has invalid name`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function ne(H,P,F){var q;const E=P?.post;if(F&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:I}=this;let $=E?I.post:I.rules.find(({type:G})=>G===F);if($||($={type:F,rules:[]},I.rules.push($)),I.keywords[H]=!0,!P)return;const B={keyword:H,definition:{...P,type:(0,l.getJSONTypes)(P.type),schemaType:(0,l.getJSONTypes)(P.schemaType)}};P.before?fe.call(this,$,B,P.before):$.rules.push(B),I.all[H]=B,(q=P.implements)===null||q===void 0||q.forEach(G=>this.addKeyword(G))}function fe(H,P,F){const q=H.rules.findIndex(E=>E.keyword===F);q>=0?H.rules.splice(q,0,P):(H.rules.push(P),this.logger.warn(`rule ${F} is not defined`))}function de(H){let{metaSchema:P}=H;P!==void 0&&(H.$data&&this.opts.$data&&(P=ye(P)),H.validateSchema=this.compile(P,!0))}const te={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ye(H){return{anyOf:[H,te]}}})(Zi)),Zi}var Zo={},Fo={},Vo={},Qd;function N_(){if(Qd)return Vo;Qd=1,Object.defineProperty(Vo,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Vo.default=t,Vo}var jr={},Xd;function L_(){if(Xd)return jr;Xd=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.callRef=jr.getValidate=void 0;const t=Do(),e=Vt(),r=Te(),n=Lr(),s=Ki(),o=Ae(),a={keyword:"$ref",schemaType:"string",code(l){const{gen:u,schema:p,it:h}=l,{baseId:d,schemaEnv:f,validateName:v,opts:y,self:w}=h,{root:g}=f;if((p==="#"||p==="#/")&&d===g.baseId)return b();const _=s.resolveRef.call(w,g,d,p);if(_===void 0)throw new t.default(h.opts.uriResolver,d,p);if(_ instanceof s.SchemaEnv)return k(_);return S(_);function b(){if(f===g)return c(l,v,f,f.$async);const C=u.scopeValue("root",{ref:g});return c(l,(0,r._)`${C}.validate`,g,g.$async)}function k(C){const x=i(l,C);c(l,x,C,C.$async)}function S(C){const x=u.scopeValue("schema",y.code.source===!0?{ref:C,code:(0,r.stringify)(C)}:{ref:C}),R=u.name("valid"),j=l.subschema({schema:C,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:p},R);l.mergeEvaluated(j),l.ok(R)}}};function i(l,u){const{gen:p}=l;return u.validate?p.scopeValue("validate",{ref:u.validate}):(0,r._)`${p.scopeValue("wrapper",{ref:u})}.validate`}jr.getValidate=i;function c(l,u,p,h){const{gen:d,it:f}=l,{allErrors:v,schemaEnv:y,opts:w}=f,g=w.passContext?n.default.this:r.nil;h?_():b();function _(){if(!y.$async)throw new Error("async schema referenced by sync schema");const C=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,e.callValidateCode)(l,u,g)}`),S(u),v||d.assign(C,!0)},x=>{d.if((0,r._)`!(${x} instanceof ${f.ValidationError})`,()=>d.throw(x)),k(x),v||d.assign(C,!1)}),l.ok(C)}function b(){l.result((0,e.callValidateCode)(l,u,g),()=>S(u),()=>k(u))}function k(C){const x=(0,r._)`${C}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(C){var x;if(!f.opts.unevaluated)return;const R=(x=p?.validate)===null||x===void 0?void 0:x.evaluated;if(f.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(f.props=o.mergeEvaluated.props(d,R.props,f.props));else{const j=d.var("props",(0,r._)`${C}.evaluated.props`);f.props=o.mergeEvaluated.props(d,j,f.props,r.Name)}if(f.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(f.items=o.mergeEvaluated.items(d,R.items,f.items));else{const j=d.var("items",(0,r._)`${C}.evaluated.items`);f.items=o.mergeEvaluated.items(d,j,f.items,r.Name)}}}return jr.callRef=c,jr.default=a,jr}var ep;function j_(){if(ep)return Fo;ep=1,Object.defineProperty(Fo,"__esModule",{value:!0});const t=N_(),e=L_(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return Fo.default=r,Fo}var Ho={},Bo={},tp;function q_(){if(tp)return Bo;tp=1,Object.defineProperty(Bo,"__esModule",{value:!0});const t=Te(),e=t.operators,r={maximum:{okStr:"<=",ok:e.LTE,fail:e.GT},minimum:{okStr:">=",ok:e.GTE,fail:e.LT},exclusiveMaximum:{okStr:"<",ok:e.LT,fail:e.GTE},exclusiveMinimum:{okStr:">",ok:e.GT,fail:e.LTE}},n={message:({keyword:o,schemaCode:a})=>(0,t.str)`must be ${r[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,t._)`{comparison: ${r[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(o){const{keyword:a,data:i,schemaCode:c}=o;o.fail$data((0,t._)`${i} ${r[a].fail} ${c} || isNaN(${i})`)}};return Bo.default=s,Bo}var Jo={},rp;function z_(){if(rp)return Jo;rp=1,Object.defineProperty(Jo,"__esModule",{value:!0});const t=Te(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){const{gen:s,data:o,schemaCode:a,it:i}=n,c=i.opts.multipleOfPrecision,l=s.let("res"),u=c?(0,t._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${c}`:(0,t._)`${l} !== parseInt(${l})`;n.fail$data((0,t._)`(${a} === 0 || (${l} = ${o}/${a}, ${u}))`)}};return Jo.default=r,Jo}var Wo={},Go={},np;function D_(){if(np)return Go;np=1,Object.defineProperty(Go,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,o;for(;s<r;)n++,o=e.charCodeAt(s++),o>=55296&&o<=56319&&s<r&&(o=e.charCodeAt(s),(o&64512)===56320&&s++);return n}return Go.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',Go}var sp;function U_(){if(sp)return Wo;sp=1,Object.defineProperty(Wo,"__esModule",{value:!0});const t=Te(),e=Ae(),r=D_(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:o,schemaCode:a}){const i=o==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:o})=>(0,t._)`{limit: ${o}}`},code(o){const{keyword:a,data:i,schemaCode:c,it:l}=o,u=a==="maxLength"?t.operators.GT:t.operators.LT,p=l.opts.unicode===!1?(0,t._)`${i}.length`:(0,t._)`${(0,e.useFunc)(o.gen,r.default)}(${i})`;o.fail$data((0,t._)`${p} ${u} ${c}`)}};return Wo.default=s,Wo}var Ko={},op;function Z_(){if(op)return Ko;op=1,Object.defineProperty(Ko,"__esModule",{value:!0});const t=Vt(),e=Te(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,e.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,e._)`{pattern: ${s}}`},code(s){const{data:o,$data:a,schema:i,schemaCode:c,it:l}=s,u=l.opts.unicodeRegExp?"u":"",p=a?(0,e._)`(new RegExp(${c}, ${u}))`:(0,t.usePattern)(s,i);s.fail$data((0,e._)`!${p}.test(${o})`)}};return Ko.default=n,Ko}var Yo={},ap;function F_(){if(ap)return Yo;ap=1,Object.defineProperty(Yo,"__esModule",{value:!0});const t=Te(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${o}).length ${i} ${a}`)}};return Yo.default=r,Yo}var Qo={},ip;function V_(){if(ip)return Qo;ip=1,Object.defineProperty(Qo,"__esModule",{value:!0});const t=Vt(),e=Te(),r=Ae(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:o}})=>(0,e.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,e._)`{missingProperty: ${o}}`},code(o){const{gen:a,schema:i,schemaCode:c,data:l,$data:u,it:p}=o,{opts:h}=p;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(p.allErrors?f():v(),h.strictRequired){const g=o.parentSchema.properties,{definedProperties:_}=o.it;for(const b of i)if(g?.[b]===void 0&&!_.has(b)){const k=p.schemaEnv.baseId+p.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(p,S,p.opts.strictRequired)}}function f(){if(d||u)o.block$data(e.nil,y);else for(const g of i)(0,t.checkReportMissingProp)(o,g)}function v(){const g=a.let("missing");if(d||u){const _=a.let("valid",!0);o.block$data(_,()=>w(g,_)),o.ok(_)}else a.if((0,t.checkMissingProp)(o,i,g)),(0,t.reportMissingProp)(o,g),a.else()}function y(){a.forOf("prop",c,g=>{o.setParams({missingProperty:g}),a.if((0,t.noPropertyInData)(a,l,g,h.ownProperties),()=>o.error())})}function w(g,_){o.setParams({missingProperty:g}),a.forOf(g,c,()=>{a.assign(_,(0,t.propertyInData)(a,l,g,h.ownProperties)),a.if((0,e.not)(_),()=>{o.error(),a.break()})},e.nil)}}};return Qo.default=s,Qo}var Xo={},cp;function H_(){if(cp)return Xo;cp=1,Object.defineProperty(Xo,"__esModule",{value:!0});const t=Te(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${o}.length ${i} ${a}`)}};return Xo.default=r,Xo}var ea={},ta={},lp;function Xi(){if(lp)return ta;lp=1,Object.defineProperty(ta,"__esModule",{value:!0});const t=zd();return t.code='require("ajv/dist/runtime/equal").default',ta.default=t,ta}var up;function B_(){if(up)return ea;up=1,Object.defineProperty(ea,"__esModule",{value:!0});const t=No(),e=Te(),r=Ae(),n=Xi(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,e.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,e._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:c,$data:l,schema:u,parentSchema:p,schemaCode:h,it:d}=a;if(!l&&!u)return;const f=i.let("valid"),v=p.items?(0,t.getSchemaTypes)(p.items):[];a.block$data(f,y,(0,e._)`${h} === false`),a.ok(f);function y(){const b=i.let("i",(0,e._)`${c}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(f,!0),i.if((0,e._)`${b} > 1`,()=>(w()?g:_)(b,k))}function w(){return v.length>0&&!v.some(b=>b==="object"||b==="array")}function g(b,k){const S=i.name("item"),C=(0,t.checkDataTypes)(v,S,d.opts.strictNumbers,t.DataType.Wrong),x=i.const("indices",(0,e._)`{}`);i.for((0,e._)`;${b}--;`,()=>{i.let(S,(0,e._)`${c}[${b}]`),i.if(C,(0,e._)`continue`),v.length>1&&i.if((0,e._)`typeof ${S} == "string"`,(0,e._)`${S} += "_"`),i.if((0,e._)`typeof ${x}[${S}] == "number"`,()=>{i.assign(k,(0,e._)`${x}[${S}]`),a.error(),i.assign(f,!1).break()}).code((0,e._)`${x}[${S}] = ${b}`)})}function _(b,k){const S=(0,r.useFunc)(i,n.default),C=i.name("outer");i.label(C).for((0,e._)`;${b}--;`,()=>i.for((0,e._)`${k} = ${b}; ${k}--;`,()=>i.if((0,e._)`${S}(${c}[${b}], ${c}[${k}])`,()=>{a.error(),i.assign(f,!1).break(C)})))}}};return ea.default=o,ea}var ra={},dp;function J_(){if(dp)return ra;dp=1,Object.defineProperty(ra,"__esModule",{value:!0});const t=Te(),e=Ae(),r=Xi(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:o})=>(0,t._)`{allowedValue: ${o}}`},code(o){const{gen:a,data:i,$data:c,schemaCode:l,schema:u}=o;c||u&&typeof u=="object"?o.fail$data((0,t._)`!${(0,e.useFunc)(a,r.default)}(${i}, ${l})`):o.fail((0,t._)`${u} !== ${i}`)}};return ra.default=s,ra}var na={},pp;function W_(){if(pp)return na;pp=1,Object.defineProperty(na,"__esModule",{value:!0});const t=Te(),e=Ae(),r=Xi(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,t._)`{allowedValues: ${o}}`},code(o){const{gen:a,data:i,$data:c,schema:l,schemaCode:u,it:p}=o;if(!c&&l.length===0)throw new Error("enum must have non-empty array");const h=l.length>=p.opts.loopEnum;let d;const f=()=>d??(d=(0,e.useFunc)(a,r.default));let v;if(h||c)v=a.let("valid"),o.block$data(v,y);else{if(!Array.isArray(l))throw new Error("ajv implementation error");const g=a.const("vSchema",u);v=(0,t.or)(...l.map((_,b)=>w(g,b)))}o.pass(v);function y(){a.assign(v,!1),a.forOf("v",u,g=>a.if((0,t._)`${f()}(${i}, ${g})`,()=>a.assign(v,!0).break()))}function w(g,_){const b=l[_];return typeof b=="object"&&b!==null?(0,t._)`${f()}(${i}, ${g}[${_}])`:(0,t._)`${i} === ${b}`}}};return na.default=s,na}var fp;function G_(){if(fp)return Ho;fp=1,Object.defineProperty(Ho,"__esModule",{value:!0});const t=q_(),e=z_(),r=U_(),n=Z_(),s=F_(),o=V_(),a=H_(),i=B_(),c=J_(),l=W_(),u=[t.default,e.default,r.default,n.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return Ho.default=u,Ho}var sa={},$n={},hp;function mp(){if(hp)return $n;hp=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.validateAdditionalItems=void 0;const t=Te(),e=Ae(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){const{parentSchema:a,it:i}=o,{items:c}=a;if(!Array.isArray(c)){(0,e.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,c)}};function s(o,a){const{gen:i,schema:c,data:l,keyword:u,it:p}=o;p.items=!0;const h=i.const("len",(0,t._)`${l}.length`);if(c===!1)o.setParams({len:a.length}),o.pass((0,t._)`${h} <= ${a.length}`);else if(typeof c=="object"&&!(0,e.alwaysValidSchema)(p,c)){const f=i.var("valid",(0,t._)`${h} <= ${a.length}`);i.if((0,t.not)(f),()=>d(f)),o.ok(f)}function d(f){i.forRange("i",a.length,h,v=>{o.subschema({keyword:u,dataProp:v,dataPropType:e.Type.Num},f),p.allErrors||i.if((0,t.not)(f),()=>i.break())})}}return $n.validateAdditionalItems=s,$n.default=n,$n}var oa={},En={},gp;function yp(){if(gp)return En;gp=1,Object.defineProperty(En,"__esModule",{value:!0}),En.validateTuple=void 0;const t=Te(),e=Ae(),r=Vt(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:a,it:i}=o;if(Array.isArray(a))return s(o,"additionalItems",a);i.items=!0,!(0,e.alwaysValidSchema)(i,a)&&o.ok((0,r.validateArray)(o))}};function s(o,a,i=o.schema){const{gen:c,parentSchema:l,data:u,keyword:p,it:h}=o;v(l),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=e.mergeEvaluated.items(c,i.length,h.items));const d=c.name("valid"),f=c.const("len",(0,t._)`${u}.length`);i.forEach((y,w)=>{(0,e.alwaysValidSchema)(h,y)||(c.if((0,t._)`${f} > ${w}`,()=>o.subschema({keyword:p,schemaProp:w,dataProp:w},d)),o.ok(d))});function v(y){const{opts:w,errSchemaPath:g}=h,_=i.length,b=_===y.minItems&&(_===y.maxItems||y[a]===!1);if(w.strictTuples&&!b){const k=`"${p}" is ${_}-tuple, but minItems or maxItems/${a} are not specified or different at path "${g}"`;(0,e.checkStrictMode)(h,k,w.strictTuples)}}}return En.validateTuple=s,En.default=n,En}var _p;function K_(){if(_p)return oa;_p=1,Object.defineProperty(oa,"__esModule",{value:!0});const t=yp(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return oa.default=e,oa}var aa={},vp;function Y_(){if(vp)return aa;vp=1,Object.defineProperty(aa,"__esModule",{value:!0});const t=Te(),e=Ae(),r=Vt(),n=mp(),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:c,it:l}=a,{prefixItems:u}=c;l.items=!0,!(0,e.alwaysValidSchema)(l,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return aa.default=o,aa}var ia={},wp;function Q_(){if(wp)return ia;wp=1,Object.defineProperty(ia,"__esModule",{value:!0});const t=Te(),e=Ae(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:o}})=>o===void 0?(0,t.str)`must contain at least ${s} valid item(s)`:(0,t.str)`must contain at least ${s} and no more than ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${o}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:c,it:l}=s;let u,p;const{minContains:h,maxContains:d}=i;l.opts.next?(u=h===void 0?1:h,p=d):u=1;const f=o.const("len",(0,t._)`${c}.length`);if(s.setParams({min:u,max:p}),p===void 0&&u===0){(0,e.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&u>p){(0,e.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(l,a)){let _=(0,t._)`${f} >= ${u}`;p!==void 0&&(_=(0,t._)`${_} && ${f} <= ${p}`),s.pass(_);return}l.items=!0;const v=o.name("valid");p===void 0&&u===1?w(v,()=>o.if(v,()=>o.break())):u===0?(o.let(v,!0),p!==void 0&&o.if((0,t._)`${c}.length > 0`,y)):(o.let(v,!1),y()),s.result(v,()=>s.reset());function y(){const _=o.name("_valid"),b=o.let("count",0);w(_,()=>o.if(_,()=>g(b)))}function w(_,b){o.forRange("i",0,f,k=>{s.subschema({keyword:"contains",dataProp:k,dataPropType:e.Type.Num,compositeRule:!0},_),b()})}function g(_){o.code((0,t._)`${_}++`),p===void 0?o.if((0,t._)`${_} >= ${u}`,()=>o.assign(v,!0).break()):(o.if((0,t._)`${_} > ${p}`,()=>o.assign(v,!1).break()),u===1?o.assign(v,!0):o.if((0,t._)`${_} >= ${u}`,()=>o.assign(v,!0)))}}};return ia.default=n,ia}var ec={},bp;function X_(){return bp||(bp=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Te(),r=Ae(),n=Vt();t.error={message:({params:{property:c,depsCount:l,deps:u}})=>{const p=l===1?"property":"properties";return(0,e.str)`must have ${p} ${u} when property ${c} is present`},params:({params:{property:c,depsCount:l,deps:u,missingProperty:p}})=>(0,e._)`{property: ${c},
|
|
6
|
+
missingProperty: ${p},
|
|
7
7
|
depsCount: ${l},
|
|
8
|
-
deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[l,u]=o(c);a(c,l),i(c,u)}};function o({schema:c}){const l={},u={};for(const h in c){if(h==="__proto__")continue;const f=Array.isArray(c[h])?l:u;f[h]=c[h]}return[l,u]}function a(c,l=c.schema){const{gen:u,data:h,it:f}=c;if(Object.keys(l).length===0)return;const p=u.let("missing");for(const m in l){const v=l[m];if(v.length===0)continue;const _=(0,n.propertyInData)(u,h,m,f.opts.ownProperties);c.setParams({property:m,depsCount:v.length,deps:v.join(", ")}),f.allErrors?u.if(_,()=>{for(const w of v)(0,n.checkReportMissingProp)(c,w)}):(u.if((0,e._)`${_} && (${(0,n.checkMissingProp)(c,v,p)})`),(0,n.reportMissingProp)(c,p),u.else())}}t.validatePropertyDeps=a;function i(c,l=c.schema){const{gen:u,data:h,keyword:f,it:p}=c,m=u.name("valid");for(const v in l)(0,r.alwaysValidSchema)(p,l[v])||(u.if((0,n.propertyInData)(u,h,v,p.opts.ownProperties),()=>{const _=c.subschema({keyword:f,schemaProp:v},m);c.mergeValidEvaluated(_,m)},()=>u.var(m,!0)),c.ok(m))}t.validateSchemaDeps=i,t.default=s})(Pc)),Pc}var ka={},Eh;function Gw(){if(Eh)return ka;Eh=1,Object.defineProperty(ka,"__esModule",{value:!0});const t=Ee(),e=Le(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:s})=>(0,t._)`{propertyName: ${s.propertyName}}`},code(s){const{gen:o,schema:a,data:i,it:c}=s;if((0,e.alwaysValidSchema)(c,a))return;const l=o.name("valid");o.forIn("key",i,u=>{s.setParams({propertyName:u}),s.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},l),o.if((0,t.not)(l),()=>{s.error(!0),c.allErrors||o.break()})}),s.ok(l)}};return ka.default=n,ka}var Ca={},xh;function Ih(){if(xh)return Ca;xh=1,Object.defineProperty(Ca,"__esModule",{value:!0});const t=Kt(),e=Ee(),r=Fr(),n=Le(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:c,parentSchema:l,data:u,errsCount:h,it:f}=a;if(!h)throw new Error("ajv implementation error");const{allErrors:p,opts:m}=f;if(f.props=!0,m.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(f,c))return;const v=(0,t.allSchemaProperties)(l.properties),_=(0,t.allSchemaProperties)(l.patternProperties);w(),a.ok((0,e._)`${h} === ${r.default.errors}`);function w(){i.forIn("key",u,k=>{!v.length&&!_.length?b(k):i.if(g(k),()=>b(k))})}function g(k){let T;if(v.length>8){const x=(0,n.schemaRefOrVal)(f,l.properties,"properties");T=(0,t.isOwnProperty)(i,x,k)}else v.length?T=(0,e.or)(...v.map(x=>(0,e._)`${k} === ${x}`)):T=e.nil;return _.length&&(T=(0,e.or)(T,..._.map(x=>(0,e._)`${(0,t.usePattern)(a,x)}.test(${k})`))),(0,e.not)(T)}function y(k){i.code((0,e._)`delete ${u}[${k}]`)}function b(k){if(m.removeAdditional==="all"||m.removeAdditional&&c===!1){y(k);return}if(c===!1){a.setParams({additionalProperty:k}),a.error(),p||i.break();return}if(typeof c=="object"&&!(0,n.alwaysValidSchema)(f,c)){const T=i.name("valid");m.removeAdditional==="failing"?(S(k,T,!1),i.if((0,e.not)(T),()=>{a.reset(),y(k)})):(S(k,T),p||i.if((0,e.not)(T),()=>i.break()))}}function S(k,T,x){const P={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};x===!1&&Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(P,T)}}};return Ca.default=o,Ca}var Ta={},Rh;function Kw(){if(Rh)return Ta;Rh=1,Object.defineProperty(Ta,"__esModule",{value:!0});const t=Qo(),e=Kt(),r=Le(),n=Ih(),s={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,parentSchema:c,data:l,it:u}=o;u.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(u,n.default,"additionalProperties"));const h=(0,e.allSchemaProperties)(i);for(const _ of h)u.definedProperties.add(_);u.opts.unevaluated&&h.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(h),u.props));const f=h.filter(_=>!(0,r.alwaysValidSchema)(u,i[_]));if(f.length===0)return;const p=a.name("valid");for(const _ of f)m(_)?v(_):(a.if((0,e.propertyInData)(a,l,_,u.opts.ownProperties)),v(_),u.allErrors||a.else().var(p,!0),a.endIf()),o.it.definedProperties.add(_),o.ok(p);function m(_){return u.opts.useDefaults&&!u.compositeRule&&i[_].default!==void 0}function v(_){o.subschema({keyword:"properties",schemaProp:_,dataProp:_},p)}}};return Ta.default=s,Ta}var $a={},Ph;function Yw(){if(Ph)return $a;Ph=1,Object.defineProperty($a,"__esModule",{value:!0});const t=Kt(),e=Ee(),r=Le(),n=Le(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,data:c,parentSchema:l,it:u}=o,{opts:h}=u,f=(0,t.allSchemaProperties)(i),p=f.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(f.length===0||p.length===f.length&&(!u.opts.unevaluated||u.props===!0))return;const m=h.strictSchema&&!h.allowMatchingProperties&&l.properties,v=a.name("valid");u.props!==!0&&!(u.props instanceof e.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:_}=u;w();function w(){for(const b of f)m&&g(b),u.allErrors?y(b):(a.var(v,!0),y(b),a.if(v))}function g(b){for(const S in m)new RegExp(b).test(S)&&(0,r.checkStrictMode)(u,`property ${S} matches pattern ${b} (use allowMatchingProperties)`)}function y(b){a.forIn("key",c,S=>{a.if((0,e._)`${(0,t.usePattern)(o,b)}.test(${S})`,()=>{const k=p.includes(b);k||o.subschema({keyword:"patternProperties",schemaProp:b,dataProp:S,dataPropType:n.Type.Str},v),u.opts.unevaluated&&_!==!0?a.assign((0,e._)`${_}[${S}]`,!0):!k&&!u.allErrors&&a.if((0,e.not)(v),()=>a.break())})})}}};return $a.default=s,$a}var Ea={},Oh;function Qw(){if(Oh)return Ea;Oh=1,Object.defineProperty(Ea,"__esModule",{value:!0});const t=Le(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:o}=r;if((0,t.alwaysValidSchema)(o,s)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return Ea.default=e,Ea}var xa={},Ah;function Xw(){if(Ah)return xa;Ah=1,Object.defineProperty(xa,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Kt().validateUnion,error:{message:"must match a schema in anyOf"}};return xa.default=e,xa}var Ia={},Mh;function eb(){if(Mh)return Ia;Mh=1,Object.defineProperty(Ia,"__esModule",{value:!0});const t=Ee(),e=Le(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:s})=>(0,t._)`{passingSchemas: ${s.passing}}`},code(s){const{gen:o,schema:a,parentSchema:i,it:c}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(c.opts.discriminator&&i.discriminator)return;const l=a,u=o.let("valid",!1),h=o.let("passing",null),f=o.name("_valid");s.setParams({passing:h}),o.block(p),s.result(u,()=>s.reset(),()=>s.error(!0));function p(){l.forEach((m,v)=>{let _;(0,e.alwaysValidSchema)(c,m)?o.var(f,!0):_=s.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},f),v>0&&o.if((0,t._)`${f} && ${u}`).assign(u,!1).assign(h,(0,t._)`[${h}, ${v}]`).else(),o.if(f,()=>{o.assign(u,!0),o.assign(h,v),_&&s.mergeEvaluated(_,t.Name)})})}}};return Ia.default=n,Ia}var Ra={},Nh;function tb(){if(Nh)return Ra;Nh=1,Object.defineProperty(Ra,"__esModule",{value:!0});const t=Le(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:o}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((i,c)=>{if((0,t.alwaysValidSchema)(o,i))return;const l=r.subschema({keyword:"allOf",schemaProp:c},a);r.ok(a),r.mergeEvaluated(l)})}};return Ra.default=e,Ra}var Pa={},Lh;function rb(){if(Lh)return Pa;Lh=1,Object.defineProperty(Pa,"__esModule",{value:!0});const t=Ee(),e=Le(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:o})=>(0,t.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,t._)`{failingKeyword: ${o.ifClause}}`},code(o){const{gen:a,parentSchema:i,it:c}=o;i.then===void 0&&i.else===void 0&&(0,e.checkStrictMode)(c,'"if" without "then" and "else" is ignored');const l=s(c,"then"),u=s(c,"else");if(!l&&!u)return;const h=a.let("valid",!0),f=a.name("_valid");if(p(),o.reset(),l&&u){const v=a.let("ifClause");o.setParams({ifClause:v}),a.if(f,m("then",v),m("else",v))}else l?a.if(f,m("then")):a.if((0,t.not)(f),m("else"));o.pass(h,()=>o.error(!0));function p(){const v=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);o.mergeEvaluated(v)}function m(v,_){return()=>{const w=o.subschema({keyword:v},f);a.assign(h,f),o.mergeValidEvaluated(w,h),_?a.assign(_,(0,t._)`${v}`):o.setParams({ifClause:v})}}}};function s(o,a){const i=o.schema[a];return i!==void 0&&!(0,e.alwaysValidSchema)(o,i)}return Pa.default=n,Pa}var Oa={},qh;function nb(){if(qh)return Oa;qh=1,Object.defineProperty(Oa,"__esModule",{value:!0});const t=Le(),e={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:s}){n.if===void 0&&(0,t.checkStrictMode)(s,`"${r}" without "if" is ignored`)}};return Oa.default=e,Oa}var jh;function sb(){if(jh)return ya;jh=1,Object.defineProperty(ya,"__esModule",{value:!0});const t=wh(),e=Hw(),r=Sh(),n=Bw(),s=Jw(),o=Ww(),a=Gw(),i=Ih(),c=Kw(),l=Yw(),u=Qw(),h=Xw(),f=eb(),p=tb(),m=rb(),v=nb();function _(w=!1){const g=[u.default,h.default,f.default,p.default,m.default,v.default,a.default,i.default,o.default,c.default,l.default];return w?g.push(e.default,n.default):g.push(t.default,r.default),g.push(s.default),g}return ya.default=_,ya}var Aa={},Ma={},Uh;function ob(){if(Uh)return Ma;Uh=1,Object.defineProperty(Ma,"__esModule",{value:!0});const t=Ee(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,s){const{gen:o,data:a,$data:i,schema:c,schemaCode:l,it:u}=n,{opts:h,errSchemaPath:f,schemaEnv:p,self:m}=u;if(!h.validateFormats)return;i?v():_();function v(){const w=o.scopeValue("formats",{ref:m.formats,code:h.code.formats}),g=o.const("fDef",(0,t._)`${w}[${l}]`),y=o.let("fType"),b=o.let("format");o.if((0,t._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>o.assign(y,(0,t._)`${g}.type || "string"`).assign(b,(0,t._)`${g}.validate`),()=>o.assign(y,(0,t._)`"string"`).assign(b,g)),n.fail$data((0,t.or)(S(),k()));function S(){return h.strictSchema===!1?t.nil:(0,t._)`${l} && !${b}`}function k(){const T=p.$async?(0,t._)`(${g}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,t._)`${b}(${a})`,x=(0,t._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${a}))`;return(0,t._)`${b} && ${b} !== true && ${y} === ${s} && !${x}`}}function _(){const w=m.formats[c];if(!w){S();return}if(w===!0)return;const[g,y,b]=k(w);g===s&&n.pass(T());function S(){if(h.strictSchema===!1){m.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${c}" ignored in schema at path "${f}"`}}function k(x){const P=x instanceof RegExp?(0,t.regexpCode)(x):h.code.formats?(0,t._)`${h.code.formats}${(0,t.getProperty)(c)}`:void 0,q=o.scopeValue("formats",{key:c,ref:x,code:P});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,t._)`${q}.validate`]:["string",x,q]}function T(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!p.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${a})`}return typeof y=="function"?(0,t._)`${b}(${a})`:(0,t._)`${b}.test(${a})`}}}};return Ma.default=r,Ma}var zh;function ab(){if(zh)return Aa;zh=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=[ob().default];return Aa.default=e,Aa}var mn={},Dh;function ib(){return Dh||(Dh=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.contentVocabulary=mn.metadataVocabulary=void 0,mn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],mn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),mn}var Zh;function cb(){if(Zh)return na;Zh=1,Object.defineProperty(na,"__esModule",{value:!0});const t=Ow(),e=Fw(),r=sb(),n=ab(),s=ib(),o=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return na.default=o,na}var Na={},Es={},Vh;function lb(){if(Vh)return Es;Vh=1,Object.defineProperty(Es,"__esModule",{value:!0}),Es.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||(Es.DiscrError=t={})),Es}var Fh;function ub(){if(Fh)return Na;Fh=1,Object.defineProperty(Na,"__esModule",{value:!0});const t=Ee(),e=lb(),r=Ec(),n=ta(),s=Le(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:c}})=>i===e.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:i,tag:c,tagName:l}})=>(0,t._)`{error: ${i}, tag: ${l}, tagValue: ${c}}`},code(i){const{gen:c,data:l,schema:u,parentSchema:h,it:f}=i,{oneOf:p}=h;if(!f.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(!p)throw new Error("discriminator: requires oneOf keyword");const v=c.let("valid",!1),_=c.const("tag",(0,t._)`${l}${(0,t.getProperty)(m)}`);c.if((0,t._)`typeof ${_} == "string"`,()=>w(),()=>i.error(!1,{discrError:e.DiscrError.Tag,tag:_,tagName:m})),i.ok(v);function w(){const b=y();c.if(!1);for(const S in b)c.elseIf((0,t._)`${_} === ${S}`),c.assign(v,g(b[S]));c.else(),i.error(!1,{discrError:e.DiscrError.Mapping,tag:_,tagName:m}),c.endIf()}function g(b){const S=c.name("valid"),k=i.subschema({keyword:"oneOf",schemaProp:b},S);return i.mergeEvaluated(k,t.Name),S}function y(){var b;const S={},k=x(h);let T=!0;for(let N=0;N<p.length;N++){let z=p[N];if(z?.$ref&&!(0,s.schemaHasRulesButRef)(z,f.self.RULES)){const F=z.$ref;if(z=r.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,F),z instanceof r.SchemaEnv&&(z=z.schema),z===void 0)throw new n.default(f.opts.uriResolver,f.baseId,F)}const D=(b=z?.properties)===null||b===void 0?void 0:b[m];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);T=T&&(k||x(z)),P(D,N)}if(!T)throw new Error(`discriminator: "${m}" must be required`);return S;function x({required:N}){return Array.isArray(N)&&N.includes(m)}function P(N,z){if(N.const)q(N.const,z);else if(N.enum)for(const D of N.enum)q(D,z);else throw new Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function q(N,z){if(typeof N!="string"||N in S)throw new Error(`discriminator: "${m}" values must be unique strings`);S[N]=z}}}};return Na.default=a,Na}const db={$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 Hh;function Bh(){return Hh||(Hh=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=Iw(),n=cb(),s=ub(),o=db,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(o,a):o;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)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Qo();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Ee();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=$c();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return h.default}});var f=ta();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(Bo,Bo.exports)),Bo.exports}var Jh=Bh();const Wh=pn(Jh);var Pe;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(const a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Pe||(Pe={}));var Oc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Oc||(Oc={}));const ae=Pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rr=t=>{switch(typeof t){case"undefined":return ae.undefined;case"string":return ae.string;case"number":return Number.isNaN(t)?ae.nan:ae.number;case"boolean":return ae.boolean;case"function":return ae.function;case"bigint":return ae.bigint;case"symbol":return ae.symbol;case"object":return Array.isArray(t)?ae.array:t===null?ae.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ae.promise:typeof Map<"u"&&t instanceof Map?ae.map:typeof Set<"u"&&t instanceof Set?ae.set:typeof Date<"u"&&t instanceof Date?ae.date:ae.object;default:return ae.unknown}},Y=Pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),pb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Mt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof Mt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Mt.create=t=>new Mt(t);const Dn=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===ae.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Pe.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Pe.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Pe.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Pe.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Pe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Pe.assertNever(t)}return{message:r}};let Gh=Dn;function hb(t){Gh=t}function La(){return Gh}const qa=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)i=l(a,{data:e,defaultError:i}).message;return{...s,path:o,message:i}},fb=[];function re(t,e){const r=La(),n=qa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Dn?void 0:Dn].filter(s=>!!s)});t.common.issues.push(n)}class ft{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return ge;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return ft.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return ge;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const ge=Object.freeze({status:"aborted"}),Zn=t=>({status:"dirty",value:t}),vt=t=>({status:"valid",value:t}),Ac=t=>t.status==="aborted",Mc=t=>t.status==="dirty",gn=t=>t.status==="valid",xs=t=>typeof Promise<"u"&&t instanceof Promise;var le;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(le||(le={}));class mr{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Kh=(t,e)=>{if(gn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Mt(t.common.issues);return this._error=r,this._error}}};function Te(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??r??i.defaultError}},description:s}}let $e=class{get description(){return this._def.description}_getType(e){return Rr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ft,ctx:{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(xs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Kh(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return gn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>gn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(xs(s)?s:Promise.resolve(s));return Kh(n,o)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{const a=e(s),i=()=>o.addIssue({code:Y.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Yt({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return _r.create(this,this._def)}nullable(){return Jr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return yn.create(this)}promise(){return Jn.create(this,this._def)}or(e){return As.create([this,e],this._def)}and(e){return Ms.create(this,e,this._def)}transform(e){return new Yt({...Te(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Us({...Te(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new qc({typeName:U.ZodBranded,type:this,...Te(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new zs({...Te(this._def),innerType:this,catchValue:r,typeName:U.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ds.create(this,e)}readonly(){return Zs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const mb=/^c[^\s-]{8,}$/i,gb=/^[0-9a-z]+$/,_b=/^[0-9A-HJKMNP-TV-Z]{26}$/i,vb=/^[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,yb=/^[a-z0-9_-]{21}$/i,wb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Sb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Nc;const 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])$/,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])\/(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]))$/,Eb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ib=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,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])))",Rb=new RegExp(`^${Yh}$`);function Qh(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Pb(t){return new RegExp(`^${Qh(t)}$`)}function Xh(t){let e=`${Yh}T${Qh(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ob(t,e){return!!((e==="v4"||!e)&&Cb.test(t)||(e==="v6"||!e)&&$b.test(t))}function Ab(t,e){if(!wb.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Mb(t,e){return!!((e==="v4"||!e)&&Tb.test(t)||(e==="v6"||!e)&&Eb.test(t))}let Vn=class Ho extends $e{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ae.string){const o=this._getOrReturnCtx(e);return re(o,{code:Y.invalid_type,expected:ae.string,received:o.parsedType}),ge}const n=new ft;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),re(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),re(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?re(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&re(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Sb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"email",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Nc||(Nc=new RegExp(kb,"u")),Nc.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"emoji",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")vb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"uuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")yb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"nanoid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")mb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"cuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")gb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"cuid2",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")_b.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"ulid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),re(s,{validation:"url",code:Y.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"regex",code:Y.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Xh(o).test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Rb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Pb(o).test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{code:Y.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?bb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"duration",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Ob(e.data,o.version)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"ip",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Ab(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"jwt",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Mb(e.data,o.version)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"cidr",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?xb.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"base64",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Ib.test(e.data)||(s=this._getOrReturnCtx(e,s),re(s,{validation:"base64url",code:Y.invalid_string,message:o.message}),n.dirty()):Pe.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Y.invalid_string,...le.errToObj(n)})}_addCheck(e){return new Ho({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...le.errToObj(e)})}url(e){return this._addCheck({kind:"url",...le.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...le.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...le.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...le.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...le.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...le.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...le.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...le.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...le.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...le.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...le.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...le.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...le.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...le.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...le.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...le.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...le.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...le.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...le.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...le.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...le.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...le.errToObj(r)})}nonempty(e){return this.min(1,le.errToObj(e))}trim(){return new Ho({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ho({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ho({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Vn.create=t=>new Vn({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...Te(t)});function Nb(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}let Is=class bp extends $e{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ae.number){const o=this._getOrReturnCtx(e);return re(o,{code:Y.invalid_type,expected:ae.number,received:o.parsedType}),ge}let n;const s=new ft;for(const o of this._def.checks)o.kind==="int"?Pe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),re(n,{code:Y.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Nb(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),re(n,{code:Y.not_finite,message:o.message}),s.dirty()):Pe.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new bp({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new bp({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:le.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:le.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:le.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:le.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Pe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Is.create=t=>new Is({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...Te(t)});class Br extends $e{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ae.bigint)return this._getInvalidInput(e);let n;const s=new ft;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),re(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Pe.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return re(r,{code:Y.invalid_type,expected:ae.bigint,received:r.parsedType}),ge}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new Br({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new Br({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Br.create=t=>new Br({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...Te(t)});let Rs=class extends $e{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ae.boolean){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.boolean,received:n.parsedType}),ge}return vt(e.data)}};Rs.create=t=>new Rs({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...Te(t)});class _n extends $e{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ae.date){const o=this._getOrReturnCtx(e);return re(o,{code:Y.invalid_type,expected:ae.date,received:o.parsedType}),ge}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return re(o,{code:Y.invalid_date}),ge}const n=new ft;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),re(s,{code:Y.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),re(s,{code:Y.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Pe.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new _n({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:le.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:le.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}_n.create=t=>new _n({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...Te(t)});class ja extends $e{_parse(e){if(this._getType(e)!==ae.symbol){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.symbol,received:n.parsedType}),ge}return vt(e.data)}}ja.create=t=>new ja({typeName:U.ZodSymbol,...Te(t)});class Ps extends $e{_parse(e){if(this._getType(e)!==ae.undefined){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.undefined,received:n.parsedType}),ge}return vt(e.data)}}Ps.create=t=>new Ps({typeName:U.ZodUndefined,...Te(t)});let Os=class extends $e{_parse(e){if(this._getType(e)!==ae.null){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.null,received:n.parsedType}),ge}return vt(e.data)}};Os.create=t=>new Os({typeName:U.ZodNull,...Te(t)});let Fn=class extends $e{constructor(){super(...arguments),this._any=!0}_parse(e){return vt(e.data)}};Fn.create=t=>new Fn({typeName:U.ZodAny,...Te(t)});let vn=class extends $e{constructor(){super(...arguments),this._unknown=!0}_parse(e){return vt(e.data)}};vn.create=t=>new vn({typeName:U.ZodUnknown,...Te(t)});let Pr=class extends $e{_parse(e){const r=this._getOrReturnCtx(e);return re(r,{code:Y.invalid_type,expected:ae.never,received:r.parsedType}),ge}};Pr.create=t=>new Pr({typeName:U.ZodNever,...Te(t)});class Ua extends $e{_parse(e){if(this._getType(e)!==ae.undefined){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.void,received:n.parsedType}),ge}return vt(e.data)}}Ua.create=t=>new Ua({typeName:U.ZodVoid,...Te(t)});let yn=class vc extends $e{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==ae.array)return re(r,{code:Y.invalid_type,expected:ae.array,received:r.parsedType}),ge;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,i=r.data.length<s.exactLength.value;(a||i)&&(re(r,{code:a?Y.too_big:Y.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(re(r,{code:Y.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(re(r,{code:Y.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>s.type._parseAsync(new mr(r,a,r.path,i)))).then(a=>ft.mergeArray(n,a));const o=[...r.data].map((a,i)=>s.type._parseSync(new mr(r,a,r.path,i)));return ft.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new vc({...this._def,minLength:{value:e,message:le.toString(r)}})}max(e,r){return new vc({...this._def,maxLength:{value:e,message:le.toString(r)}})}length(e,r){return new vc({...this._def,exactLength:{value:e,message:le.toString(r)}})}nonempty(e){return this.min(1,e)}};yn.create=(t,e)=>new yn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...Te(e)});function Hn(t){if(t instanceof Dt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=_r.create(Hn(n))}return new Dt({...t._def,shape:()=>e})}else return t instanceof yn?new yn({...t._def,type:Hn(t.element)}):t instanceof _r?_r.create(Hn(t.unwrap())):t instanceof Jr?Jr.create(Hn(t.unwrap())):t instanceof gr?gr.create(t.items.map(e=>Hn(e))):t}let Dt=class fr extends $e{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Pe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ae.object){const l=this._getOrReturnCtx(e);return re(l,{code:Y.invalid_type,expected:ae.object,received:l.parsedType}),ge}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Pr&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||i.push(l);const c=[];for(const l of a){const u=o[l],h=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new mr(s,h,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Pr){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of i)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")i.length>0&&(re(s,{code:Y.unrecognized_keys,keys:i}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of i){const h=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new mr(s,h,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of c){const h=await u.key,f=await u.value;l.push({key:h,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>ft.mergeObjectSync(n,l)):ft.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return le.errToObj,new fr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:le.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new fr({...this._def,unknownKeys:"strip"})}passthrough(){return new fr({...this._def,unknownKeys:"passthrough"})}extend(e){return new fr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new fr({...this._def,catchall:e})}pick(e){const r={};for(const n of Pe.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new fr({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Pe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new fr({...this._def,shape:()=>r})}deepPartial(){return Hn(this)}partial(e){const r={};for(const n of Pe.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new fr({...this._def,shape:()=>r})}required(e){const r={};for(const n of Pe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof _r;)o=o._def.innerType;r[n]=o}return new fr({...this._def,shape:()=>r})}keyof(){return rf(Pe.objectKeys(this.shape))}};Dt.create=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strip",catchall:Pr.create(),typeName:U.ZodObject,...Te(e)}),Dt.strictCreate=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strict",catchall:Pr.create(),typeName:U.ZodObject,...Te(e)}),Dt.lazycreate=(t,e)=>new Dt({shape:t,unknownKeys:"strip",catchall:Pr.create(),typeName:U.ZodObject,...Te(e)});let As=class extends $e{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new Mt(i.ctx.common.issues));return re(r,{code:Y.invalid_union,unionErrors:a}),ge}if(r.common.async)return Promise.all(n.map(async o=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of n){const l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(c=>new Mt(c));return re(r,{code:Y.invalid_union,unionErrors:i}),ge}}get options(){return this._def.options}};As.create=(t,e)=>new As({options:t,typeName:U.ZodUnion,...Te(e)});const Or=t=>t instanceof Ns?Or(t.schema):t instanceof Yt?Or(t.innerType()):t instanceof Ls?[t.value]:t instanceof qs?t.options:t instanceof js?Pe.objectValues(t.enum):t instanceof Us?Or(t._def.innerType):t instanceof Ps?[void 0]:t instanceof Os?[null]:t instanceof _r?[void 0,...Or(t.unwrap())]:t instanceof Jr?[null,...Or(t.unwrap())]:t instanceof qc||t instanceof Zs?Or(t.unwrap()):t instanceof zs?Or(t._def.innerType):[];let ef=class fw extends $e{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ae.object)return re(r,{code:Y.invalid_type,expected:ae.object,received:r.parsedType}),ge;const n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(re(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ge)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const o of r){const a=Or(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o)}}return new fw({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Te(n)})}};function Lc(t,e){const r=Rr(t),n=Rr(e);if(t===e)return{valid:!0,data:t};if(r===ae.object&&n===ae.object){const s=Pe.objectKeys(e),o=Pe.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(const i of o){const c=Lc(t[i],e[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(r===ae.array&&n===ae.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const a=t[o],i=e[o],c=Lc(a,i);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===ae.date&&n===ae.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Ms=class extends $e{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Ac(o)||Ac(a))return ge;const i=Lc(o.value,a.value);return i.valid?((Mc(o)||Mc(a))&&r.dirty(),{status:r.value,value:i.data}):(re(n,{code:Y.invalid_intersection_types}),ge)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ms.create=(t,e,r)=>new Ms({left:t,right:e,typeName:U.ZodIntersection,...Te(r)});class gr extends $e{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.array)return re(n,{code:Y.invalid_type,expected:ae.array,received:n.parsedType}),ge;if(n.data.length<this._def.items.length)return re(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ge;!this._def.rest&&n.data.length>this._def.items.length&&(re(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((a,i)=>{const c=this._def.items[i]||this._def.rest;return c?c._parse(new mr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ft.mergeArray(r,a)):ft.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new gr({...this._def,rest:e})}}gr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gr({items:t,typeName:U.ZodTuple,rest:null,...Te(e)})};let tf=class Sp extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.object)return re(n,{code:Y.invalid_type,expected:ae.object,received:n.parsedType}),ge;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in n.data)s.push({key:o._parse(new mr(n,i,n.path,i)),value:a._parse(new mr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ft.mergeObjectAsync(r,s):ft.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof $e?new Sp({keyType:e,valueType:r,typeName:U.ZodRecord,...Te(n)}):new Sp({keyType:Vn.create(),valueType:e,typeName:U.ZodRecord,...Te(r)})}};class za extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.map)return re(n,{code:Y.invalid_type,expected:ae.map,received:n.parsedType}),ge;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([i,c],l)=>({key:s._parse(new mr(n,i,n.path,[l,"key"])),value:o._parse(new mr(n,c,n.path,[l,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const c of a){const l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}}}}za.create=(t,e,r)=>new za({valueType:e,keyType:t,typeName:U.ZodMap,...Te(r)});class wn extends $e{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.set)return re(n,{code:Y.invalid_type,expected:ae.set,received:n.parsedType}),ge;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(re(n,{code:Y.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(re(n,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const o=this._def.valueType;function a(c){const l=new Set;for(const u of c){if(u.status==="aborted")return ge;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}const i=[...n.data.values()].map((c,l)=>o._parse(new mr(n,c,n.path,l)));return n.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(e,r){return new wn({...this._def,minSize:{value:e,message:le.toString(r)}})}max(e,r){return new wn({...this._def,maxSize:{value:e,message:le.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}wn.create=(t,e)=>new wn({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...Te(e)});class Bn extends $e{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ae.function)return re(r,{code:Y.invalid_type,expected:ae.function,received:r.parsedType}),ge;function n(i,c){return qa({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,La(),Dn].filter(l=>!!l),issueData:{code:Y.invalid_arguments,argumentsError:c}})}function s(i,c){return qa({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,La(),Dn].filter(l=>!!l),issueData:{code:Y.invalid_return_type,returnTypeError:c}})}const o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Jn){const i=this;return vt(async function(...c){const l=new Mt([]),u=await i._def.args.parseAsync(c,o).catch(p=>{throw l.addIssue(n(c,p)),l}),h=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(h,o).catch(p=>{throw l.addIssue(s(h,p)),l})})}else{const i=this;return vt(function(...c){const l=i._def.args.safeParse(c,o);if(!l.success)throw new Mt([n(c,l.error)]);const u=Reflect.apply(a,this,l.data),h=i._def.returns.safeParse(u,o);if(!h.success)throw new Mt([s(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Bn({...this._def,args:gr.create(e).rest(vn.create())})}returns(e){return new Bn({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new Bn({args:e||gr.create([]).rest(vn.create()),returns:r||vn.create(),typeName:U.ZodFunction,...Te(n)})}}let Ns=class extends $e{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ns.create=(t,e)=>new Ns({getter:t,typeName:U.ZodLazy,...Te(e)});let Ls=class extends $e{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return re(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),ge}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ls.create=(t,e)=>new Ls({value:t,typeName:U.ZodLiteral,...Te(e)});function rf(t,e){return new qs({values:t,typeName:U.ZodEnum,...Te(e)})}let qs=class kp extends $e{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return re(r,{expected:Pe.joinValues(n),received:r.parsedType,code:Y.invalid_type}),ge}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return re(r,{received:r.data,code:Y.invalid_enum_value,options:n}),ge}return vt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return kp.create(e,{...this._def,...r})}exclude(e,r=this._def){return kp.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};qs.create=rf;class js extends $e{_parse(e){const r=Pe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ae.string&&n.parsedType!==ae.number){const s=Pe.objectValues(r);return re(n,{expected:Pe.joinValues(s),received:n.parsedType,code:Y.invalid_type}),ge}if(this._cache||(this._cache=new Set(Pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Pe.objectValues(r);return re(n,{received:n.data,code:Y.invalid_enum_value,options:s}),ge}return vt(e.data)}get enum(){return this._def.values}}js.create=(t,e)=>new js({values:t,typeName:U.ZodNativeEnum,...Te(e)});class Jn extends $e{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ae.promise&&r.common.async===!1)return re(r,{code:Y.invalid_type,expected:ae.promise,received:r.parsedType}),ge;const n=r.parsedType===ae.promise?r.data:Promise.resolve(r.data);return vt(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Jn.create=(t,e)=>new Jn({type:t,typeName:U.ZodPromise,...Te(e)});class Yt extends $e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{re(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return ge;const c=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return c.status==="aborted"?ge:c.status==="dirty"||r.value==="dirty"?Zn(c.value):c});{if(r.value==="aborted")return ge;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?ge:i.status==="dirty"||r.value==="dirty"?Zn(i.value):i}}if(s.type==="refinement"){const a=i=>{const c=s.refinement(i,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gn(a))return ge;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>gn(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:r.value,value:i})):ge);Pe.assertNever(s)}}Yt.create=(t,e,r)=>new Yt({schema:t,typeName:U.ZodEffects,effect:e,...Te(r)}),Yt.createWithPreprocess=(t,e,r)=>new Yt({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...Te(r)});let _r=class extends $e{_parse(e){return this._getType(e)===ae.undefined?vt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_r.create=(t,e)=>new _r({innerType:t,typeName:U.ZodOptional,...Te(e)});let Jr=class extends $e{_parse(e){return this._getType(e)===ae.null?vt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Jr.create=(t,e)=>new Jr({innerType:t,typeName:U.ZodNullable,...Te(e)});let Us=class extends $e{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ae.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Us.create=(t,e)=>new Us({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Te(e)});let zs=class extends $e{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Mt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Mt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};zs.create=(t,e)=>new zs({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Te(e)});class Da extends $e{_parse(e){if(this._getType(e)!==ae.nan){const n=this._getOrReturnCtx(e);return re(n,{code:Y.invalid_type,expected:ae.nan,received:n.parsedType}),ge}return{status:"valid",value:e.data}}}Da.create=t=>new Da({typeName:U.ZodNaN,...Te(t)});const Lb=Symbol("zod_brand");class qc extends $e{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Ds extends $e{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ge:o.status==="dirty"?(r.dirty(),Zn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ge:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Ds({in:e,out:r,typeName:U.ZodPipeline})}}let Zs=class extends $e{_parse(e){const r=this._def.innerType._parse(e),n=s=>(gn(s)&&(s.value=Object.freeze(s.value)),s);return xs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Zs.create=(t,e)=>new Zs({innerType:t,typeName:U.ZodReadonly,...Te(e)});function nf(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function sf(t,e={},r){return t?Fn.create().superRefine((n,s)=>{const o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){const i=nf(e,n),c=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:c})}});if(!o){const a=nf(e,n),i=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:i})}}):Fn.create()}const qb={object:Dt.lazycreate};var U;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(U||(U={}));const jb=(t,e={message:`Input not instance of ${t.name}`})=>sf(r=>r instanceof t,e),of=Vn.create,af=Is.create,Ub=Da.create,zb=Br.create,cf=Rs.create,Db=_n.create,Zb=ja.create,Vb=Ps.create,Fb=Os.create,Hb=Fn.create,Bb=vn.create,Jb=Pr.create,Wb=Ua.create,Gb=yn.create,lf=Dt.create,Kb=Dt.strictCreate,Yb=As.create,Qb=ef.create,Xb=Ms.create,e3=gr.create,t3=tf.create,r3=za.create,n3=wn.create,s3=Bn.create,o3=Ns.create,a3=Ls.create,i3=qs.create,c3=js.create,l3=Jn.create,uf=Yt.create,u3=_r.create,d3=Jr.create,p3=Yt.createWithPreprocess,h3=Ds.create,f3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Lb,DIRTY:Zn,EMPTY_PATH:fb,INVALID:ge,NEVER:ge,OK:vt,ParseStatus:ft,Schema:$e,ZodAny:Fn,ZodArray:yn,ZodBigInt:Br,ZodBoolean:Rs,ZodBranded:qc,ZodCatch:zs,ZodDate:_n,ZodDefault:Us,ZodDiscriminatedUnion:ef,ZodEffects:Yt,ZodEnum:qs,ZodError:Mt,get ZodFirstPartyTypeKind(){return U},ZodFunction:Bn,ZodIntersection:Ms,ZodIssueCode:Y,ZodLazy:Ns,ZodLiteral:Ls,ZodMap:za,ZodNaN:Da,ZodNativeEnum:js,ZodNever:Pr,ZodNull:Os,ZodNullable:Jr,ZodNumber:Is,ZodObject:Dt,ZodOptional:_r,ZodParsedType:ae,ZodPipeline:Ds,ZodPromise:Jn,ZodReadonly:Zs,ZodRecord:tf,ZodSchema:$e,ZodSet:wn,ZodString:Vn,ZodSymbol:ja,ZodTransformer:Yt,ZodTuple:gr,ZodType:$e,ZodUndefined:Ps,ZodUnion:As,ZodUnknown:vn,ZodVoid:Ua,addIssueToContext:re,any:Hb,array:Gb,bigint:zb,boolean:cf,coerce:{string:(t=>Vn.create({...t,coerce:!0})),number:(t=>Is.create({...t,coerce:!0})),boolean:(t=>Rs.create({...t,coerce:!0})),bigint:(t=>Br.create({...t,coerce:!0})),date:(t=>_n.create({...t,coerce:!0}))},custom:sf,date:Db,datetimeRegex:Xh,defaultErrorMap:Dn,discriminatedUnion:Qb,effect:uf,enum:i3,function:s3,getErrorMap:La,getParsedType:Rr,instanceof:jb,intersection:Xb,isAborted:Ac,isAsync:xs,isDirty:Mc,isValid:gn,late:qb,lazy:o3,literal:a3,makeIssue:qa,map:r3,nan:Ub,nativeEnum:c3,never:Jb,null:Fb,nullable:d3,number:af,object:lf,get objectUtil(){return Oc},oboolean:()=>cf().optional(),onumber:()=>af().optional(),optional:u3,ostring:()=>of().optional(),pipeline:h3,preprocess:p3,promise:l3,quotelessJson:pb,record:t3,set:n3,setErrorMap:hb,strictObject:Kb,string:of,symbol:Zb,transformer:uf,tuple:e3,undefined:Vb,union:Yb,unknown:Bb,get util(){return Pe},void:Wb},Symbol.toStringTag,{value:"Module"})),jc=Object.freeze({status:"aborted"});function J(t,e,r){function n(i,c){var l;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(l=i._zod).traits??(l.traits=new Set),i._zod.traits.add(t),e(i,c);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=c}const s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function a(i){var c;const l=r?.Parent?new o:this;n(l,i),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}class Vs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const df={};function Wr(t){return df}function pf(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function m3(t,e){return typeof e=="bigint"?e.toString():e}function Uc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function zc(t){return t==null}function Dc(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function g3(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function qe(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Fs(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Hs(t){return JSON.stringify(t)}const hf=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const _3=Uc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Va(t){if(Za(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Za(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const v3=new Set(["string","number","symbol"]);function Bs(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gr(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ce(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function y3(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const w3={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 b3(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Gr(t,{...t._zod.def,shape:r,checks:[]})}function S3(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Gr(t,{...t._zod.def,shape:r,checks:[]})}function k3(t,e){if(!Va(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return Fs(this,"shape",n),n},checks:[]};return Gr(t,r)}function C3(t,e){return Gr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Fs(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function T3(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(const o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Gr(e,{...e._zod.def,shape:s,checks:[]})}function $3(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(const o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Gr(e,{...e._zod.def,shape:s,checks:[]})}function Js(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function bn(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Fa(t){return typeof t=="string"?t:t?.message}function Kr(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Fa(t.inst?._zod.def?.error?.(t))??Fa(e?.error?.(t))??Fa(r.customError?.(t))??Fa(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Zc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ws(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const ff=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,m3,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},mf=J("$ZodError",ff),Ha=J("$ZodError",ff,{Parent:Error});function E3(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function x3(t,e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(t),n}const gf=t=>(e,r,n,s)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Vs;if(a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Kr(c,o,Wr())));throw hf(i,s?.callee),i}return a.value},I3=gf(Ha),_f=t=>async(e,r,n,s)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Kr(c,o,Wr())));throw hf(i,s?.callee),i}return a.value},R3=_f(Ha),vf=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Vs;return o.issues.length?{success:!1,error:new(t??mf)(o.issues.map(a=>Kr(a,s,Wr())))}:{success:!0,data:o.value}},Ba=vf(Ha),yf=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>Kr(a,s,Wr())))}:{success:!0,data:o.value}},Vc=yf(Ha),P3=/^[cC][^\s-]{8,}$/,O3=/^[0-9a-z]+$/,A3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M3=/^[0-9a-vA-V]{20}$/,N3=/^[A-Za-z0-9]{27}$/,L3=/^[a-zA-Z0-9_-]{21}$/,q3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,j3=/^([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})$/,wf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,U3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,z3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function D3(){return new RegExp(z3,"u")}const Z3=/^(?:(?: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])$/,V3=/^(([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})$/,F3=/^((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])$/,H3=/^(([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])$/,B3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bf=/^[A-Za-z0-9_-]*$/,J3=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,W3=/^\+(?:[0-9]){6,14}[0-9]$/,Sf="(?:(?:\\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])))",G3=new RegExp(`^${Sf}$`);function kf(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function K3(t){return new RegExp(`^${kf(t)}$`)}function Y3(t){const e=kf({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Sf}T(?:${n})$`)}const Q3=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},X3=/^\d+$/,e9=/^-?\d+(?:\.\d+)?/i,t9=/true|false/i,r9=/null/i,n9=/^[^A-Z]*$/,s9=/^[^a-z]*$/,$t=J("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Cf={number:"number",bigint:"bigint",object:"date"},Tf=J("$ZodCheckLessThan",(t,e)=>{$t.init(t,e);const r=Cf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),$f=J("$ZodCheckGreaterThan",(t,e)=>{$t.init(t,e);const r=Cf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),o9=J("$ZodCheckMultipleOf",(t,e)=>{$t.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):g3(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),a9=J("$ZodCheckNumberFormat",(t,e)=>{$t.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,o]=w3[e.format];t._zod.onattach.push(a=>{const i=a._zod.bag;i.format=e.format,i.minimum=s,i.maximum=o,r&&(i.pattern=X3)}),t._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}}),i9=J("$ZodCheckMaxLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!zc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{const s=n.value;if(s.length<=e.maximum)return;const a=Zc(s);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),c9=J("$ZodCheckMinLength",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!zc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const a=Zc(s);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),l9=J("$ZodCheckLengthEquals",(t,e)=>{var r;$t.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!zc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,o=s.length;if(o===e.length)return;const a=Zc(s),i=o>e.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ja=J("$ZodCheckStringFormat",(t,e)=>{var r,n;$t.init(t,e),t._zod.onattach.push(s=>{const o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),u9=J("$ZodCheckRegex",(t,e)=>{Ja.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),d9=J("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=n9),Ja.init(t,e)}),p9=J("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=s9),Ja.init(t,e)}),h9=J("$ZodCheckIncludes",(t,e)=>{$t.init(t,e);const r=Bs(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),f9=J("$ZodCheckStartsWith",(t,e)=>{$t.init(t,e);const r=new RegExp(`^${Bs(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),m9=J("$ZodCheckEndsWith",(t,e)=>{$t.init(t,e);const r=new RegExp(`.*${Bs(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),g9=J("$ZodCheckOverwrite",(t,e)=>{$t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class _9{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
|
|
8
|
+
deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[l,u]=o(c);a(c,l),i(c,u)}};function o({schema:c}){const l={},u={};for(const p in c){if(p==="__proto__")continue;const h=Array.isArray(c[p])?l:u;h[p]=c[p]}return[l,u]}function a(c,l=c.schema){const{gen:u,data:p,it:h}=c;if(Object.keys(l).length===0)return;const d=u.let("missing");for(const f in l){const v=l[f];if(v.length===0)continue;const y=(0,n.propertyInData)(u,p,f,h.opts.ownProperties);c.setParams({property:f,depsCount:v.length,deps:v.join(", ")}),h.allErrors?u.if(y,()=>{for(const w of v)(0,n.checkReportMissingProp)(c,w)}):(u.if((0,e._)`${y} && (${(0,n.checkMissingProp)(c,v,d)})`),(0,n.reportMissingProp)(c,d),u.else())}}t.validatePropertyDeps=a;function i(c,l=c.schema){const{gen:u,data:p,keyword:h,it:d}=c,f=u.name("valid");for(const v in l)(0,r.alwaysValidSchema)(d,l[v])||(u.if((0,n.propertyInData)(u,p,v,d.opts.ownProperties),()=>{const y=c.subschema({keyword:h,schemaProp:v},f);c.mergeValidEvaluated(y,f)},()=>u.var(f,!0)),c.ok(f))}t.validateSchemaDeps=i,t.default=s})(ec)),ec}var ca={},kp;function ev(){if(kp)return ca;kp=1,Object.defineProperty(ca,"__esModule",{value:!0});const t=Te(),e=Ae(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:s})=>(0,t._)`{propertyName: ${s.propertyName}}`},code(s){const{gen:o,schema:a,data:i,it:c}=s;if((0,e.alwaysValidSchema)(c,a))return;const l=o.name("valid");o.forIn("key",i,u=>{s.setParams({propertyName:u}),s.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},l),o.if((0,t.not)(l),()=>{s.error(!0),c.allErrors||o.break()})}),s.ok(l)}};return ca.default=n,ca}var la={},Sp;function Cp(){if(Sp)return la;Sp=1,Object.defineProperty(la,"__esModule",{value:!0});const t=Vt(),e=Te(),r=Lr(),n=Ae(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:c,parentSchema:l,data:u,errsCount:p,it:h}=a;if(!p)throw new Error("ajv implementation error");const{allErrors:d,opts:f}=h;if(h.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,c))return;const v=(0,t.allSchemaProperties)(l.properties),y=(0,t.allSchemaProperties)(l.patternProperties);w(),a.ok((0,e._)`${p} === ${r.default.errors}`);function w(){i.forIn("key",u,S=>{!v.length&&!y.length?b(S):i.if(g(S),()=>b(S))})}function g(S){let C;if(v.length>8){const x=(0,n.schemaRefOrVal)(h,l.properties,"properties");C=(0,t.isOwnProperty)(i,x,S)}else v.length?C=(0,e.or)(...v.map(x=>(0,e._)`${S} === ${x}`)):C=e.nil;return y.length&&(C=(0,e.or)(C,...y.map(x=>(0,e._)`${(0,t.usePattern)(a,x)}.test(${S})`))),(0,e.not)(C)}function _(S){i.code((0,e._)`delete ${u}[${S}]`)}function b(S){if(f.removeAdditional==="all"||f.removeAdditional&&c===!1){_(S);return}if(c===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof c=="object"&&!(0,n.alwaysValidSchema)(h,c)){const C=i.name("valid");f.removeAdditional==="failing"?(k(S,C,!1),i.if((0,e.not)(C),()=>{a.reset(),_(S)})):(k(S,C),d||i.if((0,e.not)(C),()=>i.break()))}}function k(S,C,x){const R={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};x===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(R,C)}}};return la.default=o,la}var ua={},Tp;function tv(){if(Tp)return ua;Tp=1,Object.defineProperty(ua,"__esModule",{value:!0});const t=jo(),e=Vt(),r=Ae(),n=Cp(),s={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,parentSchema:c,data:l,it:u}=o;u.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(u,n.default,"additionalProperties"));const p=(0,e.allSchemaProperties)(i);for(const y of p)u.definedProperties.add(y);u.opts.unevaluated&&p.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(p),u.props));const h=p.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(h.length===0)return;const d=a.name("valid");for(const y of h)f(y)?v(y):(a.if((0,e.propertyInData)(a,l,y,u.opts.ownProperties)),v(y),u.allErrors||a.else().var(d,!0),a.endIf()),o.it.definedProperties.add(y),o.ok(d);function f(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function v(y){o.subschema({keyword:"properties",schemaProp:y,dataProp:y},d)}}};return ua.default=s,ua}var da={},$p;function rv(){if($p)return da;$p=1,Object.defineProperty(da,"__esModule",{value:!0});const t=Vt(),e=Te(),r=Ae(),n=Ae(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,data:c,parentSchema:l,it:u}=o,{opts:p}=u,h=(0,t.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const f=p.strictSchema&&!p.allowMatchingProperties&&l.properties,v=a.name("valid");u.props!==!0&&!(u.props instanceof e.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:y}=u;w();function w(){for(const b of h)f&&g(b),u.allErrors?_(b):(a.var(v,!0),_(b),a.if(v))}function g(b){for(const k in f)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function _(b){a.forIn("key",c,k=>{a.if((0,e._)`${(0,t.usePattern)(o,b)}.test(${k})`,()=>{const S=d.includes(b);S||o.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?a.assign((0,e._)`${y}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,e.not)(v),()=>a.break())})})}}};return da.default=s,da}var pa={},Ep;function nv(){if(Ep)return pa;Ep=1,Object.defineProperty(pa,"__esModule",{value:!0});const t=Ae(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:o}=r;if((0,t.alwaysValidSchema)(o,s)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return pa.default=e,pa}var fa={},xp;function sv(){if(xp)return fa;xp=1,Object.defineProperty(fa,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Vt().validateUnion,error:{message:"must match a schema in anyOf"}};return fa.default=e,fa}var ha={},Ip;function ov(){if(Ip)return ha;Ip=1,Object.defineProperty(ha,"__esModule",{value:!0});const t=Te(),e=Ae(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:s})=>(0,t._)`{passingSchemas: ${s.passing}}`},code(s){const{gen:o,schema:a,parentSchema:i,it:c}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(c.opts.discriminator&&i.discriminator)return;const l=a,u=o.let("valid",!1),p=o.let("passing",null),h=o.name("_valid");s.setParams({passing:p}),o.block(d),s.result(u,()=>s.reset(),()=>s.error(!0));function d(){l.forEach((f,v)=>{let y;(0,e.alwaysValidSchema)(c,f)?o.var(h,!0):y=s.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},h),v>0&&o.if((0,t._)`${h} && ${u}`).assign(u,!1).assign(p,(0,t._)`[${p}, ${v}]`).else(),o.if(h,()=>{o.assign(u,!0),o.assign(p,v),y&&s.mergeEvaluated(y,t.Name)})})}}};return ha.default=n,ha}var ma={},Rp;function av(){if(Rp)return ma;Rp=1,Object.defineProperty(ma,"__esModule",{value:!0});const t=Ae(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:o}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((i,c)=>{if((0,t.alwaysValidSchema)(o,i))return;const l=r.subschema({keyword:"allOf",schemaProp:c},a);r.ok(a),r.mergeEvaluated(l)})}};return ma.default=e,ma}var ga={},Pp;function iv(){if(Pp)return ga;Pp=1,Object.defineProperty(ga,"__esModule",{value:!0});const t=Te(),e=Ae(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:o})=>(0,t.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,t._)`{failingKeyword: ${o.ifClause}}`},code(o){const{gen:a,parentSchema:i,it:c}=o;i.then===void 0&&i.else===void 0&&(0,e.checkStrictMode)(c,'"if" without "then" and "else" is ignored');const l=s(c,"then"),u=s(c,"else");if(!l&&!u)return;const p=a.let("valid",!0),h=a.name("_valid");if(d(),o.reset(),l&&u){const v=a.let("ifClause");o.setParams({ifClause:v}),a.if(h,f("then",v),f("else",v))}else l?a.if(h,f("then")):a.if((0,t.not)(h),f("else"));o.pass(p,()=>o.error(!0));function d(){const v=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);o.mergeEvaluated(v)}function f(v,y){return()=>{const w=o.subschema({keyword:v},h);a.assign(p,h),o.mergeValidEvaluated(w,p),y?a.assign(y,(0,t._)`${v}`):o.setParams({ifClause:v})}}}};function s(o,a){const i=o.schema[a];return i!==void 0&&!(0,e.alwaysValidSchema)(o,i)}return ga.default=n,ga}var ya={},Op;function cv(){if(Op)return ya;Op=1,Object.defineProperty(ya,"__esModule",{value:!0});const t=Ae(),e={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:s}){n.if===void 0&&(0,t.checkStrictMode)(s,`"${r}" without "if" is ignored`)}};return ya.default=e,ya}var Ap;function lv(){if(Ap)return sa;Ap=1,Object.defineProperty(sa,"__esModule",{value:!0});const t=mp(),e=K_(),r=yp(),n=Y_(),s=Q_(),o=X_(),a=ev(),i=Cp(),c=tv(),l=rv(),u=nv(),p=sv(),h=ov(),d=av(),f=iv(),v=cv();function y(w=!1){const g=[u.default,p.default,h.default,d.default,f.default,v.default,a.default,i.default,o.default,c.default,l.default];return w?g.push(e.default,n.default):g.push(t.default,r.default),g.push(s.default),g}return sa.default=y,sa}var _a={},va={},Mp;function uv(){if(Mp)return va;Mp=1,Object.defineProperty(va,"__esModule",{value:!0});const t=Te(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,s){const{gen:o,data:a,$data:i,schema:c,schemaCode:l,it:u}=n,{opts:p,errSchemaPath:h,schemaEnv:d,self:f}=u;if(!p.validateFormats)return;i?v():y();function v(){const w=o.scopeValue("formats",{ref:f.formats,code:p.code.formats}),g=o.const("fDef",(0,t._)`${w}[${l}]`),_=o.let("fType"),b=o.let("format");o.if((0,t._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>o.assign(_,(0,t._)`${g}.type || "string"`).assign(b,(0,t._)`${g}.validate`),()=>o.assign(_,(0,t._)`"string"`).assign(b,g)),n.fail$data((0,t.or)(k(),S()));function k(){return p.strictSchema===!1?t.nil:(0,t._)`${l} && !${b}`}function S(){const C=d.$async?(0,t._)`(${g}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,t._)`${b}(${a})`,x=(0,t._)`(typeof ${b} == "function" ? ${C} : ${b}.test(${a}))`;return(0,t._)`${b} && ${b} !== true && ${_} === ${s} && !${x}`}}function y(){const w=f.formats[c];if(!w){k();return}if(w===!0)return;const[g,_,b]=S(w);g===s&&n.pass(C());function k(){if(p.strictSchema===!1){f.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${c}" ignored in schema at path "${h}"`}}function S(x){const R=x instanceof RegExp?(0,t.regexpCode)(x):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(c)}`:void 0,j=o.scopeValue("formats",{key:c,ref:x,code:R});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,t._)`${j}.validate`]:["string",x,j]}function C(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!d.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${a})`}return typeof _=="function"?(0,t._)`${b}(${a})`:(0,t._)`${b}.test(${a})`}}}};return va.default=r,va}var Np;function dv(){if(Np)return _a;Np=1,Object.defineProperty(_a,"__esModule",{value:!0});const e=[uv().default];return _a.default=e,_a}var on={},Lp;function pv(){return Lp||(Lp=1,Object.defineProperty(on,"__esModule",{value:!0}),on.contentVocabulary=on.metadataVocabulary=void 0,on.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],on.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),on}var jp;function fv(){if(jp)return Zo;jp=1,Object.defineProperty(Zo,"__esModule",{value:!0});const t=j_(),e=G_(),r=lv(),n=dv(),s=pv(),o=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return Zo.default=o,Zo}var wa={},ms={},qp;function hv(){if(qp)return ms;qp=1,Object.defineProperty(ms,"__esModule",{value:!0}),ms.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||(ms.DiscrError=t={})),ms}var zp;function mv(){if(zp)return wa;zp=1,Object.defineProperty(wa,"__esModule",{value:!0});const t=Te(),e=hv(),r=Ki(),n=Do(),s=Ae(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:c}})=>i===e.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:i,tag:c,tagName:l}})=>(0,t._)`{error: ${i}, tag: ${l}, tagValue: ${c}}`},code(i){const{gen:c,data:l,schema:u,parentSchema:p,it:h}=i,{oneOf:d}=p;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const v=c.let("valid",!1),y=c.const("tag",(0,t._)`${l}${(0,t.getProperty)(f)}`);c.if((0,t._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:e.DiscrError.Tag,tag:y,tagName:f})),i.ok(v);function w(){const b=_();c.if(!1);for(const k in b)c.elseIf((0,t._)`${y} === ${k}`),c.assign(v,g(b[k]));c.else(),i.error(!1,{discrError:e.DiscrError.Mapping,tag:y,tagName:f}),c.endIf()}function g(b){const k=c.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,t.Name),k}function _(){var b;const k={},S=x(p);let C=!0;for(let O=0;O<d.length;O++){let D=d[O];if(D?.$ref&&!(0,s.schemaHasRulesButRef)(D,h.self.RULES)){const V=D.$ref;if(D=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,V),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(h.opts.uriResolver,h.baseId,V)}const U=(b=D?.properties)===null||b===void 0?void 0:b[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);C=C&&(S||x(D)),R(U,O)}if(!C)throw new Error(`discriminator: "${f}" must be required`);return k;function x({required:O}){return Array.isArray(O)&&O.includes(f)}function R(O,D){if(O.const)j(O.const,D);else if(O.enum)for(const U of O.enum)j(U,D);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function j(O,D){if(typeof O!="string"||O in k)throw new Error(`discriminator: "${f}" values must be unique strings`);k[O]=D}}}};return wa.default=a,wa}const gv={$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 Dp;function Up(){return Dp||(Dp=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=M_(),n=fv(),s=mv(),o=gv,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(f,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=jo();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Te();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var p=Gi();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var h=Do();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})(Po,Po.exports)),Po.exports}var yv=Up();const Zp=rn(yv);var Re;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(const a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Re||(Re={}));var tc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tc||(tc={}));const se=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),br=t=>{switch(typeof t){case"undefined":return se.undefined;case"string":return se.string;case"number":return Number.isNaN(t)?se.nan:se.number;case"boolean":return se.boolean;case"function":return se.function;case"bigint":return se.bigint;case"symbol":return se.symbol;case"object":return Array.isArray(t)?se.array:t===null?se.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?se.promise:typeof Map<"u"&&t instanceof Map?se.map:typeof Set<"u"&&t instanceof Set?se.set:typeof Date<"u"&&t instanceof Date?se.date:se.object;default:return se.unknown}},Y=Re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),_v=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class It extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof It))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}It.create=t=>new It(t);const xn=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===se.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Re.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Re.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Re.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Re.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Re.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Re.assertNever(t)}return{message:r}};let Fp=xn;function vv(t){Fp=t}function ba(){return Fp}const ka=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)i=l(a,{data:e,defaultError:i}).message;return{...s,path:o,message:i}},wv=[];function ee(t,e){const r=ba(),n=ka({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xn?void 0:xn].filter(s=>!!s)});t.common.issues.push(n)}class ut{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return ge;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return ut.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return ge;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const ge=Object.freeze({status:"aborted"}),In=t=>({status:"dirty",value:t}),ft=t=>({status:"valid",value:t}),rc=t=>t.status==="aborted",nc=t=>t.status==="dirty",an=t=>t.status==="valid",gs=t=>typeof Promise<"u"&&t instanceof Promise;var ce;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ce||(ce={}));class cr{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Vp=(t,e)=>{if(an(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new It(t.common.issues);return this._error=r,this._error}}};function Se(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??r??i.defaultError}},description:s}}let Ce=class{get description(){return this._def.description}_getType(e){return br(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ut,ctx:{common:e.parent.common,data:e.data,parsedType:br(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(gs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:br(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Vp(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:br(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return an(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>an(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:br(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(gs(s)?s:Promise.resolve(s));return Vp(n,o)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{const a=e(s),i=()=>o.addIssue({code:Y.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Ht({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Bt.create(this,this._def)}nullable(){return zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return un.create(this)}promise(){return Mn.create(this,this._def)}or(e){return bs.create([this,e],this._def)}and(e){return ks.create(this,e,this._def)}transform(e){return new Ht({...Se(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Es({...Se(this._def),innerType:this,defaultValue:r,typeName:z.ZodDefault})}brand(){return new ac({typeName:z.ZodBranded,type:this,...Se(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new xs({...Se(this._def),innerType:this,catchValue:r,typeName:z.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Is.create(this,e)}readonly(){return Rs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bv=/^c[^\s-]{8,}$/i,kv=/^[0-9a-z]+$/,Sv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cv=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Tv=/^[a-z0-9_-]{21}$/i,$v=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ev=/^[-+]?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)?)??$/,xv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Iv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let sc;const Rv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Pv=/^(?:(?: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])$/,Ov=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Av=/^(([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])$/,Mv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Hp="((\\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])))",Lv=new RegExp(`^${Hp}$`);function Bp(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function jv(t){return new RegExp(`^${Bp(t)}$`)}function Jp(t){let e=`${Hp}T${Bp(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function qv(t,e){return!!((e==="v4"||!e)&&Rv.test(t)||(e==="v6"||!e)&&Ov.test(t))}function zv(t,e){if(!$v.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Dv(t,e){return!!((e==="v4"||!e)&&Pv.test(t)||(e==="v6"||!e)&&Av.test(t))}let Rn=class Ro extends Ce{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==se.string){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.string,received:o.parsedType}),ge}const n=new ut;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?ee(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&ee(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")xv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"email",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")sc||(sc=new RegExp(Iv,"u")),sc.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"emoji",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Cv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"uuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Tv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"nanoid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")bv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")kv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cuid2",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Sv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"ulid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ee(s,{validation:"url",code:Y.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"regex",code:Y.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Jp(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Lv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?jv(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Ev.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"duration",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?qv(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"ip",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?zv(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"jwt",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Dv(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"cidr",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Mv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"base64",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Nv.test(e.data)||(s=this._getOrReturnCtx(e,s),ee(s,{validation:"base64url",code:Y.invalid_string,message:o.message}),n.dirty()):Re.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Y.invalid_string,...ce.errToObj(n)})}_addCheck(e){return new Ro({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ce.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ce.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ce.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ce.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ce.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ce.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ce.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ce.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ce.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ce.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ce.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ce.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ce.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ce.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ce.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ce.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ce.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ce.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ce.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ce.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ce.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ce.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ce.errToObj(r)})}nonempty(e){return this.min(1,ce.errToObj(e))}trim(){return new Ro({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ro({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ro({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...Se(t)});function Uv(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}let ys=class gd extends Ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==se.number){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.number,received:o.parsedType}),ge}let n;const s=new ut;for(const o of this._def.checks)o.kind==="int"?Re.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Uv(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_finite,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ce.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ce.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ce.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ce.toString(r))}setLimit(e,r,n,s){return new gd({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new gd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ce.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ce.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ce.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ce.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ce.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Re.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ys.create=t=>new ys({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...Se(t)});class qr extends Ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==se.bigint)return this._getInvalidInput(e);let n;const s=new ut;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ee(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return ee(r,{code:Y.invalid_type,expected:se.bigint,received:r.parsedType}),ge}gte(e,r){return this.setLimit("min",e,!0,ce.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ce.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ce.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ce.toString(r))}setLimit(e,r,n,s){return new qr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new qr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}qr.create=t=>new qr({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...Se(t)});let _s=class extends Ce{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==se.boolean){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.boolean,received:n.parsedType}),ge}return ft(e.data)}};_s.create=t=>new _s({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...Se(t)});class cn extends Ce{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==se.date){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_type,expected:se.date,received:o.parsedType}),ge}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return ee(o,{code:Y.invalid_date}),ge}const n=new ut;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),ee(s,{code:Y.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Re.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new cn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ce.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ce.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}cn.create=t=>new cn({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...Se(t)});class Sa extends Ce{_parse(e){if(this._getType(e)!==se.symbol){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.symbol,received:n.parsedType}),ge}return ft(e.data)}}Sa.create=t=>new Sa({typeName:z.ZodSymbol,...Se(t)});class vs extends Ce{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.undefined,received:n.parsedType}),ge}return ft(e.data)}}vs.create=t=>new vs({typeName:z.ZodUndefined,...Se(t)});let ws=class extends Ce{_parse(e){if(this._getType(e)!==se.null){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.null,received:n.parsedType}),ge}return ft(e.data)}};ws.create=t=>new ws({typeName:z.ZodNull,...Se(t)});let Pn=class extends Ce{constructor(){super(...arguments),this._any=!0}_parse(e){return ft(e.data)}};Pn.create=t=>new Pn({typeName:z.ZodAny,...Se(t)});let ln=class extends Ce{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ft(e.data)}};ln.create=t=>new ln({typeName:z.ZodUnknown,...Se(t)});let kr=class extends Ce{_parse(e){const r=this._getOrReturnCtx(e);return ee(r,{code:Y.invalid_type,expected:se.never,received:r.parsedType}),ge}};kr.create=t=>new kr({typeName:z.ZodNever,...Se(t)});class Ca extends Ce{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.void,received:n.parsedType}),ge}return ft(e.data)}}Ca.create=t=>new Ca({typeName:z.ZodVoid,...Se(t)});let un=class Ui extends Ce{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==se.array)return ee(r,{code:Y.invalid_type,expected:se.array,received:r.parsedType}),ge;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,i=r.data.length<s.exactLength.value;(a||i)&&(ee(r,{code:a?Y.too_big:Y.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(ee(r,{code:Y.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(ee(r,{code:Y.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>s.type._parseAsync(new cr(r,a,r.path,i)))).then(a=>ut.mergeArray(n,a));const o=[...r.data].map((a,i)=>s.type._parseSync(new cr(r,a,r.path,i)));return ut.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new Ui({...this._def,minLength:{value:e,message:ce.toString(r)}})}max(e,r){return new Ui({...this._def,maxLength:{value:e,message:ce.toString(r)}})}length(e,r){return new Ui({...this._def,exactLength:{value:e,message:ce.toString(r)}})}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...Se(e)});function On(t){if(t instanceof Lt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Bt.create(On(n))}return new Lt({...t._def,shape:()=>e})}else return t instanceof un?new un({...t._def,type:On(t.element)}):t instanceof Bt?Bt.create(On(t.unwrap())):t instanceof zr?zr.create(On(t.unwrap())):t instanceof lr?lr.create(t.items.map(e=>On(e))):t}let Lt=class ir extends Ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Re.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==se.object){const l=this._getOrReturnCtx(e);return ee(l,{code:Y.invalid_type,expected:se.object,received:l.parsedType}),ge}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof kr&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||i.push(l);const c=[];for(const l of a){const u=o[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new cr(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof kr){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of i)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")i.length>0&&(ee(s,{code:Y.unrecognized_keys,keys:i}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of i){const p=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new cr(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of c){const p=await u.key,h=await u.value;l.push({key:p,value:h,alwaysSet:u.alwaysSet})}return l}).then(l=>ut.mergeObjectSync(n,l)):ut.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ce.errToObj,new ir({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ce.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ir({...this._def,unknownKeys:"strip"})}passthrough(){return new ir({...this._def,unknownKeys:"passthrough"})}extend(e){return new ir({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ir({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ir({...this._def,catchall:e})}pick(e){const r={};for(const n of Re.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ir({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Re.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ir({...this._def,shape:()=>r})}deepPartial(){return On(this)}partial(e){const r={};for(const n of Re.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new ir({...this._def,shape:()=>r})}required(e){const r={};for(const n of Re.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Bt;)o=o._def.innerType;r[n]=o}return new ir({...this._def,shape:()=>r})}keyof(){return Kp(Re.objectKeys(this.shape))}};Lt.create=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strip",catchall:kr.create(),typeName:z.ZodObject,...Se(e)}),Lt.strictCreate=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strict",catchall:kr.create(),typeName:z.ZodObject,...Se(e)}),Lt.lazycreate=(t,e)=>new Lt({shape:t,unknownKeys:"strip",catchall:kr.create(),typeName:z.ZodObject,...Se(e)});let bs=class extends Ce{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new It(i.ctx.common.issues));return ee(r,{code:Y.invalid_union,unionErrors:a}),ge}if(r.common.async)return Promise.all(n.map(async o=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of n){const l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(c=>new It(c));return ee(r,{code:Y.invalid_union,unionErrors:i}),ge}}get options(){return this._def.options}};bs.create=(t,e)=>new bs({options:t,typeName:z.ZodUnion,...Se(e)});const Sr=t=>t instanceof Ss?Sr(t.schema):t instanceof Ht?Sr(t.innerType()):t instanceof Cs?[t.value]:t instanceof Ts?t.options:t instanceof $s?Re.objectValues(t.enum):t instanceof Es?Sr(t._def.innerType):t instanceof vs?[void 0]:t instanceof ws?[null]:t instanceof Bt?[void 0,...Sr(t.unwrap())]:t instanceof zr?[null,...Sr(t.unwrap())]:t instanceof ac||t instanceof Rs?Sr(t.unwrap()):t instanceof xs?Sr(t._def.innerType):[];let Wp=class w_ extends Ce{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.object)return ee(r,{code:Y.invalid_type,expected:se.object,received:r.parsedType}),ge;const n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(ee(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ge)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const o of r){const a=Sr(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o)}}return new w_({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Se(n)})}};function oc(t,e){const r=br(t),n=br(e);if(t===e)return{valid:!0,data:t};if(r===se.object&&n===se.object){const s=Re.objectKeys(e),o=Re.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(const i of o){const c=oc(t[i],e[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(r===se.array&&n===se.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const a=t[o],i=e[o],c=oc(a,i);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===se.date&&n===se.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ks=class extends Ce{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(rc(o)||rc(a))return ge;const i=oc(o.value,a.value);return i.valid?((nc(o)||nc(a))&&r.dirty(),{status:r.value,value:i.data}):(ee(n,{code:Y.invalid_intersection_types}),ge)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ks.create=(t,e,r)=>new ks({left:t,right:e,typeName:z.ZodIntersection,...Se(r)});class lr extends Ce{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.array)return ee(n,{code:Y.invalid_type,expected:se.array,received:n.parsedType}),ge;if(n.data.length<this._def.items.length)return ee(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ge;!this._def.rest&&n.data.length>this._def.items.length&&(ee(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((a,i)=>{const c=this._def.items[i]||this._def.rest;return c?c._parse(new cr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ut.mergeArray(r,a)):ut.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new lr({...this._def,rest:e})}}lr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lr({items:t,typeName:z.ZodTuple,rest:null,...Se(e)})};let Gp=class yd extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.object)return ee(n,{code:Y.invalid_type,expected:se.object,received:n.parsedType}),ge;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in n.data)s.push({key:o._parse(new cr(n,i,n.path,i)),value:a._parse(new cr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ut.mergeObjectAsync(r,s):ut.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ce?new yd({keyType:e,valueType:r,typeName:z.ZodRecord,...Se(n)}):new yd({keyType:Rn.create(),valueType:e,typeName:z.ZodRecord,...Se(r)})}};class Ta extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.map)return ee(n,{code:Y.invalid_type,expected:se.map,received:n.parsedType}),ge;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([i,c],l)=>({key:s._parse(new cr(n,i,n.path,[l,"key"])),value:o._parse(new cr(n,c,n.path,[l,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const c of a){const l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ge;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(l.value,u.value)}return{status:r.value,value:i}}}}Ta.create=(t,e,r)=>new Ta({valueType:e,keyType:t,typeName:z.ZodMap,...Se(r)});class dn extends Ce{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.set)return ee(n,{code:Y.invalid_type,expected:se.set,received:n.parsedType}),ge;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(ee(n,{code:Y.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(ee(n,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const o=this._def.valueType;function a(c){const l=new Set;for(const u of c){if(u.status==="aborted")return ge;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}const i=[...n.data.values()].map((c,l)=>o._parse(new cr(n,c,n.path,l)));return n.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(e,r){return new dn({...this._def,minSize:{value:e,message:ce.toString(r)}})}max(e,r){return new dn({...this._def,maxSize:{value:e,message:ce.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...Se(e)});class An extends Ce{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.function)return ee(r,{code:Y.invalid_type,expected:se.function,received:r.parsedType}),ge;function n(i,c){return ka({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ba(),xn].filter(l=>!!l),issueData:{code:Y.invalid_arguments,argumentsError:c}})}function s(i,c){return ka({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ba(),xn].filter(l=>!!l),issueData:{code:Y.invalid_return_type,returnTypeError:c}})}const o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mn){const i=this;return ft(async function(...c){const l=new It([]),u=await i._def.args.parseAsync(c,o).catch(d=>{throw l.addIssue(n(c,d)),l}),p=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(p,o).catch(d=>{throw l.addIssue(s(p,d)),l})})}else{const i=this;return ft(function(...c){const l=i._def.args.safeParse(c,o);if(!l.success)throw new It([n(c,l.error)]);const u=Reflect.apply(a,this,l.data),p=i._def.returns.safeParse(u,o);if(!p.success)throw new It([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new An({...this._def,args:lr.create(e).rest(ln.create())})}returns(e){return new An({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new An({args:e||lr.create([]).rest(ln.create()),returns:r||ln.create(),typeName:z.ZodFunction,...Se(n)})}}let Ss=class extends Ce{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ss.create=(t,e)=>new Ss({getter:t,typeName:z.ZodLazy,...Se(e)});let Cs=class extends Ce{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return ee(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),ge}return{status:"valid",value:e.data}}get value(){return this._def.value}};Cs.create=(t,e)=>new Cs({value:t,typeName:z.ZodLiteral,...Se(e)});function Kp(t,e){return new Ts({values:t,typeName:z.ZodEnum,...Se(e)})}let Ts=class _d extends Ce{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return ee(r,{expected:Re.joinValues(n),received:r.parsedType,code:Y.invalid_type}),ge}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return ee(r,{received:r.data,code:Y.invalid_enum_value,options:n}),ge}return ft(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return _d.create(e,{...this._def,...r})}exclude(e,r=this._def){return _d.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ts.create=Kp;class $s extends Ce{_parse(e){const r=Re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==se.string&&n.parsedType!==se.number){const s=Re.objectValues(r);return ee(n,{expected:Re.joinValues(s),received:n.parsedType,code:Y.invalid_type}),ge}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Re.objectValues(r);return ee(n,{received:n.data,code:Y.invalid_enum_value,options:s}),ge}return ft(e.data)}get enum(){return this._def.values}}$s.create=(t,e)=>new $s({values:t,typeName:z.ZodNativeEnum,...Se(e)});class Mn extends Ce{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==se.promise&&r.common.async===!1)return ee(r,{code:Y.invalid_type,expected:se.promise,received:r.parsedType}),ge;const n=r.parsedType===se.promise?r.data:Promise.resolve(r.data);return ft(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Mn.create=(t,e)=>new Mn({type:t,typeName:z.ZodPromise,...Se(e)});class Ht extends Ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{ee(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return ge;const c=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return c.status==="aborted"?ge:c.status==="dirty"||r.value==="dirty"?In(c.value):c});{if(r.value==="aborted")return ge;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?ge:i.status==="dirty"||r.value==="dirty"?In(i.value):i}}if(s.type==="refinement"){const a=i=>{const c=s.refinement(i,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?ge:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!an(a))return ge;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>an(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:r.value,value:i})):ge);Re.assertNever(s)}}Ht.create=(t,e,r)=>new Ht({schema:t,typeName:z.ZodEffects,effect:e,...Se(r)}),Ht.createWithPreprocess=(t,e,r)=>new Ht({schema:e,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...Se(r)});let Bt=class extends Ce{_parse(e){return this._getType(e)===se.undefined?ft(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:z.ZodOptional,...Se(e)});let zr=class extends Ce{_parse(e){return this._getType(e)===se.null?ft(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:z.ZodNullable,...Se(e)});let Es=class extends Ce{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===se.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Es.create=(t,e)=>new Es({innerType:t,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Se(e)});let xs=class extends Ce{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new It(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new It(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xs.create=(t,e)=>new xs({innerType:t,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Se(e)});class $a extends Ce{_parse(e){if(this._getType(e)!==se.nan){const n=this._getOrReturnCtx(e);return ee(n,{code:Y.invalid_type,expected:se.nan,received:n.parsedType}),ge}return{status:"valid",value:e.data}}}$a.create=t=>new $a({typeName:z.ZodNaN,...Se(t)});const Zv=Symbol("zod_brand");class ac extends Ce{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Is extends Ce{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ge:o.status==="dirty"?(r.dirty(),In(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ge:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Is({in:e,out:r,typeName:z.ZodPipeline})}}let Rs=class extends Ce{_parse(e){const r=this._def.innerType._parse(e),n=s=>(an(s)&&(s.value=Object.freeze(s.value)),s);return gs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Rs.create=(t,e)=>new Rs({innerType:t,typeName:z.ZodReadonly,...Se(e)});function Yp(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Qp(t,e={},r){return t?Pn.create().superRefine((n,s)=>{const o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){const i=Yp(e,n),c=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:c})}});if(!o){const a=Yp(e,n),i=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:i})}}):Pn.create()}const Fv={object:Lt.lazycreate};var z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(z||(z={}));const Vv=(t,e={message:`Input not instance of ${t.name}`})=>Qp(r=>r instanceof t,e),Xp=Rn.create,ef=ys.create,Hv=$a.create,Bv=qr.create,tf=_s.create,Jv=cn.create,Wv=Sa.create,Gv=vs.create,Kv=ws.create,Yv=Pn.create,Qv=ln.create,Xv=kr.create,ew=Ca.create,tw=un.create,rf=Lt.create,rw=Lt.strictCreate,nw=bs.create,sw=Wp.create,ow=ks.create,aw=lr.create,iw=Gp.create,cw=Ta.create,lw=dn.create,uw=An.create,dw=Ss.create,pw=Cs.create,fw=Ts.create,hw=$s.create,mw=Mn.create,nf=Ht.create,gw=Bt.create,yw=zr.create,_w=Ht.createWithPreprocess,vw=Is.create,ww=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Zv,DIRTY:In,EMPTY_PATH:wv,INVALID:ge,NEVER:ge,OK:ft,ParseStatus:ut,Schema:Ce,ZodAny:Pn,ZodArray:un,ZodBigInt:qr,ZodBoolean:_s,ZodBranded:ac,ZodCatch:xs,ZodDate:cn,ZodDefault:Es,ZodDiscriminatedUnion:Wp,ZodEffects:Ht,ZodEnum:Ts,ZodError:It,get ZodFirstPartyTypeKind(){return z},ZodFunction:An,ZodIntersection:ks,ZodIssueCode:Y,ZodLazy:Ss,ZodLiteral:Cs,ZodMap:Ta,ZodNaN:$a,ZodNativeEnum:$s,ZodNever:kr,ZodNull:ws,ZodNullable:zr,ZodNumber:ys,ZodObject:Lt,ZodOptional:Bt,ZodParsedType:se,ZodPipeline:Is,ZodPromise:Mn,ZodReadonly:Rs,ZodRecord:Gp,ZodSchema:Ce,ZodSet:dn,ZodString:Rn,ZodSymbol:Sa,ZodTransformer:Ht,ZodTuple:lr,ZodType:Ce,ZodUndefined:vs,ZodUnion:bs,ZodUnknown:ln,ZodVoid:Ca,addIssueToContext:ee,any:Yv,array:tw,bigint:Bv,boolean:tf,coerce:{string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ys.create({...t,coerce:!0})),boolean:(t=>_s.create({...t,coerce:!0})),bigint:(t=>qr.create({...t,coerce:!0})),date:(t=>cn.create({...t,coerce:!0}))},custom:Qp,date:Jv,datetimeRegex:Jp,defaultErrorMap:xn,discriminatedUnion:sw,effect:nf,enum:fw,function:uw,getErrorMap:ba,getParsedType:br,instanceof:Vv,intersection:ow,isAborted:rc,isAsync:gs,isDirty:nc,isValid:an,late:Fv,lazy:dw,literal:pw,makeIssue:ka,map:cw,nan:Hv,nativeEnum:hw,never:Xv,null:Kv,nullable:yw,number:ef,object:rf,get objectUtil(){return tc},oboolean:()=>tf().optional(),onumber:()=>ef().optional(),optional:gw,ostring:()=>Xp().optional(),pipeline:vw,preprocess:_w,promise:mw,quotelessJson:_v,record:iw,set:lw,setErrorMap:vv,strictObject:rw,string:Xp,symbol:Wv,transformer:nf,tuple:aw,undefined:Gv,union:nw,unknown:Qv,get util(){return Re},void:ew},Symbol.toStringTag,{value:"Module"})),sf=Object.freeze({status:"aborted"});function J(t,e,r){function n(i,c){var l;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(l=i._zod).traits??(l.traits=new Set),i._zod.traits.add(t),e(i,c);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=c}const s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function a(i){var c;const l=r?.Parent?new o:this;n(l,i),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}class Ps extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const of={};function Dr(t){return of}function af(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function bw(t,e){return typeof e=="bigint"?e.toString():e}function ic(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function cc(t){return t==null}function lc(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function kw(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function Me(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Os(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function As(t){return JSON.stringify(t)}const cf=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ea(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Sw=ic(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function xa(t){if(Ea(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ea(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Cw=new Set(["string","number","symbol"]);function Ms(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ur(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Tw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const $w={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 Ew(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Ur(t,{...t._zod.def,shape:r,checks:[]})}function xw(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Ur(t,{...t._zod.def,shape:r,checks:[]})}function Iw(t,e){if(!xa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return Os(this,"shape",n),n},checks:[]};return Ur(t,r)}function Rw(t,e){return Ur(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Os(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Pw(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(const o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Ur(e,{...e._zod.def,shape:s,checks:[]})}function Ow(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(const o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Ur(e,{...e._zod.def,shape:s,checks:[]})}function Ns(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function pn(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ia(t){return typeof t=="string"?t:t?.message}function Zr(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Ia(t.inst?._zod.def?.error?.(t))??Ia(e?.error?.(t))??Ia(r.customError?.(t))??Ia(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function uc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ls(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const lf=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,bw,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},uf=J("$ZodError",lf),Ra=J("$ZodError",lf,{Parent:Error});function Aw(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function Mw(t,e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(r(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(t),n}const df=t=>(e,r,n,s)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Ps;if(a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Zr(c,o,Dr())));throw cf(i,s?.callee),i}return a.value},Nw=df(Ra),pf=t=>async(e,r,n,s)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(s?.Err??t)(a.issues.map(c=>Zr(c,o,Dr())));throw cf(i,s?.callee),i}return a.value},Lw=pf(Ra),ff=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Ps;return o.issues.length?{success:!1,error:new(t??uf)(o.issues.map(a=>Zr(a,s,Dr())))}:{success:!0,data:o.value}},dc=ff(Ra),hf=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>Zr(a,s,Dr())))}:{success:!0,data:o.value}},pc=hf(Ra),jw=/^[cC][^\s-]{8,}$/,qw=/^[0-9a-z]+$/,zw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dw=/^[0-9a-vA-V]{20}$/,Uw=/^[A-Za-z0-9]{27}$/,Zw=/^[a-zA-Z0-9_-]{21}$/,Fw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vw=/^([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})$/,mf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Hw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Bw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Jw(){return new RegExp(Bw,"u")}const Ww=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Gw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Kw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yw=/^(([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])$/,Qw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gf=/^[A-Za-z0-9_-]*$/,Xw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,eb=/^\+(?:[0-9]){6,14}[0-9]$/,yf="(?:(?:\\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(`^${yf}$`);function _f(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function rb(t){return new RegExp(`^${_f(t)}$`)}function nb(t){const e=_f({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${yf}T(?:${n})$`)}const sb=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ob=/^\d+$/,ab=/^-?\d+(?:\.\d+)?/i,ib=/true|false/i,cb=/null/i,lb=/^[^A-Z]*$/,ub=/^[^a-z]*$/,kt=J("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),vf={number:"number",bigint:"bigint",object:"date"},wf=J("$ZodCheckLessThan",(t,e)=>{kt.init(t,e);const r=vf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),bf=J("$ZodCheckGreaterThan",(t,e)=>{kt.init(t,e);const r=vf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),db=J("$ZodCheckMultipleOf",(t,e)=>{kt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):kw(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),pb=J("$ZodCheckNumberFormat",(t,e)=>{kt.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,o]=$w[e.format];t._zod.onattach.push(a=>{const i=a._zod.bag;i.format=e.format,i.minimum=s,i.maximum=o,r&&(i.pattern=ob)}),t._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}}),fb=J("$ZodCheckMaxLength",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{const s=n.value;if(s.length<=e.maximum)return;const a=uc(s);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),hb=J("$ZodCheckMinLength",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const a=uc(s);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),mb=J("$ZodCheckLengthEquals",(t,e)=>{var r;kt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!cc(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,o=s.length;if(o===e.length)return;const a=uc(s),i=o>e.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Pa=J("$ZodCheckStringFormat",(t,e)=>{var r,n;kt.init(t,e),t._zod.onattach.push(s=>{const o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),gb=J("$ZodCheckRegex",(t,e)=>{Pa.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),yb=J("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=lb),Pa.init(t,e)}),_b=J("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ub),Pa.init(t,e)}),vb=J("$ZodCheckIncludes",(t,e)=>{kt.init(t,e);const r=Ms(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),wb=J("$ZodCheckStartsWith",(t,e)=>{kt.init(t,e);const r=new RegExp(`^${Ms(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),bb=J("$ZodCheckEndsWith",(t,e)=>{kt.init(t,e);const r=new RegExp(`.*${Ms(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),kb=J("$ZodCheckOverwrite",(t,e)=>{kt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class Sb{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
|
|
9
9
|
`).filter(a=>a),s=Math.min(...n.map(a=>a.length-a.trimStart().length)),o=n.map(a=>a.slice(s)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
|
|
10
|
-
`))}}const
|
|
11
|
-
if (${
|
|
10
|
+
`))}}const Cb={major:4,minor:0,patch:0},Ze=J("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Cb;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const s of n)for(const o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,a,i)=>{let c=Ns(o),l;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(c)continue;const p=o.issues.length,h=u._zod.check(o);if(h instanceof Promise&&i?.async===!1)throw new Ps;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await h,o.issues.length!==p&&(c||(c=Ns(o,p)))});else{if(o.issues.length===p)continue;c||(c=Ns(o,p))}}return l?l.then(()=>o):o};t._zod.run=(o,a)=>{const i=t._zod.parse(o,a);if(i instanceof Promise){if(a.async===!1)throw new Ps;return i.then(c=>s(c,n,a))}return s(i,n,a)}}t["~standard"]={validate:s=>{try{const o=dc(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return pc(t,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),fc=J("$ZodString",(t,e)=>{Ze.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??sb(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Je=J("$ZodStringFormat",(t,e)=>{Pa.init(t,e),fc.init(t,e)}),Tb=J("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Vw),Je.init(t,e)}),$b=J("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=mf(n))}else e.pattern??(e.pattern=mf());Je.init(t,e)}),Eb=J("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Hw),Je.init(t,e)}),xb=J("$ZodURL",(t,e)=>{Je.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Xw.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Ib=J("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Jw()),Je.init(t,e)}),Rb=J("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Zw),Je.init(t,e)}),Pb=J("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=jw),Je.init(t,e)}),Ob=J("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=qw),Je.init(t,e)}),Ab=J("$ZodULID",(t,e)=>{e.pattern??(e.pattern=zw),Je.init(t,e)}),Mb=J("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Dw),Je.init(t,e)}),Nb=J("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Uw),Je.init(t,e)}),Lb=J("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=nb(e)),Je.init(t,e)}),jb=J("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=tb),Je.init(t,e)}),qb=J("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=rb(e)),Je.init(t,e)}),zb=J("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Fw),Je.init(t,e)}),Db=J("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ww),Je.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),Ub=J("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Gw),Je.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Zb=J("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Kw),Je.init(t,e)}),Fb=J("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Yw),Je.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function kf(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Vb=J("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Qw),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{kf(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Hb(t){if(!gf.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return kf(r)}const Bb=J("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=gf),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Hb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Jb=J("$ZodE164",(t,e)=>{e.pattern??(e.pattern=eb),Je.init(t,e)});function Wb(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Gb=J("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=r=>{Wb(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Sf=J("$ZodNumber",(t,e)=>{Ze.init(t,e),t._zod.pattern=t._zod.bag.pattern??ab,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;const o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Kb=J("$ZodNumber",(t,e)=>{pb.init(t,e),Sf.init(t,e)}),Yb=J("$ZodBoolean",(t,e)=>{Ze.init(t,e),t._zod.pattern=ib,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Qb=J("$ZodNull",(t,e)=>{Ze.init(t,e),t._zod.pattern=cb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{const s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),Xb=J("$ZodAny",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),e3=J("$ZodUnknown",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),t3=J("$ZodNever",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Cf(t,e,r){t.issues.length&&e.issues.push(...pn(r,t.issues)),e.value[r]=t.value}const r3=J("$ZodArray",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);const o=[];for(let a=0;a<s.length;a++){const i=s[a],c=e.element._zod.run({value:i,issues:[]},n);c instanceof Promise?o.push(c.then(l=>Cf(l,r,a))):Cf(c,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function Oa(t,e,r){t.issues.length&&e.issues.push(...pn(r,t.issues)),e.value[r]=t.value}function Tf(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...pn(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const $f=J("$ZodObject",(t,e)=>{Ze.init(t,e);const r=ic(()=>{const p=Object.keys(e.shape);for(const d of p)if(!(e.shape[d]instanceof Ze))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=Tw(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(h)}});Me(t._zod,"propValues",()=>{const p=e.shape,h={};for(const d in p){const f=p[d]._zod;if(f.values){h[d]??(h[d]=new Set);for(const v of f.values)h[d].add(v)}}return h});const n=p=>{const h=new Sb(["shape","payload","ctx"]),d=r.value,f=g=>{const _=As(g);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const g of d.keys)v[g]=`key_${y++}`;h.write("const newResult = {}");for(const g of d.keys)if(d.optionalKeys.has(g)){const _=v[g];h.write(`const ${_} = ${f(g)};`);const b=As(g);h.write(`
|
|
11
|
+
if (${_}.issues.length) {
|
|
12
12
|
if (input[${b}] === undefined) {
|
|
13
13
|
if (${b} in input) {
|
|
14
14
|
newResult[${b}] = undefined;
|
|
15
15
|
}
|
|
16
16
|
} else {
|
|
17
17
|
payload.issues = payload.issues.concat(
|
|
18
|
-
${
|
|
18
|
+
${_}.issues.map((iss) => ({
|
|
19
19
|
...iss,
|
|
20
20
|
path: iss.path ? [${b}, ...iss.path] : [${b}],
|
|
21
21
|
}))
|
|
22
22
|
);
|
|
23
23
|
}
|
|
24
|
-
} else if (${
|
|
24
|
+
} else if (${_}.value === undefined) {
|
|
25
25
|
if (${b} in input) newResult[${b}] = undefined;
|
|
26
26
|
} else {
|
|
27
|
-
newResult[${b}] = ${
|
|
27
|
+
newResult[${b}] = ${_}.value;
|
|
28
28
|
}
|
|
29
|
-
`)}else{const
|
|
30
|
-
if (${
|
|
29
|
+
`)}else{const _=v[g];h.write(`const ${_} = ${f(g)};`),h.write(`
|
|
30
|
+
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
|
31
31
|
...iss,
|
|
32
|
-
path: iss.path ? [${
|
|
33
|
-
})));`),f.write(`newResult[${Hs(g)}] = ${y}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const w=f.compile();return(g,y)=>w(h,g,y)};let s;const o=Za,a=!df.jitless,c=a&&_3.value,l=e.catchall;let u;t._zod.parse=(h,f)=>{u??(u=r.value);const p=h.value;if(!o(p))return h.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),h;const m=[];if(a&&c&&f?.async===!1&&f.jitless!==!0)s||(s=n(e.shape)),h=s(h,f);else{h.value={};const y=u.shape;for(const b of u.keys){const S=y[b],k=S._zod.run({value:p[b],issues:[]},f),T=S._zod.optin==="optional"&&S._zod.optout==="optional";k instanceof Promise?m.push(k.then(x=>T?Rf(x,h,b,p):Wa(x,h,b))):T?Rf(k,h,b,p):Wa(k,h,b)}}if(!l)return m.length?Promise.all(m).then(()=>h):h;const v=[],_=u.keySet,w=l._zod,g=w.def.type;for(const y of Object.keys(p)){if(_.has(y))continue;if(g==="never"){v.push(y);continue}const b=w.run({value:p[y],issues:[]},f);b instanceof Promise?m.push(b.then(S=>Wa(S,h,y))):Wa(b,h,y)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:p,inst:t}),m.length?Promise.all(m).then(()=>h):h}});function Of(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>Kr(o,n,Wr())))}),e}const Af=J("$ZodUnion",(t,e)=>{He.init(t,e),qe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),qe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),qe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),qe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Dc(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const o=[];for(const a of e.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)o.push(i),s=!0;else{if(i.issues.length===0)return i;o.push(i)}}return s?Promise.all(o).then(a=>Of(a,r,t,n)):Of(o,r,t,n)}}),Y9=J("$ZodDiscriminatedUnion",(t,e)=>{Af.init(t,e);const r=t._zod.parse;qe(t._zod,"propValues",()=>{const s={};for(const o of e.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[i,c]of Object.entries(a)){s[i]||(s[i]=new Set);for(const l of c)s[i].add(l)}}return s});const n=Uc(()=>{const s=e.options,o=new Map;for(const a of s){const i=a._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const c of i){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,a)}}return o});t._zod.parse=(s,o)=>{const a=s.value;if(!Za(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const i=n.value.get(a?.[e.discriminator]);return i?i._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),Q9=J("$ZodIntersection",(t,e)=>{He.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,o=e.left._zod.run({value:s,issues:[]},n),a=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([c,l])=>Mf(r,c,l)):Mf(r,o,a)}});function Hc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Va(t)&&Va(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(const o of n){const a=Hc(t[o],e[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};s[o]=a.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<t.length;n++){const s=t[n],o=e[n],a=Hc(s,o);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mf(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Js(t))return t;const n=Hc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}const X9=J("$ZodRecord",(t,e)=>{He.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Va(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const o=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;r.value={};for(const c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const l=e.valueType._zod.run({value:s[c],issues:[]},n);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&r.issues.push(...bn(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...bn(c,l.issues)),r.value[c]=l.value)}let i;for(const c in s)a.has(c)||(i=i??[],i.push(c));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const i=e.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(l=>Kr(l,n,Wr())),input:a,path:[a],inst:t}),r.value[i.value]=i.value;continue}const c=e.valueType._zod.run({value:s[a],issues:[]},n);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&r.issues.push(...bn(a,l.issues)),r.value[i.value]=l.value})):(c.issues.length&&r.issues.push(...bn(a,c.issues)),r.value[i.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),e4=J("$ZodEnum",(t,e)=>{He.init(t,e);const r=pf(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>v3.has(typeof n)).map(n=>typeof n=="string"?Bs(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),t4=J("$ZodLiteral",(t,e)=>{He.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Bs(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),r4=J("$ZodTransform",(t,e)=>{He.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(r.value=a,r));if(s instanceof Promise)throw new Vs;return r.value=s,r}}),n4=J("$ZodOptional",(t,e)=>{He.init(t,e),t._zod.optin="optional",t._zod.optout="optional",qe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),qe(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Dc(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),s4=J("$ZodNullable",(t,e)=>{He.init(t,e),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Dc(r.source)}|null)$`):void 0}),qe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),o4=J("$ZodDefault",(t,e)=>{He.init(t,e),t._zod.optin="optional",qe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Nf(o,e)):Nf(s,e)}});function Nf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const a4=J("$ZodPrefault",(t,e)=>{He.init(t,e),t._zod.optin="optional",qe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),i4=J("$ZodNonOptional",(t,e)=>{He.init(t,e),qe(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Lf(o,t)):Lf(s,t)}});function Lf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const c4=J("$ZodCatch",(t,e)=>{He.init(t,e),t._zod.optin="optional",qe(t._zod,"optout",()=>e.innerType._zod.optout),qe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(a=>Kr(a,n,Wr()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Kr(o,n,Wr()))},input:r.value}),r.issues=[]),r)}}),l4=J("$ZodPipe",(t,e)=>{He.init(t,e),qe(t._zod,"values",()=>e.in._zod.values),qe(t._zod,"optin",()=>e.in._zod.optin),qe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>qf(o,e,n)):qf(s,e,n)}});function qf(t,e,r){return Js(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const u4=J("$ZodReadonly",(t,e)=>{He.init(t,e),qe(t._zod,"propValues",()=>e.innerType._zod.propValues),qe(t._zod,"values",()=>e.innerType._zod.values),qe(t._zod,"optin",()=>e.innerType._zod.optin),qe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(jf):jf(s)}});function jf(t){return t.value=Object.freeze(t.value),t}const d4=J("$ZodLazy",(t,e)=>{He.init(t,e),qe(t._zod,"innerType",()=>e.getter()),qe(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),qe(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),qe(t._zod,"optin",()=>t._zod.innerType._zod.optin),qe(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),p4=J("$ZodCustom",(t,e)=>{$t.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Uf(o,r,n,t));Uf(s,r,n,t)}});function Uf(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Ws(s))}}class zf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function h4(){return new zf}const Gs=h4();function f4(t,e){return new t({type:"string",...ce(e)})}function m4(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ce(e)})}function Df(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ce(e)})}function g4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ce(e)})}function _4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ce(e)})}function v4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ce(e)})}function y4(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ce(e)})}function Zf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ce(e)})}function w4(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ce(e)})}function b4(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ce(e)})}function S4(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ce(e)})}function k4(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ce(e)})}function C4(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ce(e)})}function T4(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ce(e)})}function $4(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ce(e)})}function E4(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ce(e)})}function x4(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ce(e)})}function I4(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ce(e)})}function R4(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ce(e)})}function Vf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ce(e)})}function P4(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ce(e)})}function O4(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ce(e)})}function A4(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ce(e)})}function M4(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ce(e)})}function N4(t,e){return new t({type:"string",format:"date",check:"string_format",...ce(e)})}function L4(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ce(e)})}function q4(t,e){return new t({type:"string",format:"duration",check:"string_format",...ce(e)})}function j4(t,e){return new t({type:"number",checks:[],...ce(e)})}function U4(t,e){return new t({type:"number",coerce:!0,checks:[],...ce(e)})}function z4(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ce(e)})}function D4(t,e){return new t({type:"boolean",...ce(e)})}function Z4(t,e){return new t({type:"null",...ce(e)})}function V4(t){return new t({type:"any"})}function F4(t){return new t({type:"unknown"})}function H4(t,e){return new t({type:"never",...ce(e)})}function Ff(t,e){return new Tf({check:"less_than",...ce(e),value:t,inclusive:!1})}function Bc(t,e){return new Tf({check:"less_than",...ce(e),value:t,inclusive:!0})}function Hf(t,e){return new $f({check:"greater_than",...ce(e),value:t,inclusive:!1})}function Jc(t,e){return new $f({check:"greater_than",...ce(e),value:t,inclusive:!0})}function Bf(t,e){return new o9({check:"multiple_of",...ce(e),value:t})}function Jf(t,e){return new i9({check:"max_length",...ce(e),maximum:t})}function Ga(t,e){return new c9({check:"min_length",...ce(e),minimum:t})}function Wf(t,e){return new l9({check:"length_equals",...ce(e),length:t})}function B4(t,e){return new u9({check:"string_format",format:"regex",...ce(e),pattern:t})}function J4(t){return new d9({check:"string_format",format:"lowercase",...ce(t)})}function W4(t){return new p9({check:"string_format",format:"uppercase",...ce(t)})}function G4(t,e){return new h9({check:"string_format",format:"includes",...ce(e),includes:t})}function K4(t,e){return new f9({check:"string_format",format:"starts_with",...ce(e),prefix:t})}function Y4(t,e){return new m9({check:"string_format",format:"ends_with",...ce(e),suffix:t})}function Ks(t){return new g9({check:"overwrite",tx:t})}function Q4(t){return Ks(e=>e.normalize(t))}function X4(){return Ks(t=>t.trim())}function eS(){return Ks(t=>t.toLowerCase())}function tS(){return Ks(t=>t.toUpperCase())}function rS(t,e,r){return new t({type:"array",element:e,...ce(r)})}function nS(t,e,r){const n=ce(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function sS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ce(r)})}class Gf{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Gs,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const h={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)i.ref=f,this.process(f,h),this.seen.get(f).isParent=!0;else{const p=i.schema;switch(s.type){case"string":{const m=p;m.type="string";const{minimum:v,maximum:_,format:w,patterns:g,contentEncoding:y}=e._zod.bag;if(typeof v=="number"&&(m.minLength=v),typeof _=="number"&&(m.maxLength=_),w&&(m.format=o[w]??w,m.format===""&&delete m.format),y&&(m.contentEncoding=y),g&&g.size>0){const b=[...g];b.length===1?m.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const m=p,{minimum:v,maximum:_,format:w,multipleOf:g,exclusiveMaximum:y,exclusiveMinimum:b}=e._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof b=="number"&&(m.exclusiveMinimum=b),typeof v=="number"&&(m.minimum=v,typeof b=="number"&&(b>=v?delete m.minimum:delete m.exclusiveMinimum)),typeof y=="number"&&(m.exclusiveMaximum=y),typeof _=="number"&&(m.maximum=_,typeof y=="number"&&(y<=_?delete m.maximum:delete m.exclusiveMaximum)),typeof g=="number"&&(m.multipleOf=g);break}case"boolean":{const m=p;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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=p,{minimum:v,maximum:_}=e._zod.bag;typeof v=="number"&&(m.minItems=v),typeof _=="number"&&(m.maxItems=_),m.type="array",m.items=this.process(s.element,{...h,path:[...h.path,"items"]});break}case"object":{const m=p;m.type="object",m.properties={};const v=s.shape;for(const g in v)m.properties[g]=this.process(v[g],{...h,path:[...h.path,"properties",g]});const _=new Set(Object.keys(v)),w=new Set([..._].filter(g=>{const y=s.shape[g]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));w.size>0&&(m.required=Array.from(w)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=p;m.anyOf=s.options.map((v,_)=>this.process(v,{...h,path:[...h.path,"anyOf",_]}));break}case"intersection":{const m=p,v=this.process(s.left,{...h,path:[...h.path,"allOf",0]}),_=this.process(s.right,{...h,path:[...h.path,"allOf",1]}),w=y=>"allOf"in y&&Object.keys(y).length===1,g=[...w(v)?v.allOf:[v],...w(_)?_.allOf:[_]];m.allOf=g;break}case"tuple":{const m=p;m.type="array";const v=s.items.map((g,y)=>this.process(g,{...h,path:[...h.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?m.prefixItems=v:m.items=v,s.rest){const g=this.process(s.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?m.items=g:m.additionalItems=g}s.rest&&(m.items=this.process(s.rest,{...h,path:[...h.path,"items"]}));const{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(m.minItems=_),typeof w=="number"&&(m.maxItems=w);break}case"record":{const m=p;m.type="object",m.propertyNames=this.process(s.keyType,{...h,path:[...h.path,"propertyNames"]}),m.additionalProperties=this.process(s.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=p,v=pf(s.entries);v.every(_=>typeof _=="number")&&(m.type="number"),v.every(_=>typeof _=="string")&&(m.type="string"),m.enum=v;break}case"literal":{const m=p,v=[];for(const _ of s.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(_))}else v.push(_);if(v.length!==0)if(v.length===1){const _=v[0];m.type=_===null?"null":typeof _,m.const=_}else v.every(_=>typeof _=="number")&&(m.type="number"),v.every(_=>typeof _=="string")&&(m.type="string"),v.every(_=>typeof _=="boolean")&&(m.type="string"),v.every(_=>_===null)&&(m.type="null"),m.enum=v;break}case"file":{const m=p,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:g}=e._zod.bag;_!==void 0&&(v.minLength=_),w!==void 0&&(v.maxLength=w),g?g.length===1?(v.contentMediaType=g[0],Object.assign(m,v)):m.anyOf=g.map(y=>({...v,contentMediaType:y})):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(s.innerType,h);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,h),i.ref=s.innerType;break}case"success":{const m=p;m.type="boolean";break}case"default":{this.process(s.innerType,h),i.ref=s.innerType,p.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,h),i.ref=s.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,h),i.ref=s.innerType;let m;try{m=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.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=p,v=e._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"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,h),i.ref=m;break}case"readonly":{this.process(s.innerType,h),i.ref=s.innerType,p.readOnly=!0;break}case"promise":{this.process(s.innerType,h),i.ref=s.innerType;break}case"optional":{this.process(s.innerType,h),i.ref=s.innerType;break}case"lazy":{const m=e._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 l=this.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),this.io==="input"&&tt(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=u=>{const h=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,_=n.external.uri??(g=>g);if(v)return{ref:_(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${_("__shared")}#/${h}/${w}`}}if(u[1]===s)return{ref:"#"};const p=`#/${h}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:p+m}},a=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:f,defId:p}=o(u);h.def={...h.schema},p&&(h.defId=p);const m=h.schema;for(const v in m)delete m[v];m.$ref=f};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 ? [${As(g)}, ...iss.path] : [${As(g)}]
|
|
33
|
+
})));`),h.write(`newResult[${As(g)}] = ${_}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const w=h.compile();return(g,_)=>w(p,g,_)};let s;const o=Ea,a=!of.jitless,c=a&&Sw.value,l=e.catchall;let u;t._zod.parse=(p,h)=>{u??(u=r.value);const d=p.value;if(!o(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;const f=[];if(a&&c&&h?.async===!1&&h.jitless!==!0)s||(s=n(e.shape)),p=s(p,h);else{p.value={};const _=u.shape;for(const b of u.keys){const k=_[b],S=k._zod.run({value:d[b],issues:[]},h),C=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?f.push(S.then(x=>C?Tf(x,p,b,d):Oa(x,p,b))):C?Tf(S,p,b,d):Oa(S,p,b)}}if(!l)return f.length?Promise.all(f).then(()=>p):p;const v=[],y=u.keySet,w=l._zod,g=w.def.type;for(const _ of Object.keys(d)){if(y.has(_))continue;if(g==="never"){v.push(_);continue}const b=w.run({value:d[_],issues:[]},h);b instanceof Promise?f.push(b.then(k=>Oa(k,p,_))):Oa(b,p,_)}return v.length&&p.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:t}),f.length?Promise.all(f).then(()=>p):p}});function Ef(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>Zr(o,n,Dr())))}),e}const xf=J("$ZodUnion",(t,e)=>{Ze.init(t,e),Me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>lc(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const o=[];for(const a of e.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)o.push(i),s=!0;else{if(i.issues.length===0)return i;o.push(i)}}return s?Promise.all(o).then(a=>Ef(a,r,t,n)):Ef(o,r,t,n)}}),n3=J("$ZodDiscriminatedUnion",(t,e)=>{xf.init(t,e);const r=t._zod.parse;Me(t._zod,"propValues",()=>{const s={};for(const o of e.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[i,c]of Object.entries(a)){s[i]||(s[i]=new Set);for(const l of c)s[i].add(l)}}return s});const n=ic(()=>{const s=e.options,o=new Map;for(const a of s){const i=a._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const c of i){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,a)}}return o});t._zod.parse=(s,o)=>{const a=s.value;if(!Ea(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const i=n.value.get(a?.[e.discriminator]);return i?i._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),s3=J("$ZodIntersection",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,o=e.left._zod.run({value:s,issues:[]},n),a=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([c,l])=>If(r,c,l)):If(r,o,a)}});function hc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(xa(t)&&xa(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(const o of n){const a=hc(t[o],e[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};s[o]=a.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<t.length;n++){const s=t[n],o=e[n],a=hc(s,o);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function If(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Ns(t))return t;const n=hc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}const o3=J("$ZodRecord",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!xa(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const o=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;r.value={};for(const c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const l=e.valueType._zod.run({value:s[c],issues:[]},n);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&r.issues.push(...pn(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...pn(c,l.issues)),r.value[c]=l.value)}let i;for(const c in s)a.has(c)||(i=i??[],i.push(c));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const i=e.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(l=>Zr(l,n,Dr())),input:a,path:[a],inst:t}),r.value[i.value]=i.value;continue}const c=e.valueType._zod.run({value:s[a],issues:[]},n);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&r.issues.push(...pn(a,l.issues)),r.value[i.value]=l.value})):(c.issues.length&&r.issues.push(...pn(a,c.issues)),r.value[i.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),a3=J("$ZodEnum",(t,e)=>{Ze.init(t,e);const r=af(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Cw.has(typeof n)).map(n=>typeof n=="string"?Ms(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),i3=J("$ZodLiteral",(t,e)=>{Ze.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ms(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),c3=J("$ZodTransform",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(r.value=a,r));if(s instanceof Promise)throw new Ps;return r.value=s,r}}),l3=J("$ZodOptional",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Me(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${lc(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),u3=J("$ZodNullable",(t,e)=>{Ze.init(t,e),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${lc(r.source)}|null)$`):void 0}),Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),d3=J("$ZodDefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Rf(o,e)):Rf(s,e)}});function Rf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const p3=J("$ZodPrefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),f3=J("$ZodNonOptional",(t,e)=>{Ze.init(t,e),Me(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Pf(o,t)):Pf(s,t)}});function Pf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const h3=J("$ZodCatch",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(a=>Zr(a,n,Dr()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Zr(o,n,Dr()))},input:r.value}),r.issues=[]),r)}}),m3=J("$ZodPipe",(t,e)=>{Ze.init(t,e),Me(t._zod,"values",()=>e.in._zod.values),Me(t._zod,"optin",()=>e.in._zod.optin),Me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Of(o,e,n)):Of(s,e,n)}});function Of(t,e,r){return Ns(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const g3=J("$ZodReadonly",(t,e)=>{Ze.init(t,e),Me(t._zod,"propValues",()=>e.innerType._zod.propValues),Me(t._zod,"values",()=>e.innerType._zod.values),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Af):Af(s)}});function Af(t){return t.value=Object.freeze(t.value),t}const y3=J("$ZodLazy",(t,e)=>{Ze.init(t,e),Me(t._zod,"innerType",()=>e.getter()),Me(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Me(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Me(t._zod,"optin",()=>t._zod.innerType._zod.optin),Me(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),_3=J("$ZodCustom",(t,e)=>{kt.init(t,e),Ze.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Mf(o,r,n,t));Mf(s,r,n,t)}});function Mf(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Ls(s))}}class Nf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function v3(){return new Nf}const js=v3();function w3(t,e){return new t({type:"string",...ae(e)})}function b3(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function Lf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function k3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function S3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function C3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function T3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function jf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function $3(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function E3(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function x3(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function I3(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function R3(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function P3(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function O3(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function A3(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function M3(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function N3(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function L3(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function qf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function j3(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function q3(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function z3(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function D3(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function U3(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function Z3(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function F3(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function V3(t,e){return new t({type:"number",checks:[],...ae(e)})}function H3(t,e){return new t({type:"number",coerce:!0,checks:[],...ae(e)})}function B3(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function J3(t,e){return new t({type:"boolean",...ae(e)})}function W3(t,e){return new t({type:"null",...ae(e)})}function G3(t){return new t({type:"any"})}function K3(t){return new t({type:"unknown"})}function Y3(t,e){return new t({type:"never",...ae(e)})}function zf(t,e){return new wf({check:"less_than",...ae(e),value:t,inclusive:!1})}function mc(t,e){return new wf({check:"less_than",...ae(e),value:t,inclusive:!0})}function Df(t,e){return new bf({check:"greater_than",...ae(e),value:t,inclusive:!1})}function gc(t,e){return new bf({check:"greater_than",...ae(e),value:t,inclusive:!0})}function Uf(t,e){return new db({check:"multiple_of",...ae(e),value:t})}function Zf(t,e){return new fb({check:"max_length",...ae(e),maximum:t})}function Aa(t,e){return new hb({check:"min_length",...ae(e),minimum:t})}function Ff(t,e){return new mb({check:"length_equals",...ae(e),length:t})}function Q3(t,e){return new gb({check:"string_format",format:"regex",...ae(e),pattern:t})}function X3(t){return new yb({check:"string_format",format:"lowercase",...ae(t)})}function e9(t){return new _b({check:"string_format",format:"uppercase",...ae(t)})}function t9(t,e){return new vb({check:"string_format",format:"includes",...ae(e),includes:t})}function r9(t,e){return new wb({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function n9(t,e){return new bb({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function qs(t){return new kb({check:"overwrite",tx:t})}function s9(t){return qs(e=>e.normalize(t))}function o9(){return qs(t=>t.trim())}function a9(){return qs(t=>t.toLowerCase())}function i9(){return qs(t=>t.toUpperCase())}function c9(t,e,r){return new t({type:"array",element:e,...ae(r)})}function l9(t,e,r){const n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function u9(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}class Vf{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??js,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)i.ref=h,this.process(h,p),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(s.type){case"string":{const f=d;f.type="string";const{minimum:v,maximum:y,format:w,patterns:g,contentEncoding:_}=e._zod.bag;if(typeof v=="number"&&(f.minLength=v),typeof y=="number"&&(f.maxLength=y),w&&(f.format=o[w]??w,f.format===""&&delete f.format),_&&(f.contentEncoding=_),g&&g.size>0){const b=[...g];b.length===1?f.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const f=d,{minimum:v,maximum:y,format:w,multipleOf:g,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof w=="string"&&w.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof v=="number"&&(f.minimum=v,typeof b=="number"&&(b>=v?delete f.minimum:delete f.exclusiveMinimum)),typeof _=="number"&&(f.exclusiveMaximum=_),typeof y=="number"&&(f.maximum=y,typeof _=="number"&&(_<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof g=="number"&&(f.multipleOf=g);break}case"boolean":{const f=d;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=d,{minimum:v,maximum:y}=e._zod.bag;typeof v=="number"&&(f.minItems=v),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const f=d;f.type="object",f.properties={};const v=s.shape;for(const g in v)f.properties[g]=this.process(v[g],{...p,path:[...p.path,"properties",g]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(g=>{const _=s.shape[g]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));w.size>0&&(f.required=Array.from(w)),s.catchall?._zod.def.type==="never"?f.additionalProperties=!1:s.catchall?s.catchall&&(f.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=d;f.anyOf=s.options.map((v,y)=>this.process(v,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{const f=d,v=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),y=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),w=_=>"allOf"in _&&Object.keys(_).length===1,g=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];f.allOf=g;break}case"tuple":{const f=d;f.type="array";const v=s.items.map((g,_)=>this.process(g,{...p,path:[...p.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?f.prefixItems=v:f.items=v,s.rest){const g=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?f.items=g:f.additionalItems=g}s.rest&&(f.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:y,maximum:w}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof w=="number"&&(f.maxItems=w);break}case"record":{const f=d;f.type="object",f.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),f.additionalProperties=this.process(s.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const f=d,v=af(s.entries);v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),f.enum=v;break}case"literal":{const f=d,v=[];for(const y of s.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];f.type=y===null?"null":typeof y,f.const=y}else v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),v.every(y=>typeof y=="boolean")&&(f.type="string"),v.every(y=>y===null)&&(f.type="null"),f.enum=v;break}case"file":{const f=d,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:g}=e._zod.bag;y!==void 0&&(v.minLength=y),w!==void 0&&(v.maxLength=w),g?g.length===1?(v.contentMediaType=g[0],Object.assign(f,v)):f.anyOf=g.map(_=>({...v,contentMediaType:_})):Object.assign(f,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(s.innerType,p);d.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"success":{const f=d;f.type="boolean";break}case"default":{this.process(s.innerType,p),i.ref=s.innerType,d.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),i.ref=s.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),i.ref=s.innerType;let f;try{f=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=d,v=e._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=v.source;break}case"pipe":{const f=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(f,p),i.ref=f;break}case"readonly":{this.process(s.innerType,p),i.ref=s.innerType,d.readOnly=!0;break}case"promise":{this.process(s.innerType,p),i.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"lazy":{const f=e._zod.innerType;this.process(f,p),i.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const l=this.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),this.io==="input"&&Qe(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=u=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,y=n.external.uri??(g=>g);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")}#/${p}/${w}`}}if(u[1]===s)return{ref:"#"};const d=`#/${p}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:d+f}},a=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:h,defId:d}=o(u);p.def={...p.schema},d&&(p.defId=d);const f=p.schema;for(const v in f)delete f[v];f.$ref=h};if(n.cycles==="throw")for(const u of this.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
34
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(e===u[0]){a(u);continue}if(n.external){const p=n.external.registry.get(u[0])?.id;if(e!==u[0]&&p){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 f=this.seen.get(u),p=f.def??f.schema,m={...p};if(f.ref===null)return;const v=f.ref;if(f.ref=null,v){i(v,h);const _=this.seen.get(v).schema;_.$ref&&h.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(_)):(Object.assign(p,_),Object.assign(p,m))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,s.def);const l=n.external?.defs??{};for(const u of this.seen.entries()){const h=u[1];h.def&&h.defId&&(l[h.defId]=h.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function Wc(t,e){if(t instanceof zf){const n=new Gf(e),s={};for(const i of t._idmap.entries()){const[c,l]=i;n.process(l)}const o={},a={registry:t,uri:e?.uri,defs:s};for(const i of t._idmap.entries()){const[c,l]=i;o[c]=n.emit(l,{...e,external:a})}if(Object.keys(s).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:s}}return{schemas:o}}const r=new Gf(e);return r.process(t),r.emit(t,e)}function tt(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return tt(s.element,r);case"object":{for(const o in s.shape)if(tt(s.shape[o],r))return!0;return!1}case"union":{for(const o of s.options)if(tt(o,r))return!0;return!1}case"intersection":return tt(s.left,r)||tt(s.right,r);case"tuple":{for(const o of s.items)if(tt(o,r))return!0;return!!(s.rest&&tt(s.rest,r))}case"record":return tt(s.keyType,r)||tt(s.valueType,r);case"map":return tt(s.keyType,r)||tt(s.valueType,r);case"set":return tt(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return tt(s.innerType,r);case"lazy":return tt(s.getter(),r);case"default":return tt(s.innerType,r);case"prefault":return tt(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return tt(s.in,r)||tt(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const oS=J("ZodISODateTime",(t,e)=>{R9.init(t,e),Qe.init(t,e)});function Kf(t){return M4(oS,t)}const aS=J("ZodISODate",(t,e)=>{P9.init(t,e),Qe.init(t,e)});function iS(t){return N4(aS,t)}const cS=J("ZodISOTime",(t,e)=>{O9.init(t,e),Qe.init(t,e)});function lS(t){return L4(cS,t)}const uS=J("ZodISODuration",(t,e)=>{A9.init(t,e),Qe.init(t,e)});function dS(t){return q4(uS,t)}const Ka=J("ZodError",(t,e)=>{mf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>x3(t,r)},flatten:{value:r=>E3(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),pS=gf(Ka),hS=_f(Ka),fS=vf(Ka),Gc=yf(Ka),We=J("ZodType",(t,e)=>(He.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Gr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>pS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>fS(t,r,n),t.parseAsync=async(r,n)=>hS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gc(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(nk(r,n)),t.superRefine=r=>t.check(sk(r)),t.overwrite=r=>t.check(Ks(r)),t.optional=()=>Q(t),t.nullable=()=>cm(t),t.nullish=()=>Q(cm(t)),t.nonoptional=r=>GS(t,r),t.array=()=>I(t),t.or=r=>ee([t,r]),t.and=r=>Ys(t,r),t.transform=r=>Xc(t,am(r)),t.default=r=>BS(t,r),t.prefault=r=>WS(t,r),t.catch=r=>YS(t,r),t.pipe=r=>Xc(t,r),t.readonly=()=>ek(t),t.describe=r=>{const n=t.clone();return Gs.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Gs.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gs.get(t);const n=t.clone();return Gs.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Yf=J("_ZodString",(t,e)=>{Fc.init(t,e),We.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(B4(...n)),t.includes=(...n)=>t.check(G4(...n)),t.startsWith=(...n)=>t.check(K4(...n)),t.endsWith=(...n)=>t.check(Y4(...n)),t.min=(...n)=>t.check(Ga(...n)),t.max=(...n)=>t.check(Jf(...n)),t.length=(...n)=>t.check(Wf(...n)),t.nonempty=(...n)=>t.check(Ga(1,...n)),t.lowercase=n=>t.check(J4(n)),t.uppercase=n=>t.check(W4(n)),t.trim=()=>t.check(X4()),t.normalize=(...n)=>t.check(Q4(...n)),t.toLowerCase=()=>t.check(eS()),t.toUpperCase=()=>t.check(tS())}),mS=J("ZodString",(t,e)=>{Fc.init(t,e),Yf.init(t,e),t.email=r=>t.check(m4(gS,r)),t.url=r=>t.check(Zf(Xf,r)),t.jwt=r=>t.check(A4(RS,r)),t.emoji=r=>t.check(w4(_S,r)),t.guid=r=>t.check(Df(Qf,r)),t.uuid=r=>t.check(g4(Ya,r)),t.uuidv4=r=>t.check(_4(Ya,r)),t.uuidv6=r=>t.check(v4(Ya,r)),t.uuidv7=r=>t.check(y4(Ya,r)),t.nanoid=r=>t.check(b4(vS,r)),t.guid=r=>t.check(Df(Qf,r)),t.cuid=r=>t.check(S4(yS,r)),t.cuid2=r=>t.check(k4(wS,r)),t.ulid=r=>t.check(C4(bS,r)),t.base64=r=>t.check(Vf(tm,r)),t.base64url=r=>t.check(P4(xS,r)),t.xid=r=>t.check(T4(SS,r)),t.ksuid=r=>t.check($4(kS,r)),t.ipv4=r=>t.check(E4(CS,r)),t.ipv6=r=>t.check(x4(TS,r)),t.cidrv4=r=>t.check(I4($S,r)),t.cidrv6=r=>t.check(R4(ES,r)),t.e164=r=>t.check(O4(IS,r)),t.datetime=r=>t.check(Kf(r)),t.date=r=>t.check(iS(r)),t.time=r=>t.check(lS(r)),t.duration=r=>t.check(dS(r))});function d(t){return f4(mS,t)}const Qe=J("ZodStringFormat",(t,e)=>{Ke.init(t,e),Yf.init(t,e)}),gS=J("ZodEmail",(t,e)=>{b9.init(t,e),Qe.init(t,e)}),Qf=J("ZodGUID",(t,e)=>{y9.init(t,e),Qe.init(t,e)}),Ya=J("ZodUUID",(t,e)=>{w9.init(t,e),Qe.init(t,e)}),Xf=J("ZodURL",(t,e)=>{S9.init(t,e),Qe.init(t,e)});function em(t){return Zf(Xf,t)}const _S=J("ZodEmoji",(t,e)=>{k9.init(t,e),Qe.init(t,e)}),vS=J("ZodNanoID",(t,e)=>{C9.init(t,e),Qe.init(t,e)}),yS=J("ZodCUID",(t,e)=>{T9.init(t,e),Qe.init(t,e)}),wS=J("ZodCUID2",(t,e)=>{$9.init(t,e),Qe.init(t,e)}),bS=J("ZodULID",(t,e)=>{E9.init(t,e),Qe.init(t,e)}),SS=J("ZodXID",(t,e)=>{x9.init(t,e),Qe.init(t,e)}),kS=J("ZodKSUID",(t,e)=>{I9.init(t,e),Qe.init(t,e)}),CS=J("ZodIPv4",(t,e)=>{M9.init(t,e),Qe.init(t,e)}),TS=J("ZodIPv6",(t,e)=>{N9.init(t,e),Qe.init(t,e)}),$S=J("ZodCIDRv4",(t,e)=>{L9.init(t,e),Qe.init(t,e)}),ES=J("ZodCIDRv6",(t,e)=>{q9.init(t,e),Qe.init(t,e)}),tm=J("ZodBase64",(t,e)=>{j9.init(t,e),Qe.init(t,e)});function rm(t){return Vf(tm,t)}const xS=J("ZodBase64URL",(t,e)=>{z9.init(t,e),Qe.init(t,e)}),IS=J("ZodE164",(t,e)=>{D9.init(t,e),Qe.init(t,e)}),RS=J("ZodJWT",(t,e)=>{V9.init(t,e),Qe.init(t,e)}),Kc=J("ZodNumber",(t,e)=>{xf.init(t,e),We.init(t,e),t.gt=(n,s)=>t.check(Hf(n,s)),t.gte=(n,s)=>t.check(Jc(n,s)),t.min=(n,s)=>t.check(Jc(n,s)),t.lt=(n,s)=>t.check(Ff(n,s)),t.lte=(n,s)=>t.check(Bc(n,s)),t.max=(n,s)=>t.check(Bc(n,s)),t.int=n=>t.check(nm(n)),t.safe=n=>t.check(nm(n)),t.positive=n=>t.check(Hf(0,n)),t.nonnegative=n=>t.check(Jc(0,n)),t.negative=n=>t.check(Ff(0,n)),t.nonpositive=n=>t.check(Bc(0,n)),t.multipleOf=(n,s)=>t.check(Bf(n,s)),t.step=(n,s)=>t.check(Bf(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function M(t){return j4(Kc,t)}const PS=J("ZodNumberFormat",(t,e)=>{F9.init(t,e),Kc.init(t,e)});function nm(t){return z4(PS,t)}const OS=J("ZodBoolean",(t,e)=>{H9.init(t,e),We.init(t,e)});function ne(t){return D4(OS,t)}const AS=J("ZodNull",(t,e)=>{B9.init(t,e),We.init(t,e)});function Yc(t){return Z4(AS,t)}const MS=J("ZodAny",(t,e)=>{J9.init(t,e),We.init(t,e)});function mt(){return V4(MS)}const NS=J("ZodUnknown",(t,e)=>{W9.init(t,e),We.init(t,e)});function he(){return F4(NS)}const LS=J("ZodNever",(t,e)=>{G9.init(t,e),We.init(t,e)});function qS(t){return H4(LS,t)}const jS=J("ZodArray",(t,e)=>{K9.init(t,e),We.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ga(r,n)),t.nonempty=r=>t.check(Ga(1,r)),t.max=(r,n)=>t.check(Jf(r,n)),t.length=(r,n)=>t.check(Wf(r,n)),t.unwrap=()=>t.element});function I(t,e){return rS(jS,t,e)}const sm=J("ZodObject",(t,e)=>{Pf.init(t,e),We.init(t,e),qe(t,"shape",()=>e.shape),t.keyof=()=>we(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:he()}),t.loose=()=>t.clone({...t._zod.def,catchall:he()}),t.strict=()=>t.clone({...t._zod.def,catchall:qS()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>k3(t,r),t.merge=r=>C3(t,r),t.pick=r=>b3(t,r),t.omit=r=>S3(t,r),t.partial=(...r)=>T3(im,t,r[0]),t.required=(...r)=>$3(lm,t,r[0])});function C(t,e){const r={type:"object",get shape(){return Fs(this,"shape",{...t}),this.shape},...ce(e)};return new sm(r)}function Oe(t,e){return new sm({type:"object",get shape(){return Fs(this,"shape",{...t}),this.shape},catchall:he(),...ce(e)})}const om=J("ZodUnion",(t,e)=>{Af.init(t,e),We.init(t,e),t.options=e.options});function ee(t,e){return new om({type:"union",options:t,...ce(e)})}const US=J("ZodDiscriminatedUnion",(t,e)=>{om.init(t,e),Y9.init(t,e)});function Xe(t,e,r){return new US({type:"union",options:e,discriminator:t,...ce(r)})}const zS=J("ZodIntersection",(t,e)=>{Q9.init(t,e),We.init(t,e)});function Ys(t,e){return new zS({type:"intersection",left:t,right:e})}const DS=J("ZodRecord",(t,e)=>{X9.init(t,e),We.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ie(t,e,r){return new DS({type:"record",keyType:t,valueType:e,...ce(r)})}const Qc=J("ZodEnum",(t,e)=>{e4.init(t,e),We.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const o={};for(const a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Qc({...e,checks:[],...ce(s),entries:o})},t.exclude=(n,s)=>{const o={...e.entries};for(const a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new Qc({...e,checks:[],...ce(s),entries:o})}});function we(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Qc({type:"enum",entries:r,...ce(e)})}const ZS=J("ZodLiteral",(t,e)=>{t4.init(t,e),We.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function O(t,e){return new ZS({type:"literal",values:Array.isArray(t)?t:[t],...ce(e)})}const VS=J("ZodTransform",(t,e)=>{r4.init(t,e),We.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ws(o,r.value,e));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Ws(a))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function am(t){return new VS({type:"transform",transform:t})}const im=J("ZodOptional",(t,e)=>{n4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q(t){return new im({type:"optional",innerType:t})}const FS=J("ZodNullable",(t,e)=>{s4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cm(t){return new FS({type:"nullable",innerType:t})}const HS=J("ZodDefault",(t,e)=>{o4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function BS(t,e){return new HS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const JS=J("ZodPrefault",(t,e)=>{a4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});function WS(t,e){return new JS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const lm=J("ZodNonOptional",(t,e)=>{i4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});function GS(t,e){return new lm({type:"nonoptional",innerType:t,...ce(e)})}const KS=J("ZodCatch",(t,e)=>{c4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function YS(t,e){return new KS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const QS=J("ZodPipe",(t,e)=>{l4.init(t,e),We.init(t,e),t.in=e.in,t.out=e.out});function Xc(t,e){return new QS({type:"pipe",in:t,out:e})}const XS=J("ZodReadonly",(t,e)=>{u4.init(t,e),We.init(t,e)});function ek(t){return new XS({type:"readonly",innerType:t})}const tk=J("ZodLazy",(t,e)=>{d4.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.getter()});function um(t){return new tk({type:"lazy",getter:t})}const el=J("ZodCustom",(t,e)=>{p4.init(t,e),We.init(t,e)});function rk(t){const e=new $t({check:"custom"});return e._zod.check=t,e}function tl(t,e){return nS(el,t??(()=>!0),e)}function nk(t,e={}){return sS(el,t,e)}function sk(t){const e=rk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ws(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ws(s))}},t(r.value,r)));return e}function Qa(t,e={error:`Input not instance of ${t.name}`}){const r=new el({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ce(e)});return r._zod.bag.Class=t,r}function rl(t,e){return Xc(am(t),e)}const nl={custom:"custom"};function dm(t){return U4(Kc,t)}const Xa="2025-11-25",ok=[Xa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Sn="io.modelcontextprotocol/related-task",ei="2.0",at=tl(t=>t!==null&&(typeof t=="object"||typeof t=="function")),pm=ee([d(),M().int()]),hm=d();Oe({ttl:ee([M(),Yc()]).optional(),pollInterval:M().optional()});const ak=C({ttl:M().optional()}),ik=C({taskId:d()}),sl=Oe({progressToken:pm.optional(),[Sn]:ik.optional()}),Nt=C({_meta:sl.optional()}),Qs=Nt.extend({task:ak.optional()}),ck=t=>Qs.safeParse(t).success,it=C({method:d(),params:Nt.loose().optional()}),Zt=C({_meta:sl.optional()}),Vt=C({method:d(),params:Zt.loose().optional()}),ct=Oe({_meta:sl.optional()}),ti=ee([d(),M().int()]),fm=C({jsonrpc:O(ei),id:ti,...it.shape}).strict(),ol=t=>fm.safeParse(t).success,mm=C({jsonrpc:O(ei),...Vt.shape}).strict(),lk=t=>mm.safeParse(t).success,al=C({jsonrpc:O(ei),id:ti,result:ct}).strict(),Xs=t=>al.safeParse(t).success;var Ce;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ce||(Ce={}));const il=C({jsonrpc:O(ei),id:ti.optional(),error:C({code:M().int(),message:d(),data:he().optional()})}).strict(),uk=t=>il.safeParse(t).success,Wn=ee([fm,mm,al,il]);ee([al,il]);const kn=ct.strict(),dk=Zt.extend({requestId:ti.optional(),reason:d().optional()}),cl=Vt.extend({method:O("notifications/cancelled"),params:dk}),pk=C({src:d(),mimeType:d().optional(),sizes:I(d()).optional(),theme:we(["light","dark"]).optional()}),eo=C({icons:I(pk).optional()}),Gn=C({name:d(),title:d().optional()}),gm=Gn.extend({...Gn.shape,...eo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),hk=Ys(C({applyDefaults:ne().optional()}),ie(d(),he())),fk=rl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ys(C({form:hk.optional(),url:at.optional()}),ie(d(),he()).optional())),mk=Oe({list:at.optional(),cancel:at.optional(),requests:Oe({sampling:Oe({createMessage:at.optional()}).optional(),elicitation:Oe({create:at.optional()}).optional()}).optional()}),gk=Oe({list:at.optional(),cancel:at.optional(),requests:Oe({tools:Oe({call:at.optional()}).optional()}).optional()}),_k=C({experimental:ie(d(),at).optional(),sampling:C({context:at.optional(),tools:at.optional()}).optional(),elicitation:fk.optional(),roots:C({listChanged:ne().optional()}).optional(),tasks:mk.optional()}),vk=Nt.extend({protocolVersion:d(),capabilities:_k,clientInfo:gm}),yk=it.extend({method:O("initialize"),params:vk}),wk=C({experimental:ie(d(),at).optional(),logging:at.optional(),completions:at.optional(),prompts:C({listChanged:ne().optional()}).optional(),resources:C({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:C({listChanged:ne().optional()}).optional(),tasks:gk.optional()}),_m=ct.extend({protocolVersion:d(),capabilities:wk,serverInfo:gm,instructions:d().optional()}),vm=Vt.extend({method:O("notifications/initialized"),params:Zt.optional()}),bk=t=>vm.safeParse(t).success,ll=it.extend({method:O("ping"),params:Nt.optional()}),Sk=C({progress:M(),total:Q(M()),message:Q(d())}),kk=C({...Zt.shape,...Sk.shape,progressToken:pm}),ul=Vt.extend({method:O("notifications/progress"),params:kk}),Ck=Nt.extend({cursor:hm.optional()}),to=it.extend({params:Ck.optional()}),ro=ct.extend({nextCursor:hm.optional()}),Tk=we(["working","input_required","completed","failed","cancelled"]),no=C({taskId:d(),status:Tk,ttl:ee([M(),Yc()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:Q(M()),statusMessage:Q(d())}),so=ct.extend({task:no}),$k=Zt.merge(no),ri=Vt.extend({method:O("notifications/tasks/status"),params:$k}),dl=it.extend({method:O("tasks/get"),params:Nt.extend({taskId:d()})}),pl=ct.merge(no),hl=it.extend({method:O("tasks/result"),params:Nt.extend({taskId:d()})});ct.loose();const fl=to.extend({method:O("tasks/list")}),ml=ro.extend({tasks:I(no)}),gl=it.extend({method:O("tasks/cancel"),params:Nt.extend({taskId:d()})}),Ek=ct.merge(no),ym=C({uri:d(),mimeType:Q(d()),_meta:ie(d(),he()).optional()}),wm=ym.extend({text:d()}),_l=d().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bm=ym.extend({blob:_l}),oo=we(["user","assistant"]),Kn=C({audience:I(oo).optional(),priority:M().min(0).max(1).optional(),lastModified:Kf({offset:!0}).optional()}),Sm=C({...Gn.shape,...eo.shape,uri:d(),description:Q(d()),mimeType:Q(d()),annotations:Kn.optional(),_meta:Q(Oe({}))}),xk=C({...Gn.shape,...eo.shape,uriTemplate:d(),description:Q(d()),mimeType:Q(d()),annotations:Kn.optional(),_meta:Q(Oe({}))}),Ik=to.extend({method:O("resources/list")}),km=ro.extend({resources:I(Sm)}),Rk=to.extend({method:O("resources/templates/list")}),Cm=ro.extend({resourceTemplates:I(xk)}),vl=Nt.extend({uri:d()}),Pk=vl,Ok=it.extend({method:O("resources/read"),params:Pk}),Tm=ct.extend({contents:I(ee([wm,bm]))}),$m=Vt.extend({method:O("notifications/resources/list_changed"),params:Zt.optional()}),Ak=vl,Mk=it.extend({method:O("resources/subscribe"),params:Ak}),Nk=vl,Lk=it.extend({method:O("resources/unsubscribe"),params:Nk}),qk=Zt.extend({uri:d()}),jk=Vt.extend({method:O("notifications/resources/updated"),params:qk}),Uk=C({name:d(),description:Q(d()),required:Q(ne())}),zk=C({...Gn.shape,...eo.shape,description:Q(d()),arguments:Q(I(Uk)),_meta:Q(Oe({}))}),Dk=to.extend({method:O("prompts/list")}),Em=ro.extend({prompts:I(zk)}),Zk=Nt.extend({name:d(),arguments:ie(d(),d()).optional()}),Vk=it.extend({method:O("prompts/get"),params:Zk}),yl=C({type:O("text"),text:d(),annotations:Kn.optional(),_meta:ie(d(),he()).optional()}),wl=C({type:O("image"),data:_l,mimeType:d(),annotations:Kn.optional(),_meta:ie(d(),he()).optional()}),bl=C({type:O("audio"),data:_l,mimeType:d(),annotations:Kn.optional(),_meta:ie(d(),he()).optional()}),Fk=C({type:O("tool_use"),name:d(),id:d(),input:ie(d(),he()),_meta:ie(d(),he()).optional()}),Hk=C({type:O("resource"),resource:ee([wm,bm]),annotations:Kn.optional(),_meta:ie(d(),he()).optional()}),Bk=Sm.extend({type:O("resource_link")}),Sl=ee([yl,wl,bl,Bk,Hk]),Jk=C({role:oo,content:Sl}),xm=ct.extend({description:d().optional(),messages:I(Jk)}),Im=Vt.extend({method:O("notifications/prompts/list_changed"),params:Zt.optional()}),Wk=C({title:d().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),Gk=C({taskSupport:we(["required","optional","forbidden"]).optional()}),Rm=C({...Gn.shape,...eo.shape,description:d().optional(),inputSchema:C({type:O("object"),properties:ie(d(),at).optional(),required:I(d()).optional()}).catchall(he()),outputSchema:C({type:O("object"),properties:ie(d(),at).optional(),required:I(d()).optional()}).catchall(he()).optional(),annotations:Wk.optional(),execution:Gk.optional(),_meta:ie(d(),he()).optional()}),Kk=to.extend({method:O("tools/list")}),Pm=ro.extend({tools:I(Rm)}),ni=ct.extend({content:I(Sl).default([]),structuredContent:ie(d(),he()).optional(),isError:ne().optional()});ni.or(ct.extend({toolResult:he()}));const Yk=Qs.extend({name:d(),arguments:ie(d(),he()).optional()}),Qk=it.extend({method:O("tools/call"),params:Yk}),Om=Vt.extend({method:O("notifications/tools/list_changed"),params:Zt.optional()}),Xk=C({autoRefresh:ne().default(!0),debounceMs:M().int().nonnegative().default(300)}),Am=we(["debug","info","notice","warning","error","critical","alert","emergency"]),eC=Nt.extend({level:Am}),tC=it.extend({method:O("logging/setLevel"),params:eC}),rC=Zt.extend({level:Am,logger:d().optional(),data:he()}),nC=Vt.extend({method:O("notifications/message"),params:rC}),sC=C({name:d().optional()}),oC=C({hints:I(sC).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),aC=C({mode:we(["auto","required","none"]).optional()}),iC=C({type:O("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:I(Sl).default([]),structuredContent:C({}).loose().optional(),isError:ne().optional(),_meta:ie(d(),he()).optional()}),cC=Xe("type",[yl,wl,bl]),si=Xe("type",[yl,wl,bl,Fk,iC]),lC=C({role:oo,content:ee([si,I(si)]),_meta:ie(d(),he()).optional()}),uC=Qs.extend({messages:I(lC),modelPreferences:oC.optional(),systemPrompt:d().optional(),includeContext:we(["none","thisServer","allServers"]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:I(d()).optional(),metadata:at.optional(),tools:I(Rm).optional(),toolChoice:aC.optional()}),Mm=it.extend({method:O("sampling/createMessage"),params:uC}),kl=ct.extend({model:d(),stopReason:Q(we(["endTurn","stopSequence","maxTokens"]).or(d())),role:oo,content:cC}),dC=ct.extend({model:d(),stopReason:Q(we(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:oo,content:ee([si,I(si)])}),pC=C({type:O("boolean"),title:d().optional(),description:d().optional(),default:ne().optional()}),hC=C({type:O("string"),title:d().optional(),description:d().optional(),minLength:M().optional(),maxLength:M().optional(),format:we(["email","uri","date","date-time"]).optional(),default:d().optional()}),fC=C({type:we(["number","integer"]),title:d().optional(),description:d().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),mC=C({type:O("string"),title:d().optional(),description:d().optional(),enum:I(d()),default:d().optional()}),gC=C({type:O("string"),title:d().optional(),description:d().optional(),oneOf:I(C({const:d(),title:d()})),default:d().optional()}),_C=C({type:O("string"),title:d().optional(),description:d().optional(),enum:I(d()),enumNames:I(d()).optional(),default:d().optional()}),vC=ee([mC,gC]),yC=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:M().optional(),maxItems:M().optional(),items:C({type:O("string"),enum:I(d())}),default:I(d()).optional()}),wC=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:M().optional(),maxItems:M().optional(),items:C({anyOf:I(C({const:d(),title:d()}))}),default:I(d()).optional()}),bC=ee([yC,wC]),SC=ee([_C,vC,bC]),kC=ee([SC,pC,hC,fC]),CC=Qs.extend({mode:O("form").optional(),message:d(),requestedSchema:C({type:O("object"),properties:ie(d(),kC),required:I(d()).optional()})}),TC=Qs.extend({mode:O("url"),message:d(),elicitationId:d(),url:d().url()}),$C=ee([CC,TC]),Nm=it.extend({method:O("elicitation/create"),params:$C}),EC=Zt.extend({elicitationId:d()}),xC=Vt.extend({method:O("notifications/elicitation/complete"),params:EC}),Cl=ct.extend({action:we(["accept","decline","cancel"]),content:rl(t=>t===null?void 0:t,ie(d(),ee([d(),M(),ne(),I(d())])).optional())}),IC=C({type:O("ref/resource"),uri:d()}),RC=C({type:O("ref/prompt"),name:d()}),PC=Nt.extend({ref:ee([RC,IC]),argument:C({name:d(),value:d()}),context:C({arguments:ie(d(),d()).optional()}).optional()}),OC=it.extend({method:O("completion/complete"),params:PC}),Lm=ct.extend({completion:Oe({values:I(d()).max(100),total:Q(M().int()),hasMore:Q(ne())})}),AC=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ie(d(),he()).optional()}),MC=it.extend({method:O("roots/list"),params:Nt.optional()}),qm=ct.extend({roots:I(AC)}),NC=Vt.extend({method:O("notifications/roots/list_changed"),params:Zt.optional()});ee([ll,yk,OC,tC,Vk,Dk,Ik,Rk,Ok,Mk,Lk,Qk,Kk,dl,hl,fl,gl]),ee([cl,ul,vm,NC,ri]),ee([kn,kl,dC,Cl,qm,pl,ml,so]),ee([ll,Mm,Nm,MC,dl,hl,fl,gl]),ee([cl,ul,nC,jk,$m,Om,Im,ri,xC]),ee([kn,_m,Lm,xm,Em,km,Cm,Tm,ni,Pm,pl,ml,so]);let be=class mw extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Ce.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new LC(s.elicitations,r)}return new mw(e,r,n)}},LC=class extends be{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ce.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};const qC=J("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");He.init(t,e),t.def=e,t.parse=(r,n)=>I3(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ba(t,r,n),t.parseAsync=async(r,n)=>R3(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Vc(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Gr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),jC=J("ZodMiniObject",(t,e)=>{Pf.init(t,e),qC.init(t,e),qe(t,"shape",()=>e.shape)});function jm(t,e){const r={type:"object",get shape(){return Fs(this,"shape",{...t}),this.shape},...ce(e)};return new jC(r)}function oi(t){return!!t._zod}function Yr(t,e){return oi(t)?Ba(t,e):t.safeParse(e)}function Um(t){if(!t)return;let e;if(oi(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function UC(t){if(oi(t)){const o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=t.value;if(n!==void 0)return n}function Cn(t){return t==="completed"||t==="failed"||t==="cancelled"}const zC=Symbol("Let zodToJsonSchema decide on which parser to use"),zm={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"},DC=t=>typeof t=="string"?{...zm,name:t}:{...zm,...t},ZC=t=>{const e=DC(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Dm(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function De(t,e,r,n,s){t[e]=r,Dm(t,e,n,s)}const Zm=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Et(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Zm(e,t.currentPath):e.join("/")}}function VC(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&De(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&De(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(De(r,"minItems",t.exactLength.value,t.exactLength.message,e),De(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function FC(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?De(r,"minimum",n.value,n.message,e):De(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),De(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?De(r,"maximum",n.value,n.message,e):De(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),De(r,"maximum",n.value,n.message,e));break;case"multipleOf":De(r,"multipleOf",n.value,n.message,e);break}return r}function HC(){return{type:"boolean"}}function Vm(t,e){return je(t.type._def,e)}const BC=(t,e)=>je(t.innerType._def,e);function Fm(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Fm(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return JC(t,e)}}const JC=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":De(r,"minimum",n.value,n.message,e);break;case"max":De(r,"maximum",n.value,n.message,e);break}return r};function WC(t,e){return{...je(t.innerType._def,e),default:t.defaultValue()}}function GC(t,e){return e.effectStrategy==="input"?je(t.schema._def,e):Et(e)}function KC(t){return{type:"string",enum:Array.from(t.values)}}const YC=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function QC(t,e){const r=[je(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),je(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(o=>{if(YC(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...c}=o;a=c}else n=void 0;s.push(a)}}),s.length?{allOf:s,...n}:void 0}function XC(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let Tl;const Qt={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:()=>(Tl===void 0&&(Tl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Tl),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 Hm(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":De(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":De(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Xt(r,"email",n.message,e);break;case"format:idn-email":Xt(r,"idn-email",n.message,e);break;case"pattern:zod":yt(r,Qt.email,n.message,e);break}break;case"url":Xt(r,"uri",n.message,e);break;case"uuid":Xt(r,"uuid",n.message,e);break;case"regex":yt(r,n.regex,n.message,e);break;case"cuid":yt(r,Qt.cuid,n.message,e);break;case"cuid2":yt(r,Qt.cuid2,n.message,e);break;case"startsWith":yt(r,RegExp(`^${$l(n.value,e)}`),n.message,e);break;case"endsWith":yt(r,RegExp(`${$l(n.value,e)}$`),n.message,e);break;case"datetime":Xt(r,"date-time",n.message,e);break;case"date":Xt(r,"date",n.message,e);break;case"time":Xt(r,"time",n.message,e);break;case"duration":Xt(r,"duration",n.message,e);break;case"length":De(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),De(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{yt(r,RegExp($l(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Xt(r,"ipv4",n.message,e),n.version!=="v4"&&Xt(r,"ipv6",n.message,e);break}case"base64url":yt(r,Qt.base64url,n.message,e);break;case"jwt":yt(r,Qt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&yt(r,Qt.ipv4Cidr,n.message,e),n.version!=="v4"&&yt(r,Qt.ipv6Cidr,n.message,e);break}case"emoji":yt(r,Qt.emoji(),n.message,e);break;case"ulid":{yt(r,Qt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Xt(r,"binary",n.message,e);break}case"contentEncoding:base64":{De(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{yt(r,Qt.base64,n.message,e);break}}break}case"nanoid":yt(r,Qt.nanoid,n.message,e)}return r}function $l(t,e){return e.patternStrategy==="escape"?t6(t):t}const e6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function t6(t){let e="";for(let r=0;r<t.length;r++)e6.has(t[r])||(e+="\\"),e+=t[r];return e}function Xt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):De(t,"format",e,r,n)}function yt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Bm(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):De(t,"pattern",Bm(e,n),r,n)}function Bm(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",o=!1,a=!1,i=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){i?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),i=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],i=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
35
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const p=u[1];if(e===u[0]){a(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(p.cycle){a(u);continue}if(p.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,p)=>{const h=this.seen.get(u),d=h.def??h.schema,f={...d};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){i(v,p);const y=this.seen.get(v).schema;y.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(y)):(Object.assign(d,y),Object.assign(d,f))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,s.def);const l=n.external?.defs??{};for(const u of this.seen.entries()){const p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function yc(t,e){if(t instanceof Nf){const n=new Vf(e),s={};for(const i of t._idmap.entries()){const[c,l]=i;n.process(l)}const o={},a={registry:t,uri:e?.uri,defs:s};for(const i of t._idmap.entries()){const[c,l]=i;o[c]=n.emit(l,{...e,external:a})}if(Object.keys(s).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:s}}return{schemas:o}}const r=new Vf(e);return r.process(t),r.emit(t,e)}function Qe(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Qe(s.element,r);case"object":{for(const o in s.shape)if(Qe(s.shape[o],r))return!0;return!1}case"union":{for(const o of s.options)if(Qe(o,r))return!0;return!1}case"intersection":return Qe(s.left,r)||Qe(s.right,r);case"tuple":{for(const o of s.items)if(Qe(o,r))return!0;return!!(s.rest&&Qe(s.rest,r))}case"record":return Qe(s.keyType,r)||Qe(s.valueType,r);case"map":return Qe(s.keyType,r)||Qe(s.valueType,r);case"set":return Qe(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Qe(s.innerType,r);case"lazy":return Qe(s.getter(),r);case"default":return Qe(s.innerType,r);case"prefault":return Qe(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Qe(s.in,r)||Qe(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const d9=J("ZodISODateTime",(t,e)=>{Lb.init(t,e),Ge.init(t,e)});function Hf(t){return D3(d9,t)}const p9=J("ZodISODate",(t,e)=>{jb.init(t,e),Ge.init(t,e)});function f9(t){return U3(p9,t)}const h9=J("ZodISOTime",(t,e)=>{qb.init(t,e),Ge.init(t,e)});function m9(t){return Z3(h9,t)}const g9=J("ZodISODuration",(t,e)=>{zb.init(t,e),Ge.init(t,e)});function y9(t){return F3(g9,t)}const Ma=J("ZodError",(t,e)=>{uf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Mw(t,r)},flatten:{value:r=>Aw(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),_9=df(Ma),v9=pf(Ma),w9=ff(Ma),_c=hf(Ma),He=J("ZodType",(t,e)=>(Ze.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ur(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>_9(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>w9(t,r,n),t.parseAsync=async(r,n)=>v9(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_c(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(u4(r,n)),t.superRefine=r=>t.check(d4(r)),t.overwrite=r=>t.check(qs(r)),t.optional=()=>le(t),t.nullable=()=>rh(t),t.nullish=()=>le(rh(t)),t.nonoptional=r=>r4(t,r),t.array=()=>M(t),t.or=r=>ie([t,r]),t.and=r=>bc(t,r),t.transform=r=>Sc(t,eh(r)),t.default=r=>X9(t,r),t.prefault=r=>t4(t,r),t.catch=r=>s4(t,r),t.pipe=r=>Sc(t,r),t.readonly=()=>i4(t),t.describe=r=>{const n=t.clone();return js.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return js.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return js.get(t);const n=t.clone();return js.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Bf=J("_ZodString",(t,e)=>{fc.init(t,e),He.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Q3(...n)),t.includes=(...n)=>t.check(t9(...n)),t.startsWith=(...n)=>t.check(r9(...n)),t.endsWith=(...n)=>t.check(n9(...n)),t.min=(...n)=>t.check(Aa(...n)),t.max=(...n)=>t.check(Zf(...n)),t.length=(...n)=>t.check(Ff(...n)),t.nonempty=(...n)=>t.check(Aa(1,...n)),t.lowercase=n=>t.check(X3(n)),t.uppercase=n=>t.check(e9(n)),t.trim=()=>t.check(o9()),t.normalize=(...n)=>t.check(s9(...n)),t.toLowerCase=()=>t.check(a9()),t.toUpperCase=()=>t.check(i9())}),b9=J("ZodString",(t,e)=>{fc.init(t,e),Bf.init(t,e),t.email=r=>t.check(b3(k9,r)),t.url=r=>t.check(jf(Wf,r)),t.jwt=r=>t.check(z3(j9,r)),t.emoji=r=>t.check($3(C9,r)),t.guid=r=>t.check(Lf(Jf,r)),t.uuid=r=>t.check(k3(Na,r)),t.uuidv4=r=>t.check(S3(Na,r)),t.uuidv6=r=>t.check(C3(Na,r)),t.uuidv7=r=>t.check(T3(Na,r)),t.nanoid=r=>t.check(E3(T9,r)),t.guid=r=>t.check(Lf(Jf,r)),t.cuid=r=>t.check(x3($9,r)),t.cuid2=r=>t.check(I3(E9,r)),t.ulid=r=>t.check(R3(x9,r)),t.base64=r=>t.check(qf(Gf,r)),t.base64url=r=>t.check(j3(N9,r)),t.xid=r=>t.check(P3(I9,r)),t.ksuid=r=>t.check(O3(R9,r)),t.ipv4=r=>t.check(A3(P9,r)),t.ipv6=r=>t.check(M3(O9,r)),t.cidrv4=r=>t.check(N3(A9,r)),t.cidrv6=r=>t.check(L3(M9,r)),t.e164=r=>t.check(q3(L9,r)),t.datetime=r=>t.check(Hf(r)),t.date=r=>t.check(f9(r)),t.time=r=>t.check(m9(r)),t.duration=r=>t.check(y9(r))});function m(t){return w3(b9,t)}const Ge=J("ZodStringFormat",(t,e)=>{Je.init(t,e),Bf.init(t,e)}),k9=J("ZodEmail",(t,e)=>{Eb.init(t,e),Ge.init(t,e)}),Jf=J("ZodGUID",(t,e)=>{Tb.init(t,e),Ge.init(t,e)}),Na=J("ZodUUID",(t,e)=>{$b.init(t,e),Ge.init(t,e)}),Wf=J("ZodURL",(t,e)=>{xb.init(t,e),Ge.init(t,e)});function S9(t){return jf(Wf,t)}const C9=J("ZodEmoji",(t,e)=>{Ib.init(t,e),Ge.init(t,e)}),T9=J("ZodNanoID",(t,e)=>{Rb.init(t,e),Ge.init(t,e)}),$9=J("ZodCUID",(t,e)=>{Pb.init(t,e),Ge.init(t,e)}),E9=J("ZodCUID2",(t,e)=>{Ob.init(t,e),Ge.init(t,e)}),x9=J("ZodULID",(t,e)=>{Ab.init(t,e),Ge.init(t,e)}),I9=J("ZodXID",(t,e)=>{Mb.init(t,e),Ge.init(t,e)}),R9=J("ZodKSUID",(t,e)=>{Nb.init(t,e),Ge.init(t,e)}),P9=J("ZodIPv4",(t,e)=>{Db.init(t,e),Ge.init(t,e)}),O9=J("ZodIPv6",(t,e)=>{Ub.init(t,e),Ge.init(t,e)}),A9=J("ZodCIDRv4",(t,e)=>{Zb.init(t,e),Ge.init(t,e)}),M9=J("ZodCIDRv6",(t,e)=>{Fb.init(t,e),Ge.init(t,e)}),Gf=J("ZodBase64",(t,e)=>{Vb.init(t,e),Ge.init(t,e)});function Kf(t){return qf(Gf,t)}const N9=J("ZodBase64URL",(t,e)=>{Bb.init(t,e),Ge.init(t,e)}),L9=J("ZodE164",(t,e)=>{Jb.init(t,e),Ge.init(t,e)}),j9=J("ZodJWT",(t,e)=>{Gb.init(t,e),Ge.init(t,e)}),vc=J("ZodNumber",(t,e)=>{Sf.init(t,e),He.init(t,e),t.gt=(n,s)=>t.check(Df(n,s)),t.gte=(n,s)=>t.check(gc(n,s)),t.min=(n,s)=>t.check(gc(n,s)),t.lt=(n,s)=>t.check(zf(n,s)),t.lte=(n,s)=>t.check(mc(n,s)),t.max=(n,s)=>t.check(mc(n,s)),t.int=n=>t.check(Yf(n)),t.safe=n=>t.check(Yf(n)),t.positive=n=>t.check(Df(0,n)),t.nonnegative=n=>t.check(gc(0,n)),t.negative=n=>t.check(zf(0,n)),t.nonpositive=n=>t.check(mc(0,n)),t.multipleOf=(n,s)=>t.check(Uf(n,s)),t.step=(n,s)=>t.check(Uf(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function N(t){return V3(vc,t)}const q9=J("ZodNumberFormat",(t,e)=>{Kb.init(t,e),vc.init(t,e)});function Yf(t){return B3(q9,t)}const z9=J("ZodBoolean",(t,e)=>{Yb.init(t,e),He.init(t,e)});function me(t){return J3(z9,t)}const D9=J("ZodNull",(t,e)=>{Qb.init(t,e),He.init(t,e)});function wc(t){return W3(D9,t)}const U9=J("ZodAny",(t,e)=>{Xb.init(t,e),He.init(t,e)});function ht(){return G3(U9)}const Z9=J("ZodUnknown",(t,e)=>{e3.init(t,e),He.init(t,e)});function Pe(){return K3(Z9)}const F9=J("ZodNever",(t,e)=>{t3.init(t,e),He.init(t,e)});function V9(t){return Y3(F9,t)}const H9=J("ZodArray",(t,e)=>{r3.init(t,e),He.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Aa(r,n)),t.nonempty=r=>t.check(Aa(1,r)),t.max=(r,n)=>t.check(Zf(r,n)),t.length=(r,n)=>t.check(Ff(r,n)),t.unwrap=()=>t.element});function M(t,e){return c9(H9,t,e)}const Qf=J("ZodObject",(t,e)=>{$f.init(t,e),He.init(t,e),Me(t,"shape",()=>e.shape),t.keyof=()=>xe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:V9()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Iw(t,r),t.merge=r=>Rw(t,r),t.pick=r=>Ew(t,r),t.omit=r=>xw(t,r),t.partial=(...r)=>Pw(th,t,r[0]),t.required=(...r)=>Ow(nh,t,r[0])});function T(t,e){const r={type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},...ae(e)};return new Qf(r)}function Ke(t,e){return new Qf({type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},catchall:Pe(),...ae(e)})}const Xf=J("ZodUnion",(t,e)=>{xf.init(t,e),He.init(t,e),t.options=e.options});function ie(t,e){return new Xf({type:"union",options:t,...ae(e)})}const B9=J("ZodDiscriminatedUnion",(t,e)=>{Xf.init(t,e),n3.init(t,e)});function Xe(t,e,r){return new B9({type:"union",options:e,discriminator:t,...ae(r)})}const J9=J("ZodIntersection",(t,e)=>{s3.init(t,e),He.init(t,e)});function bc(t,e){return new J9({type:"intersection",left:t,right:e})}const W9=J("ZodRecord",(t,e)=>{o3.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new W9({type:"record",keyType:t,valueType:e,...ae(r)})}const kc=J("ZodEnum",(t,e)=>{a3.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const o={};for(const a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new kc({...e,checks:[],...ae(s),entries:o})},t.exclude=(n,s)=>{const o={...e.entries};for(const a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new kc({...e,checks:[],...ae(s),entries:o})}});function xe(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new kc({type:"enum",entries:r,...ae(e)})}const G9=J("ZodLiteral",(t,e)=>{i3.init(t,e),He.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function L(t,e){return new G9({type:"literal",values:Array.isArray(t)?t:[t],...ae(e)})}const K9=J("ZodTransform",(t,e)=>{c3.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ls(o,r.value,e));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Ls(a))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function eh(t){return new K9({type:"transform",transform:t})}const th=J("ZodOptional",(t,e)=>{l3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function le(t){return new th({type:"optional",innerType:t})}const Y9=J("ZodNullable",(t,e)=>{u3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function rh(t){return new Y9({type:"nullable",innerType:t})}const Q9=J("ZodDefault",(t,e)=>{d3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function X9(t,e){return new Q9({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const e4=J("ZodPrefault",(t,e)=>{p3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function t4(t,e){return new e4({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const nh=J("ZodNonOptional",(t,e)=>{f3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});function r4(t,e){return new nh({type:"nonoptional",innerType:t,...ae(e)})}const n4=J("ZodCatch",(t,e)=>{h3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function s4(t,e){return new n4({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const o4=J("ZodPipe",(t,e)=>{m3.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});function Sc(t,e){return new o4({type:"pipe",in:t,out:e})}const a4=J("ZodReadonly",(t,e)=>{g3.init(t,e),He.init(t,e)});function i4(t){return new a4({type:"readonly",innerType:t})}const c4=J("ZodLazy",(t,e)=>{y3.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.getter()});function sh(t){return new c4({type:"lazy",getter:t})}const Cc=J("ZodCustom",(t,e)=>{_3.init(t,e),He.init(t,e)});function l4(t){const e=new kt({check:"custom"});return e._zod.check=t,e}function oh(t,e){return l9(Cc,t??(()=>!0),e)}function u4(t,e={}){return u9(Cc,t,e)}function d4(t){const e=l4(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ls(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ls(s))}},t(r.value,r)));return e}function La(t,e={error:`Input not instance of ${t.name}`}){const r=new Cc({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ae(e)});return r._zod.bag.Class=t,r}function ah(t,e){return Sc(eh(t),e)}const ih={custom:"custom"};function ch(t){return H3(vc,t)}const zs="2025-11-25",lh=[zs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fn="io.modelcontextprotocol/related-task",ja="2.0",st=oh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),uh=ie([m(),N().int()]),dh=m();Ke({ttl:ie([N(),wc()]).optional(),pollInterval:N().optional()});const p4=T({ttl:N().optional()}),f4=T({taskId:m()}),Tc=Ke({progressToken:uh.optional(),[fn]:f4.optional()}),Rt=T({_meta:Tc.optional()}),Ds=Rt.extend({task:p4.optional()}),h4=t=>Ds.safeParse(t).success,ot=T({method:m(),params:Rt.loose().optional()}),jt=T({_meta:Tc.optional()}),qt=T({method:m(),params:jt.loose().optional()}),at=Ke({_meta:Tc.optional()}),qa=ie([m(),N().int()]),ph=T({jsonrpc:L(ja),id:qa,...ot.shape}).strict(),$c=t=>ph.safeParse(t).success,fh=T({jsonrpc:L(ja),...qt.shape}).strict(),m4=t=>fh.safeParse(t).success,Ec=T({jsonrpc:L(ja),id:qa,result:at}).strict(),Us=t=>Ec.safeParse(t).success;var oe;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(oe||(oe={}));const xc=T({jsonrpc:L(ja),id:qa.optional(),error:T({code:N().int(),message:m(),data:Pe().optional()})}).strict(),g4=t=>xc.safeParse(t).success,Cr=ie([ph,fh,Ec,xc]);ie([Ec,xc]);const Fr=at.strict(),y4=jt.extend({requestId:qa.optional(),reason:m().optional()}),Ic=qt.extend({method:L("notifications/cancelled"),params:y4}),_4=T({src:m(),mimeType:m().optional(),sizes:M(m()).optional(),theme:xe(["light","dark"]).optional()}),Zs=T({icons:M(_4).optional()}),Nn=T({name:m(),title:m().optional()}),hh=Nn.extend({...Nn.shape,...Zs.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),v4=bc(T({applyDefaults:me().optional()}),be(m(),Pe())),w4=ah(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,bc(T({form:v4.optional(),url:st.optional()}),be(m(),Pe()).optional())),b4=Ke({list:st.optional(),cancel:st.optional(),requests:Ke({sampling:Ke({createMessage:st.optional()}).optional(),elicitation:Ke({create:st.optional()}).optional()}).optional()}),k4=Ke({list:st.optional(),cancel:st.optional(),requests:Ke({tools:Ke({call:st.optional()}).optional()}).optional()}),S4=T({experimental:be(m(),st).optional(),sampling:T({context:st.optional(),tools:st.optional()}).optional(),elicitation:w4.optional(),roots:T({listChanged:me().optional()}).optional(),tasks:b4.optional()}),C4=Rt.extend({protocolVersion:m(),capabilities:S4,clientInfo:hh}),mh=ot.extend({method:L("initialize"),params:C4}),T4=T({experimental:be(m(),st).optional(),logging:st.optional(),completions:st.optional(),prompts:T({listChanged:me().optional()}).optional(),resources:T({subscribe:me().optional(),listChanged:me().optional()}).optional(),tools:T({listChanged:me().optional()}).optional(),tasks:k4.optional()}),gh=at.extend({protocolVersion:m(),capabilities:T4,serverInfo:hh,instructions:m().optional()}),Rc=qt.extend({method:L("notifications/initialized"),params:jt.optional()}),$4=t=>Rc.safeParse(t).success,Pc=ot.extend({method:L("ping"),params:Rt.optional()}),E4=T({progress:N(),total:le(N()),message:le(m())}),x4=T({...jt.shape,...E4.shape,progressToken:uh}),Oc=qt.extend({method:L("notifications/progress"),params:x4}),I4=Rt.extend({cursor:dh.optional()}),Fs=ot.extend({params:I4.optional()}),Vs=at.extend({nextCursor:dh.optional()}),R4=xe(["working","input_required","completed","failed","cancelled"]),Hs=T({taskId:m(),status:R4,ttl:ie([N(),wc()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:le(N()),statusMessage:le(m())}),Ln=at.extend({task:Hs}),P4=jt.merge(Hs),za=qt.extend({method:L("notifications/tasks/status"),params:P4}),Ac=ot.extend({method:L("tasks/get"),params:Rt.extend({taskId:m()})}),Mc=at.merge(Hs),Nc=ot.extend({method:L("tasks/result"),params:Rt.extend({taskId:m()})});at.loose();const Lc=Fs.extend({method:L("tasks/list")}),jc=Vs.extend({tasks:M(Hs)}),qc=ot.extend({method:L("tasks/cancel"),params:Rt.extend({taskId:m()})}),O4=at.merge(Hs),yh=T({uri:m(),mimeType:le(m()),_meta:be(m(),Pe()).optional()}),_h=yh.extend({text:m()}),zc=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vh=yh.extend({blob:zc}),Bs=xe(["user","assistant"]),jn=T({audience:M(Bs).optional(),priority:N().min(0).max(1).optional(),lastModified:Hf({offset:!0}).optional()}),wh=T({...Nn.shape,...Zs.shape,uri:m(),description:le(m()),mimeType:le(m()),annotations:jn.optional(),_meta:le(Ke({}))}),A4=T({...Nn.shape,...Zs.shape,uriTemplate:m(),description:le(m()),mimeType:le(m()),annotations:jn.optional(),_meta:le(Ke({}))}),Da=Fs.extend({method:L("resources/list")}),bh=Vs.extend({resources:M(wh)}),Dc=Fs.extend({method:L("resources/templates/list")}),kh=Vs.extend({resourceTemplates:M(A4)}),Uc=Rt.extend({uri:m()}),M4=Uc,Zc=ot.extend({method:L("resources/read"),params:M4}),Sh=at.extend({contents:M(ie([_h,vh]))}),Fc=qt.extend({method:L("notifications/resources/list_changed"),params:jt.optional()}),N4=Uc,Ch=ot.extend({method:L("resources/subscribe"),params:N4}),L4=Uc,Th=ot.extend({method:L("resources/unsubscribe"),params:L4}),j4=jt.extend({uri:m()}),$h=qt.extend({method:L("notifications/resources/updated"),params:j4}),q4=T({name:m(),description:le(m()),required:le(me())}),z4=T({...Nn.shape,...Zs.shape,description:le(m()),arguments:le(M(q4)),_meta:le(Ke({}))}),Vc=Fs.extend({method:L("prompts/list")}),Eh=Vs.extend({prompts:M(z4)}),D4=Rt.extend({name:m(),arguments:be(m(),m()).optional()}),Hc=ot.extend({method:L("prompts/get"),params:D4}),Bc=T({type:L("text"),text:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),Jc=T({type:L("image"),data:zc,mimeType:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),Wc=T({type:L("audio"),data:zc,mimeType:m(),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),U4=T({type:L("tool_use"),name:m(),id:m(),input:be(m(),Pe()),_meta:be(m(),Pe()).optional()}),Z4=T({type:L("resource"),resource:ie([_h,vh]),annotations:jn.optional(),_meta:be(m(),Pe()).optional()}),F4=wh.extend({type:L("resource_link")}),Gc=ie([Bc,Jc,Wc,F4,Z4]),V4=T({role:Bs,content:Gc}),xh=at.extend({description:m().optional(),messages:M(V4)}),Kc=qt.extend({method:L("notifications/prompts/list_changed"),params:jt.optional()}),H4=T({title:m().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),B4=T({taskSupport:xe(["required","optional","forbidden"]).optional()}),Ih=T({...Nn.shape,...Zs.shape,description:m().optional(),inputSchema:T({type:L("object"),properties:be(m(),st).optional(),required:M(m()).optional()}).catchall(Pe()),outputSchema:T({type:L("object"),properties:be(m(),st).optional(),required:M(m()).optional()}).catchall(Pe()).optional(),annotations:H4.optional(),execution:B4.optional(),_meta:be(m(),Pe()).optional()}),Yc=Fs.extend({method:L("tools/list")}),Rh=Vs.extend({tools:M(Ih)}),qn=at.extend({content:M(Gc).default([]),structuredContent:be(m(),Pe()).optional(),isError:me().optional()});qn.or(at.extend({toolResult:Pe()}));const J4=Ds.extend({name:m(),arguments:be(m(),Pe()).optional()}),Ua=ot.extend({method:L("tools/call"),params:J4}),Qc=qt.extend({method:L("notifications/tools/list_changed"),params:jt.optional()}),W4=T({autoRefresh:me().default(!0),debounceMs:N().int().nonnegative().default(300)}),Za=xe(["debug","info","notice","warning","error","critical","alert","emergency"]),G4=Rt.extend({level:Za}),Fa=ot.extend({method:L("logging/setLevel"),params:G4}),K4=jt.extend({level:Za,logger:m().optional(),data:Pe()}),Ph=qt.extend({method:L("notifications/message"),params:K4}),Y4=T({name:m().optional()}),Q4=T({hints:M(Y4).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),X4=T({mode:xe(["auto","required","none"]).optional()}),ek=T({type:L("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:M(Gc).default([]),structuredContent:T({}).loose().optional(),isError:me().optional(),_meta:be(m(),Pe()).optional()}),tk=Xe("type",[Bc,Jc,Wc]),Va=Xe("type",[Bc,Jc,Wc,U4,ek]),rk=T({role:Bs,content:ie([Va,M(Va)]),_meta:be(m(),Pe()).optional()}),nk=Ds.extend({messages:M(rk),modelPreferences:Q4.optional(),systemPrompt:m().optional(),includeContext:xe(["none","thisServer","allServers"]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:M(m()).optional(),metadata:st.optional(),tools:M(Ih).optional(),toolChoice:X4.optional()}),Xc=ot.extend({method:L("sampling/createMessage"),params:nk}),Ha=at.extend({model:m(),stopReason:le(xe(["endTurn","stopSequence","maxTokens"]).or(m())),role:Bs,content:tk}),Oh=at.extend({model:m(),stopReason:le(xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:Bs,content:ie([Va,M(Va)])}),sk=T({type:L("boolean"),title:m().optional(),description:m().optional(),default:me().optional()}),ok=T({type:L("string"),title:m().optional(),description:m().optional(),minLength:N().optional(),maxLength:N().optional(),format:xe(["email","uri","date","date-time"]).optional(),default:m().optional()}),ak=T({type:xe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),ik=T({type:L("string"),title:m().optional(),description:m().optional(),enum:M(m()),default:m().optional()}),ck=T({type:L("string"),title:m().optional(),description:m().optional(),oneOf:M(T({const:m(),title:m()})),default:m().optional()}),lk=T({type:L("string"),title:m().optional(),description:m().optional(),enum:M(m()),enumNames:M(m()).optional(),default:m().optional()}),uk=ie([ik,ck]),dk=T({type:L("array"),title:m().optional(),description:m().optional(),minItems:N().optional(),maxItems:N().optional(),items:T({type:L("string"),enum:M(m())}),default:M(m()).optional()}),pk=T({type:L("array"),title:m().optional(),description:m().optional(),minItems:N().optional(),maxItems:N().optional(),items:T({anyOf:M(T({const:m(),title:m()}))}),default:M(m()).optional()}),fk=ie([dk,pk]),hk=ie([lk,uk,fk]),mk=ie([hk,sk,ok,ak]),gk=Ds.extend({mode:L("form").optional(),message:m(),requestedSchema:T({type:L("object"),properties:be(m(),mk),required:M(m()).optional()})}),yk=Ds.extend({mode:L("url"),message:m(),elicitationId:m(),url:m().url()}),_k=ie([gk,yk]),el=ot.extend({method:L("elicitation/create"),params:_k}),vk=jt.extend({elicitationId:m()}),wk=qt.extend({method:L("notifications/elicitation/complete"),params:vk}),Js=at.extend({action:xe(["accept","decline","cancel"]),content:ah(t=>t===null?void 0:t,be(m(),ie([m(),N(),me(),M(m())])).optional())}),bk=T({type:L("ref/resource"),uri:m()}),kk=T({type:L("ref/prompt"),name:m()}),Sk=Rt.extend({ref:ie([kk,bk]),argument:T({name:m(),value:m()}),context:T({arguments:be(m(),m()).optional()}).optional()}),tl=ot.extend({method:L("completion/complete"),params:Sk});function Ck(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Tk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const Ah=at.extend({completion:Ke({values:M(m()).max(100),total:le(N().int()),hasMore:le(me())})}),$k=T({uri:m().startsWith("file://"),name:m().optional(),_meta:be(m(),Pe()).optional()}),Mh=ot.extend({method:L("roots/list"),params:Rt.optional()}),rl=at.extend({roots:M($k)}),Nh=qt.extend({method:L("notifications/roots/list_changed"),params:jt.optional()});ie([Pc,mh,tl,Fa,Hc,Vc,Da,Dc,Zc,Ch,Th,Ua,Yc,Ac,Nc,Lc,qc]),ie([Ic,Oc,Rc,Nh,za]),ie([Fr,Ha,Oh,Js,rl,Mc,jc,Ln]),ie([Pc,Xc,el,Mh,Ac,Nc,Lc,qc]),ie([Ic,Oc,Ph,$h,Fc,Qc,Kc,za,wk]),ie([Fr,gh,Ah,xh,Eh,bh,kh,Sh,qn,Rh,Mc,jc,Ln]);class re extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===oe.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new Ek(s.elicitations,r)}return new re(e,r,n)}}class Ek extends re{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}const xk=J("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ze.init(t,e),t.def=e,t.parse=(r,n)=>Nw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>dc(t,r,n),t.parseAsync=async(r,n)=>Lw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>pc(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ur(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),Ik=J("ZodMiniObject",(t,e)=>{$f.init(t,e),xk.init(t,e),Me(t,"shape",()=>e.shape)});function Lh(t,e){const r={type:"object",get shape(){return Os(this,"shape",{...t}),this.shape},...ae(e)};return new Ik(r)}function Jt(t){return!!t._zod}function zn(t){const e=Object.values(t);if(e.length===0)return Lh({});const r=e.every(Jt),n=e.every(s=>!Jt(s));if(r)return Lh(t);if(n)return rf(t);throw new Error("Mixed Zod versions detected in object shape.")}function Wt(t,e){return Jt(t)?dc(t,e):t.safeParse(e)}async function nl(t,e){return Jt(t)?await pc(t,e):await t.safeParseAsync(e)}function Dn(t){if(!t)return;let e;if(Jt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ws(t){if(t){if(typeof t=="object"){const e=t,r=t;if(!e._def&&!r._zod){const n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return zn(t)}}if(Jt(t)){const r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function sl(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){const e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Rk(t){return t.description}function Pk(t){if(Jt(t))return t._zod?.def?.type==="optional";const e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function jh(t){if(Jt(t)){const o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=t.value;if(n!==void 0)return n}function hn(t){return t==="completed"||t==="failed"||t==="cancelled"}const Ok=Symbol("Let zodToJsonSchema decide on which parser to use"),qh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ak=t=>typeof t=="string"?{...qh,name:t}:{...qh,...t},Mk=t=>{const e=Ak(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function zh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,s){t[e]=r,zh(t,e,n,s)}const Dh=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function St(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Dh(e,t.currentPath):e.join("/")}}function Nk(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(r.items=Ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Lk(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function jk(){return{type:"boolean"}}function Uh(t,e){return Ne(t.type._def,e)}const qk=(t,e)=>Ne(t.innerType._def,e);function Zh(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Zh(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zk(t,e)}}const zk=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function Dk(t,e){return{...Ne(t.innerType._def,e),default:t.defaultValue()}}function Uk(t,e){return e.effectStrategy==="input"?Ne(t.schema._def,e):St(e)}function Zk(t){return{type:"string",enum:Array.from(t.values)}}const Fk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Vk(t,e){const r=[Ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ne(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(o=>{if(Fk(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...c}=o;a=c}else n=void 0;s.push(a)}}),s.length?{allOf:s,...n}:void 0}function Hk(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let ol;const Gt={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:()=>(ol===void 0&&(ol=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ol),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Fh(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Kt(r,"email",n.message,e);break;case"format:idn-email":Kt(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,Gt.email,n.message,e);break}break;case"url":Kt(r,"uri",n.message,e);break;case"uuid":Kt(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,Gt.cuid,n.message,e);break;case"cuid2":mt(r,Gt.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${al(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${al(n.value,e)}$`),n.message,e);break;case"datetime":Kt(r,"date-time",n.message,e);break;case"date":Kt(r,"date",n.message,e);break;case"time":Kt(r,"time",n.message,e);break;case"duration":Kt(r,"duration",n.message,e);break;case"length":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(al(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Kt(r,"ipv4",n.message,e),n.version!=="v4"&&Kt(r,"ipv6",n.message,e);break}case"base64url":mt(r,Gt.base64url,n.message,e);break;case"jwt":mt(r,Gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,Gt.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,Gt.ipv6Cidr,n.message,e);break}case"emoji":mt(r,Gt.emoji(),n.message,e);break;case"ulid":{mt(r,Gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Kt(r,"binary",n.message,e);break}case"contentEncoding:base64":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,Gt.base64,n.message,e);break}}break}case"nanoid":mt(r,Gt.nanoid,n.message,e)}return r}function al(t,e){return e.patternStrategy==="escape"?Jk(t):t}const Bk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Jk(t){let e="";for(let r=0;r<t.length;r++)Bk.has(t[r])||(e+="\\"),e+=t[r];return e}function Kt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):qe(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Vh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",Vh(e,n),r,n)}function Vh(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",o=!1,a=!1,i=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){i?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),i=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],i=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
36
36
|
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
37
37
|
]))`;continue}}if(r.s&&n[c]==="."){s+=a?`${n[c]}\r
|
|
38
38
|
`:`[${n[c]}\r
|
|
39
|
-
]`;continue}s+=n[c],n[c]==="\\"?o=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Jm(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:je(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Et(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:je(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=Hm(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=Vm(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function r6(t,e){if(e.mapStrategy==="record")return Jm(t,e);const r=je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Et(e),n=je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Et(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function n6(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function s6(t){return t.target==="openAi"?void 0:{not:Et({...t,currentPath:[...t.currentPath,"not"]})}}function o6(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ai={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function a6(t,e){if(e.target==="openApi3")return Wm(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ai&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=ai[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Wm(t,e)}const Wm=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>je(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function i6(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ai[t.innerType._def.typeName],nullable:!0}:{type:[ai[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=je(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function c6(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Dm(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?De(r,"minimum",n.value,n.message,e):De(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),De(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?De(r,"maximum",n.value,n.message,e):De(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),De(r,"maximum",n.value,n.message,e));break;case"multipleOf":De(r,"multipleOf",n.value,n.message,e);break}return r}function l6(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(const i in o){let c=o[i];if(c===void 0||c._def===void 0)continue;let l=d6(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=je(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,l||s.push(i))}s.length&&(n.required=s);const a=u6(t,e);return a!==void 0&&(n.additionalProperties=a),n}function u6(t,e){if(t.catchall._def.typeName!=="ZodNever")return je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function d6(t){try{return t.isOptional()}catch{return!0}}const p6=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return je(t.innerType._def,e);const r=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Et(e)},r]}:Et(e)},h6=(t,e)=>{if(e.pipeStrategy==="input")return je(t.in._def,e);if(e.pipeStrategy==="output")return je(t.out._def,e);const r=je(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function f6(t,e){return je(t.type._def,e)}function m6(t,e){const n={type:"array",uniqueItems:!0,items:je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&De(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&De(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function g6(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:je(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function _6(t){return{not:Et(t)}}function v6(t){return Et(t)}const y6=(t,e)=>je(t.innerType._def,e),w6=(t,e,r)=>{switch(e){case U.ZodString:return Hm(t,r);case U.ZodNumber:return c6(t,r);case U.ZodObject:return l6(t,r);case U.ZodBigInt:return FC(t,r);case U.ZodBoolean:return HC();case U.ZodDate:return Fm(t,r);case U.ZodUndefined:return _6(r);case U.ZodNull:return o6(r);case U.ZodArray:return VC(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return a6(t,r);case U.ZodIntersection:return QC(t,r);case U.ZodTuple:return g6(t,r);case U.ZodRecord:return Jm(t,r);case U.ZodLiteral:return XC(t,r);case U.ZodEnum:return KC(t);case U.ZodNativeEnum:return n6(t);case U.ZodNullable:return i6(t,r);case U.ZodOptional:return p6(t,r);case U.ZodMap:return r6(t,r);case U.ZodSet:return m6(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return f6(t,r);case U.ZodNaN:case U.ZodNever:return s6(r);case U.ZodEffects:return GC(t,r);case U.ZodAny:return Et(r);case U.ZodUnknown:return v6(r);case U.ZodDefault:return WC(t,r);case U.ZodBranded:return Vm(t,r);case U.ZodReadonly:return y6(t,r);case U.ZodCatch:return BC(t,r);case U.ZodPipeline:return h6(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})()}};function je(t,e,r=!1){const n=e.seen.get(t);if(e.override){const i=e.override?.(t,e,n,r);if(i!==zC)return i}if(n&&!r){const i=b6(n,e);if(i!==void 0)return i}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=w6(t,t.typeName,e),a=typeof o=="function"?je(o(),e):o;if(a&&S6(t,e,a),e.postProcess){const i=e.postProcess(a,t,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}const b6=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Zm(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Et(e)):e.$refStrategy==="seen"?Et(e):void 0}},S6=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),k6=(t,e)=>{const r=ZC(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:je(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Et(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=je(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Et(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Gm(t){const r=Um(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=UC(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Km(t,e){const r=Yr(t,e);if(!r.success)throw r.error;return r.data}const C6=6e4;let T6=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(cl,r=>{this._oncancel(r)}),this.setNotificationHandler(ul,r=>{this._onprogress(r)}),this.setRequestHandler(ll,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(dl,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new be(Ce.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(hl,async(r,n)=>{const s=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(i.type==="response"||i.type==="error"){const c=i.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),i.type==="response")u(c);else{const h=c,f=new be(h.error.code,h.error.message,h.error.data);u(f)}else{const h=i.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new be(Ce.InvalidParams,`Task not found: ${o}`);if(!Cn(a.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Cn(a.status)){const i=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[Sn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(fl,async(r,n)=>{try{const{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new be(Ce.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(gl,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new be(Ce.InvalidParams,`Task not found: ${r.params.taskId}`);if(Cn(s.status))throw new be(Ce.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new be(Ce.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof be?s:new be(Ce.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),be.fromError(Ce.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};const s=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{s?.(o,a),Xs(o)||uk(o)?this._onresponse(o):ol(o)?this._onrequest(o,a):lk(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=be.fromError(Ce.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Sn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:e.id,error:{code:Ce.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):s?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const i=ck(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,l={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{const h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(u,h)},sendRequest:async(u,h,f)=>{const p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});const m=p.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,h,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(a.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)},async u=>{if(a.signal.aborted)return;const h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ce.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(c);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xs(e))n(e);else{const a=new be(e.error.code,e.error.message,e.error.data);n(a)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Xs(e)&&e.result&&typeof e.result=="object"){const a=e.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,r))}}if(o||this._progressHandlers.delete(r),Xs(e))s(e);else{const a=be.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){const{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof be?a:new be(Ce.InternalError,String(a))}}return}let o;try{const a=await this.request(e,so,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new be(Ce.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:i},Cn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:i.status==="failed"?yield{type:"error",error:new be(Ce.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new be(Ce.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}const c=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof be?a:new be(Ce.InternalError,String(a))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:i,relatedTask:c}=n??{};return new Promise((l,u)=>{const h=g=>{u(g)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(g){h(g);return}n?.signal?.throwIfAborted();const f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),i&&(p.params={...p.params,task:i}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Sn]:c}});const m=g=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(g)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));const y=g instanceof be?g:new be(Ce.RequestTimeout,String(g));u(y)};this._responseHandlers.set(f,g=>{if(!n?.signal?.aborted){if(g instanceof Error)return u(g);try{const y=Yr(r,g.result);y.success?l(y.data):u(y.error)}catch(y){u(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});const v=n?.timeout??C6,_=()=>m(be.fromError(Ce.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(f,v,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);const w=c?.taskId;if(w){const g=y=>{const b=this._responseHandlers.get(f);b?b(y):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,g),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(f),u(y)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(g=>{this._cleanupTimeout(f),u(g)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},pl,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ml,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Ek,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=r?.relatedTask?.taskId;if(n){const i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Sn]:r.relatedTask}}}),this._transport?.send(i,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Sn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){const n=Gm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=Km(e,s);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=Gm(e);this._notificationHandlers.set(n,s=>{const o=Km(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&ol(s.message)){const o=s.message.id,a=this._requestResolvers.get(o);a?(a(new be(Ce.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new be(Ce.InvalidRequest,"Request cancelled"));return}const a=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new be(Ce.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const o=await n.getTask(s,r);if(!o)throw new be(Ce.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,r);const i=await n.getTask(s,r);if(i){const c=ri.parse({method:"notifications/tasks/status",params:i});await this.notification(c),Cn(i.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,a)=>{const i=await n.getTask(s,r);if(!i)throw new be(Ce.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Cn(i.status))throw new be(Ce.InvalidParams,`Cannot update task "${s}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,r);const c=await n.getTask(s,r);if(c){const l=ri.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Cn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function Ym(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function $6(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];Ym(a)&&Ym(o)?r[s]={...a,...o}:r[s]=o}return r}var ii={exports:{}},El={},Qm;function E6(){return Qm||(Qm=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(N,z){return{validate:N,compare:z}}t.fullFormats={date:e(o,a),time:e(c(!0),l),"date-time":e(f(!0),p),"iso-time":e(c(),u),"iso-date-time":e(f(),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:q,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:y,int32:{type:"number",validate:k},int64:{type:"number",validate:T},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,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},t.formatNames=Object.keys(t.fullFormats);function r(N){return N%4===0&&(N%100!==0||N%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(N){const z=n.exec(N);if(!z)return!1;const D=+z[1],F=+z[2],oe=+z[3];return F>=1&&F<=12&&oe>=1&&oe<=(F===2&&r(D)?29:s[F])}function a(N,z){if(N&&z)return N>z?1:N<z?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(N){return function(D){const F=i.exec(D);if(!F)return!1;const oe=+F[1],fe=+F[2],de=+F[3],se=F[4],_e=F[5]==="-"?-1:1,H=+(F[6]||0),A=+(F[7]||0);if(H>23||A>59||N&&!se)return!1;if(oe<=23&&fe<=59&&de<60)return!0;const V=fe-A*_e,j=oe-H*_e-(V<0?1:0);return(j===23||j===-1)&&(V===59||V===-1)&&de<61}}function l(N,z){if(!(N&&z))return;const D=new Date("2020-01-01T"+N).valueOf(),F=new Date("2020-01-01T"+z).valueOf();if(D&&F)return D-F}function u(N,z){if(!(N&&z))return;const D=i.exec(N),F=i.exec(z);if(D&&F)return N=D[1]+D[2]+D[3],z=F[1]+F[2]+F[3],N>z?1:N<z?-1:0}const h=/t|\s/i;function f(N){const z=c(N);return function(F){const oe=F.split(h);return oe.length===2&&o(oe[0])&&z(oe[1])}}function p(N,z){if(!(N&&z))return;const D=new Date(N).valueOf(),F=new Date(z).valueOf();if(D&&F)return D-F}function m(N,z){if(!(N&&z))return;const[D,F]=N.split(h),[oe,fe]=z.split(h),de=a(D,oe);if(de!==void 0)return de||l(F,fe)}const v=/\/|:/,_=/^(?:[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(N){return v.test(N)&&_.test(N)}const g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(N){return g.lastIndex=0,g.test(N)}const b=-2147483648,S=2**31-1;function k(N){return Number.isInteger(N)&&N<=S&&N>=b}function T(N){return Number.isInteger(N)}function x(){return!0}const P=/[^\\]\\Z/;function q(N){if(P.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}})(El)),El}var xl={},Xm;function x6(){return Xm||(Xm=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=Bh(),r=Ee(),n=r.operators,s={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},o={message:({keyword:i,schemaCode:c})=>(0,r.str)`should be ${s[i].okStr} ${c}`,params:({keyword:i,schemaCode:c})=>(0,r._)`{comparison: ${s[i].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(i){const{gen:c,data:l,schemaCode:u,keyword:h,it:f}=i,{opts:p,self:m}=f;if(!p.validateFormats)return;const v=new e.KeywordCxt(f,m.RULES.all.format.definition,"format");v.$data?_():w();function _(){const y=c.scopeValue("formats",{ref:m.formats,code:p.code.formats}),b=c.const("fmt",(0,r._)`${y}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,g(b)))}function w(){const y=v.schema,b=m.formats[y];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${h}": format "${y}" does not define "compare" function`);const S=c.scopeValue("formats",{key:y,ref:b,code:p.code.formats?(0,r._)`${p.code.formats}${(0,r.getProperty)(y)}`:void 0});i.fail$data(g(S))}function g(y){return(0,r._)`${y}.compare(${l}, ${u}) ${s[h].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(t.formatLimitDefinition),i);t.default=a})(xl)),xl}var e0;function I6(){return e0||(e0=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=E6(),n=x6(),s=Ee(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(l,u={keywords:!0})=>{if(Array.isArray(u))return c(l,u,r.fullFormats,o),l;const[h,f]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,o],p=u.formats||r.formatNames;return c(l,p,h,f),u.keywords&&(0,n.default)(l),l};i.get=(l,u="full")=>{const f=(u==="fast"?r.fastFormats:r.fullFormats)[l];if(!f)throw new Error(`Unknown format "${l}"`);return f};function c(l,u,h,f){var p,m;(p=(m=l.opts.code).formats)!==null&&p!==void 0||(m.formats=(0,s._)`require("ajv-formats/dist/formats").${f}`);for(const v of u)l.addFormat(v,h[v])}t.exports=e=i,Object.defineProperty(e,"__esModule",{value:!0}),e.default=i})(ii,ii.exports)),ii.exports}var R6=I6();const t0=pn(R6);function P6(){const t=new Wh({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return t0(t),t}let O6=class{constructor(e){this._ajv=e??P6()}getValidator(e){const r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};class A6{constructor(e){this._client=e}async*callToolStream(e,r=ni,n){const s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},a=s.requestStream({method:"tools/call",params:e},r,o),i=s.getToolOutputValidator(e.name);for await(const c of a){if(c.type==="result"&&i){const l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new be(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const u=i(l.structuredContent);if(!u.valid){yield{type:"error",error:new be(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof be){yield{type:"error",error:u};return}yield{type:"error",error:new be(Ce.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function M6(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function N6(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function ci(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&ci(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)typeof r!="boolean"&&ci(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)typeof r!="boolean"&&ci(r,e)}}function L6(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}let Il=class extends T6{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new O6,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Om,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Im,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",$m,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new A6(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=$6(this._capabilities,e)}setRequestHandler(e,r){const s=Um(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(oi(s)){const i=s;o=i._zod?.def?.value??i.value}else{const i=s;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const a=o;if(a==="elicitation/create"){const i=async(c,l)=>{const u=Yr(Nm,c);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new be(Ce.InvalidParams,`Invalid elicitation request: ${g}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:f,supportsUrlMode:p}=L6(this._capabilities.elicitation);if(h.mode==="form"&&!f)throw new be(Ce.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!p)throw new be(Ce.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(r(c,l));if(h.task){const g=Yr(so,m);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new be(Ce.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const v=Yr(Cl,m);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new be(Ce.InvalidParams,`Invalid elicitation result: ${g}`)}const _=v.data,w=h.mode==="form"?h.requestedSchema:void 0;if(h.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{ci(w,_.content)}catch{}return _};return super.setRequestHandler(e,i)}if(a==="sampling/createMessage"){const i=async(c,l)=>{const u=Yr(Mm,c);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new be(Ce.InvalidParams,`Invalid sampling request: ${m}`)}const{params:h}=u.data,f=await Promise.resolve(r(c,l));if(h.task){const m=Yr(so,f);if(!m.success){const v=m.error instanceof Error?m.error.message:String(m.error);throw new be(Ce.InvalidParams,`Invalid task creation result: ${v}`)}return m.data}const p=Yr(kl,f);if(!p.success){const m=p.error instanceof Error?p.error.message:String(p.error);throw new be(Ce.InvalidParams,`Invalid sampling result: ${m}`)}return p.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Xa,capabilities:this._capabilities,clientInfo:this._clientInfo}},_m,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!ok.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){M6(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&N6(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},kn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Lm,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},kn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},xm,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Em,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},km,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Cm,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Tm,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},kn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},kn,r)}async callTool(e,r=ni,n){if(this.isToolTaskRequired(e.name))throw new be(Ce.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new be(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new be(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof be?a:new be(Ce.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of e){if(r.outputSchema){const s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},Pm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){const o=Xk.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=o.data,{onChanged:c}=n,l=async()=>{if(!a){c(null,null);return}try{const h=await s();c(null,h)}catch(h){const f=h instanceof Error?h:new Error(String(h));c(f,null)}},u=()=>{if(i){const h=this._listChangedDebounceTimers.get(e);h&&clearTimeout(h);const f=setTimeout(l,i);this._listChangedDebounceTimers.set(e,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};class r0 extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Rl(t){}function n0(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Rl,onError:r=Rl,onRetry:n=Rl,onComment:s}=t;let o="",a=!0,i,c="",l="";function u(v){const _=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,g]=q6(`${o}${_}`);for(const y of w)h(y);o=g,a=!1}function h(v){if(v===""){p();return}if(v.startsWith(":")){s&&s(v.slice(v.startsWith(": ")?2:1));return}const _=v.indexOf(":");if(_!==-1){const w=v.slice(0,_),g=v[_+1]===" "?2:1,y=v.slice(_+g);f(w,y,v);return}f(v,"",v)}function f(v,_,w){switch(v){case"event":l=_;break;case"data":c=`${c}${_}
|
|
40
|
-
`;break;case"id":i=
|
|
41
|
-
`)?c.slice(0,-1):c}),i=void 0,c="",l=""}function
|
|
39
|
+
]`;continue}s+=n[c],n[c]==="\\"?o=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Hh(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===z.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??St(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===z.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=Fh(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===z.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=Uh(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function Wk(t,e){if(e.mapStrategy==="record")return Hh(t,e);const r=Ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||St(e),n=Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||St(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Gk(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Kk(t){return t.target==="openAi"?void 0:{not:St({...t,currentPath:[...t.currentPath,"not"]})}}function Yk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ba={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Qk(t,e){if(e.target==="openApi3")return Bh(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ba&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ba[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Bh(t,e)}const Bh=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ne(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Xk(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ba[t.innerType._def.typeName],nullable:!0}:{type:[Ba[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function e6(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",zh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function t6(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(const i in o){let c=o[i];if(c===void 0||c._def===void 0)continue;let l=n6(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Ne(c._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,l||s.push(i))}s.length&&(n.required=s);const a=r6(t,e);return a!==void 0&&(n.additionalProperties=a),n}function r6(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ne(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function n6(t){try{return t.isOptional()}catch{return!0}}const s6=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Ne(t.innerType._def,e);const r=Ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:St(e)},r]}:St(e)},o6=(t,e)=>{if(e.pipeStrategy==="input")return Ne(t.in._def,e);if(e.pipeStrategy==="output")return Ne(t.out._def,e);const r=Ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function a6(t,e){return Ne(t.type._def,e)}function i6(t,e){const n={type:"array",uniqueItems:!0,items:Ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&qe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&qe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function c6(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function l6(t){return{not:St(t)}}function u6(t){return St(t)}const d6=(t,e)=>Ne(t.innerType._def,e),p6=(t,e,r)=>{switch(e){case z.ZodString:return Fh(t,r);case z.ZodNumber:return e6(t,r);case z.ZodObject:return t6(t,r);case z.ZodBigInt:return Lk(t,r);case z.ZodBoolean:return jk();case z.ZodDate:return Zh(t,r);case z.ZodUndefined:return l6(r);case z.ZodNull:return Yk(r);case z.ZodArray:return Nk(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return Qk(t,r);case z.ZodIntersection:return Vk(t,r);case z.ZodTuple:return c6(t,r);case z.ZodRecord:return Hh(t,r);case z.ZodLiteral:return Hk(t,r);case z.ZodEnum:return Zk(t);case z.ZodNativeEnum:return Gk(t);case z.ZodNullable:return Xk(t,r);case z.ZodOptional:return s6(t,r);case z.ZodMap:return Wk(t,r);case z.ZodSet:return i6(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return a6(t,r);case z.ZodNaN:case z.ZodNever:return Kk(r);case z.ZodEffects:return Uk(t,r);case z.ZodAny:return St(r);case z.ZodUnknown:return u6(r);case z.ZodDefault:return Dk(t,r);case z.ZodBranded:return Uh(t,r);case z.ZodReadonly:return d6(t,r);case z.ZodCatch:return qk(t,r);case z.ZodPipeline:return o6(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ne(t,e,r=!1){const n=e.seen.get(t);if(e.override){const i=e.override?.(t,e,n,r);if(i!==Ok)return i}if(n&&!r){const i=f6(n,e);if(i!==void 0)return i}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=p6(t,t.typeName,e),a=typeof o=="function"?Ne(o(),e):o;if(a&&h6(t,e,a),e.postProcess){const i=e.postProcess(a,t,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}const f6=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Dh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),St(e)):e.$refStrategy==="seen"?St(e):void 0}},h6=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),m6=(t,e)=>{const r=Mk(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Ne(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??St(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Ne(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??St(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function g6(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Jh(t,e){return Jt(t)?yc(t,{target:g6(e?.target),io:e?.pipeStrategy??"input"}):m6(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Wh(t){const r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=jh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Gh(t,e){const r=Wt(t,e);if(!r.success)throw r.error;return r.data}const y6=6e4;class Kh{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ic,r=>{this._oncancel(r)}),this.setNotificationHandler(Oc,r=>{this._onprogress(r)}),this.setRequestHandler(Pc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ac,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new re(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Nc,async(r,n)=>{const s=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(i.type==="response"||i.type==="error"){const c=i.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),i.type==="response")u(c);else{const p=c,h=new re(p.error.code,p.error.message,p.error.data);u(h)}else{const p=i.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new re(oe.InvalidParams,`Task not found: ${o}`);if(!hn(a.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(hn(a.status)){const i=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[fn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Lc,async(r,n)=>{try{const{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new re(oe.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(qc,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new re(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(hn(s.status))throw new re(oe.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new re(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof re?s:new re(oe.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),re.fromError(oe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};const s=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{s?.(o,a),Us(o)||g4(o)?this._onresponse(o):$c(o)?this._onrequest(o,a):m4(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=re.fromError(oe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[fn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:e.id,error:{code:oe.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):s?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const i=h4(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,l={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{const p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(u,p)},sendRequest:async(u,p,h)=>{const d={...h,relatedRequestId:e.id};o&&!d.relatedTask&&(d.relatedTask={taskId:o});const f=d.relatedTask?.taskId??o;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(a.signal.aborted)return;const p={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)},async u=>{if(a.signal.aborted)return;const p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:oe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(c);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Us(e))n(e);else{const a=new re(e.error.code,e.error.message,e.error.data);n(a)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Us(e)&&e.result&&typeof e.result=="object"){const a=e.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,r))}}if(o||this._progressHandlers.delete(r),Us(e))s(e);else{const a=re.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){const{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof re?a:new re(oe.InternalError,String(a))}}return}let o;try{const a=await this.request(e,Ln,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new re(oe.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:i},hn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:i.status==="failed"?yield{type:"error",error:new re(oe.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new re(oe.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}const c=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof re?a:new re(oe.InternalError,String(a))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:i,relatedTask:c}=n??{};return new Promise((l,u)=>{const p=g=>{u(g)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(g){p(g);return}n?.signal?.throwIfAborted();const h=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),i&&(d.params={...d.params,task:i}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[fn]:c}});const f=g=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(g)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));const _=g instanceof re?g:new re(oe.RequestTimeout,String(g));u(_)};this._responseHandlers.set(h,g=>{if(!n?.signal?.aborted){if(g instanceof Error)return u(g);try{const _=Wt(r,g.result);_.success?l(_.data):u(_.error)}catch(_){u(_)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});const v=n?.timeout??y6,y=()=>f(re.fromError(oe.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(h,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=c?.taskId;if(w){const g=_=>{const b=this._responseHandlers.get(h);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,g),this._enqueueTaskMessage(w,{type:"request",message:d,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(h),u(_)})}else this._transport.send(d,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(g=>{this._cleanupTimeout(h),u(g)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Mc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},jc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},O4,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=r?.relatedTask?.taskId;if(n){const i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[fn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[fn]:r.relatedTask}}}),this._transport?.send(i,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[fn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){const n=Wh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=Gh(e,s);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=Wh(e);this._notificationHandlers.set(n,s=>{const o=Gh(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&$c(s.message)){const o=s.message.id,a=this._requestResolvers.get(o);a?(a(new re(oe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new re(oe.InvalidRequest,"Request cancelled"));return}const a=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new re(oe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const o=await n.getTask(s,r);if(!o)throw new re(oe.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,r);const i=await n.getTask(s,r);if(i){const c=za.parse({method:"notifications/tasks/status",params:i});await this.notification(c),hn(i.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,a)=>{const i=await n.getTask(s,r);if(!i)throw new re(oe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(hn(i.status))throw new re(oe.InvalidParams,`Cannot update task "${s}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,r);const c=await n.getTask(s,r);if(c){const l=za.parse({method:"notifications/tasks/status",params:c});await this.notification(l),hn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function Yh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qh(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];Yh(a)&&Yh(o)?r[s]={...a,...o}:r[s]=o}return r}var Ja={exports:{}},il={},Xh;function _6(){return Xh||(Xh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(O,D){return{validate:O,compare:D}}t.fullFormats={date:e(o,a),time:e(c(!0),l),"date-time":e(h(!0),d),"iso-time":e(c(),u),"iso-date-time":e(h(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:j,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_,int32:{type:"number",validate:S},int64:{type:"number",validate:C},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(O){const D=n.exec(O);if(!D)return!1;const U=+D[1],V=+D[2],ne=+D[3];return V>=1&&V<=12&&ne>=1&&ne<=(V===2&&r(U)?29:s[V])}function a(O,D){if(O&&D)return O>D?1:O<D?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(O){return function(U){const V=i.exec(U);if(!V)return!1;const ne=+V[1],fe=+V[2],de=+V[3],te=V[4],ye=V[5]==="-"?-1:1,H=+(V[6]||0),P=+(V[7]||0);if(H>23||P>59||O&&!te)return!1;if(ne<=23&&fe<=59&&de<60)return!0;const F=fe-P*ye,q=ne-H*ye-(F<0?1:0);return(q===23||q===-1)&&(F===59||F===-1)&&de<61}}function l(O,D){if(!(O&&D))return;const U=new Date("2020-01-01T"+O).valueOf(),V=new Date("2020-01-01T"+D).valueOf();if(U&&V)return U-V}function u(O,D){if(!(O&&D))return;const U=i.exec(O),V=i.exec(D);if(U&&V)return O=U[1]+U[2]+U[3],D=V[1]+V[2]+V[3],O>D?1:O<D?-1:0}const p=/t|\s/i;function h(O){const D=c(O);return function(V){const ne=V.split(p);return ne.length===2&&o(ne[0])&&D(ne[1])}}function d(O,D){if(!(O&&D))return;const U=new Date(O).valueOf(),V=new Date(D).valueOf();if(U&&V)return U-V}function f(O,D){if(!(O&&D))return;const[U,V]=O.split(p),[ne,fe]=D.split(p),de=a(U,ne);if(de!==void 0)return de||l(V,fe)}const v=/\/|:/,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 g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function _(O){return g.lastIndex=0,g.test(O)}const b=-2147483648,k=2**31-1;function S(O){return Number.isInteger(O)&&O<=k&&O>=b}function C(O){return Number.isInteger(O)}function x(){return!0}const R=/[^\\]\\Z/;function j(O){if(R.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(il)),il}var cl={},e0;function v6(){return e0||(e0=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=Up(),r=Te(),n=r.operators,s={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},o={message:({keyword:i,schemaCode:c})=>(0,r.str)`should be ${s[i].okStr} ${c}`,params:({keyword:i,schemaCode:c})=>(0,r._)`{comparison: ${s[i].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(i){const{gen:c,data:l,schemaCode:u,keyword:p,it:h}=i,{opts:d,self:f}=h;if(!d.validateFormats)return;const v=new e.KeywordCxt(h,f.RULES.all.format.definition,"format");v.$data?y():w();function y(){const _=c.scopeValue("formats",{ref:f.formats,code:d.code.formats}),b=c.const("fmt",(0,r._)`${_}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,g(b)))}function w(){const _=v.schema,b=f.formats[_];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${p}": format "${_}" does not define "compare" function`);const k=c.scopeValue("formats",{key:_,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(_)}`:void 0});i.fail$data(g(k))}function g(_){return(0,r._)`${_}.compare(${l}, ${u}) ${s[p].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(t.formatLimitDefinition),i);t.default=a})(cl)),cl}var t0;function w6(){return t0||(t0=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=_6(),n=v6(),s=Te(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(l,u={keywords:!0})=>{if(Array.isArray(u))return c(l,u,r.fullFormats,o),l;const[p,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,o],d=u.formats||r.formatNames;return c(l,d,p,h),u.keywords&&(0,n.default)(l),l};i.get=(l,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[l];if(!h)throw new Error(`Unknown format "${l}"`);return h};function c(l,u,p,h){var d,f;(d=(f=l.opts.code).formats)!==null&&d!==void 0||(f.formats=(0,s._)`require("ajv-formats/dist/formats").${h}`);for(const v of u)l.addFormat(v,p[v])}t.exports=e=i,Object.defineProperty(e,"__esModule",{value:!0}),e.default=i})(Ja,Ja.exports)),Ja.exports}var b6=w6();const k6=rn(b6);function S6(){const t=new Zp({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return k6(t),t}class r0{constructor(e){this._ajv=e??S6()}getValidator(e){const r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class C6{constructor(e){this._client=e}async*callToolStream(e,r=qn,n){const s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},a=s.requestStream({method:"tools/call",params:e},r,o),i=s.getToolOutputValidator(e.name);for await(const c of a){if(c.type==="result"&&i){const l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new re(oe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const u=i(l.structuredContent);if(!u.valid){yield{type:"error",error:new re(oe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof re){yield{type:"error",error:u};return}yield{type:"error",error:new re(oe.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function n0(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function s0(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function Wa(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Wa(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)typeof r!="boolean"&&Wa(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)typeof r!="boolean"&&Wa(r,e)}}function T6(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class Gs extends Kh{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new r0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Qc,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Kc,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Fc,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new C6(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qh(this._capabilities,e)}setRequestHandler(e,r){const s=Dn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Jt(s)){const i=s;o=i._zod?.def?.value??i.value}else{const i=s;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const a=o;if(a==="elicitation/create"){const i=async(c,l)=>{const u=Wt(el,c);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid elicitation request: ${g}`)}const{params:p}=u.data;p.mode=p.mode??"form";const{supportsFormMode:h,supportsUrlMode:d}=T6(this._capabilities.elicitation);if(p.mode==="form"&&!h)throw new re(oe.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!d)throw new re(oe.InvalidParams,"Client does not support URL-mode elicitation requests");const f=await Promise.resolve(r(c,l));if(p.task){const g=Wt(Ln,f);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}const v=Wt(Js,f);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new re(oe.InvalidParams,`Invalid elicitation result: ${g}`)}const y=v.data,w=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Wa(w,y.content)}catch{}return y};return super.setRequestHandler(e,i)}if(a==="sampling/createMessage"){const i=async(c,l)=>{const u=Wt(Xc,c);if(!u.success){const f=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid sampling request: ${f}`)}const{params:p}=u.data,h=await Promise.resolve(r(c,l));if(p.task){const f=Wt(Ln,h);if(!f.success){const v=f.error instanceof Error?f.error.message:String(f.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${v}`)}return f.data}const d=Wt(Ha,h);if(!d.success){const f=d.error instanceof Error?d.error.message:String(d.error);throw new re(oe.InvalidParams,`Invalid sampling result: ${f}`)}return d.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:zs,capabilities:this._capabilities,clientInfo:this._clientInfo}},gh,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!lh.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){n0(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&s0(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Fr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ah,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Fr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},xh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Eh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},bh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},kh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Sh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Fr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Fr,r)}async callTool(e,r=qn,n){if(this.isToolTaskRequired(e.name))throw new re(oe.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new re(oe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new re(oe.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof re?a:new re(oe.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of e){if(r.outputSchema){const s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},Rh,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){const o=W4.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=o.data,{onChanged:c}=n,l=async()=>{if(!a){c(null,null);return}try{const p=await s();c(null,p)}catch(p){const h=p instanceof Error?p:new Error(String(p));c(h,null)}},u=()=>{if(i){const p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);const h=setTimeout(l,i);this._listChangedDebounceTimers.set(e,h)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class o0 extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function ll(t){}function a0(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=ll,onError:r=ll,onRetry:n=ll,onComment:s}=t;let o="",a=!0,i,c="",l="";function u(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,g]=$6(`${o}${y}`);for(const _ of w)p(_);o=g,a=!1}function p(v){if(v===""){d();return}if(v.startsWith(":")){s&&s(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const w=v.slice(0,y),g=v[y+1]===" "?2:1,_=v.slice(y+g);h(w,_,v);return}h(v,"",v)}function h(v,y,w){switch(v){case"event":l=y;break;case"data":c=`${c}${y}
|
|
40
|
+
`;break;case"id":i=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new o0(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new o0(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:y,line:w}));break}}function d(){c.length>0&&e({id:i,event:l||void 0,data:c.endsWith(`
|
|
41
|
+
`)?c.slice(0,-1):c}),i=void 0,c="",l=""}function f(v={}){o&&v.consume&&p(o),a=!0,i=void 0,c="",l="",o=""}return{feed:u,reset:f}}function $6(t){const e=[];let r="",n=0;for(;n<t.length;){const s=t.indexOf("\r",n),o=t.indexOf(`
|
|
42
42
|
`,n);let a=-1;if(s!==-1&&o!==-1?a=Math.min(s,o):s!==-1?s===t.length-1?a=-1:a=s:o!==-1&&(a=o),a===-1){r=t.slice(n);break}else{const i=t.slice(n,a);e.push(i),n=a+1,t[n-1]==="\r"&&t[n]===`
|
|
43
|
-
`&&n++}}return[e,r]}class s0 extends Event{constructor(e,r){var n,s;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(s=r?.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(o0(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(o0(this),r)}}function j6(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Pl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Pl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Pl(t.cause)}`:t.message:`${t}`}function o0(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var a0=t=>{throw TypeError(t)},Ol=(t,e,r)=>e.has(t)||a0("Cannot "+r),Re=(t,e,r)=>(Ol(t,e,"read from private field"),r?r.call(t):e.get(t)),rt=(t,e,r)=>e.has(t)?a0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Ye=(t,e,r,n)=>(Ol(t,e,"write to private field"),e.set(t,r),r),Ar=(t,e,r)=>(Ol(t,e,"access private method"),r),xt,Tn,Yn,li,ui,ao,Qn,io,Qr,Xn,es,ts,co,er,Al,Ml,Nl,i0,Ll,ql,lo,jl,Ul;class uo extends EventTarget{constructor(e,r){var n,s;super(),rt(this,er),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,rt(this,xt),rt(this,Tn),rt(this,Yn),rt(this,li),rt(this,ui),rt(this,ao),rt(this,Qn),rt(this,io,null),rt(this,Qr),rt(this,Xn),rt(this,es,null),rt(this,ts,null),rt(this,co,null),rt(this,Ml,async o=>{var a;Re(this,Xn).reset();const{body:i,redirected:c,status:l,headers:u}=o;if(l===204){Ar(this,er,lo).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?Ye(this,Yn,new URL(o.url)):Ye(this,Yn,void 0),l!==200){Ar(this,er,lo).call(this,`Non-200 status code (${l})`,l);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Ar(this,er,lo).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(Re(this,xt)===this.CLOSED)return;Ye(this,xt,this.OPEN);const h=new Event("open");if((a=Re(this,co))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){Ar(this,er,lo).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const f=new TextDecoder,p=i.getReader();let m=!0;do{const{done:v,value:_}=await p.read();_&&Re(this,Xn).feed(f.decode(_,{stream:!v})),v&&(m=!1,Re(this,Xn).reset(),Ar(this,er,jl).call(this))}while(m)}),rt(this,Nl,o=>{Ye(this,Qr,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Ar(this,er,jl).call(this,Pl(o))}),rt(this,Ll,o=>{typeof o.id=="string"&&Ye(this,io,o.id);const a=new MessageEvent(o.event||"message",{data:o.data,origin:Re(this,Yn)?Re(this,Yn).origin:Re(this,Tn).origin,lastEventId:o.id||""});Re(this,ts)&&(!o.event||o.event==="message")&&Re(this,ts).call(this,a),this.dispatchEvent(a)}),rt(this,ql,o=>{Ye(this,ao,o)}),rt(this,Ul,()=>{Ye(this,Qn,void 0),Re(this,xt)===this.CONNECTING&&Ar(this,er,Al).call(this)});try{if(e instanceof URL)Ye(this,Tn,e);else if(typeof e=="string")Ye(this,Tn,new URL(e,U6()));else throw new Error("Invalid URL")}catch{throw j6("An invalid or illegal string was specified")}Ye(this,Xn,n0({onEvent:Re(this,Ll),onRetry:Re(this,ql)})),Ye(this,xt,this.CONNECTING),Ye(this,ao,3e3),Ye(this,ui,(n=r?.fetch)!=null?n:globalThis.fetch),Ye(this,li,(s=r?.withCredentials)!=null?s:!1),Ar(this,er,Al).call(this)}get readyState(){return Re(this,xt)}get url(){return Re(this,Tn).href}get withCredentials(){return Re(this,li)}get onerror(){return Re(this,es)}set onerror(e){Ye(this,es,e)}get onmessage(){return Re(this,ts)}set onmessage(e){Ye(this,ts,e)}get onopen(){return Re(this,co)}set onopen(e){Ye(this,co,e)}addEventListener(e,r,n){const s=r;super.addEventListener(e,s,n)}removeEventListener(e,r,n){const s=r;super.removeEventListener(e,s,n)}close(){Re(this,Qn)&&clearTimeout(Re(this,Qn)),Re(this,xt)!==this.CLOSED&&(Re(this,Qr)&&Re(this,Qr).abort(),Ye(this,xt,this.CLOSED),Ye(this,Qr,void 0))}}xt=new WeakMap,Tn=new WeakMap,Yn=new WeakMap,li=new WeakMap,ui=new WeakMap,ao=new WeakMap,Qn=new WeakMap,io=new WeakMap,Qr=new WeakMap,Xn=new WeakMap,es=new WeakMap,ts=new WeakMap,co=new WeakMap,er=new WeakSet,Al=function(){Ye(this,xt,this.CONNECTING),Ye(this,Qr,new AbortController),Re(this,ui)(Re(this,Tn),Ar(this,er,i0).call(this)).then(Re(this,Ml)).catch(Re(this,Nl))},Ml=new WeakMap,Nl=new WeakMap,i0=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Re(this,io)?{"Last-Event-ID":Re(this,io)}:void 0},cache:"no-store",signal:(t=Re(this,Qr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Ll=new WeakMap,ql=new WeakMap,lo=function(t,e){var r;Re(this,xt)!==this.CLOSED&&Ye(this,xt,this.CLOSED);const n=new s0("error",{code:e,message:t});(r=Re(this,es))==null||r.call(this,n),this.dispatchEvent(n)},jl=function(t,e){var r;if(Re(this,xt)===this.CLOSED)return;Ye(this,xt,this.CONNECTING);const n=new s0("error",{code:e,message:t});(r=Re(this,es))==null||r.call(this,n),this.dispatchEvent(n),Ye(this,Qn,setTimeout(Re(this,Ul),Re(this,ao)))},Ul=new WeakMap,uo.CONNECTING=0,uo.OPEN=1,uo.CLOSED=2;function U6(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function di(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function c0(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...di(e.headers),...di(n.headers)}:e.headers};return t(r,s)}:t}let zl;zl=globalThis.crypto;async function z6(t){return(await zl).getRandomValues(new Uint8Array(t))}async function D6(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await z6(t-n.length);for(const o of s)o<r&&(n+=e[o%e.length])}return n}async function Z6(t){return await D6(t)}async function V6(t){const e=await(await zl).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Dl(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await Z6(t),r=await V6(e);return{code_verifier:e,code_challenge:r}}const lt=em().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:nl.custom,message:"URL must be parseable",fatal:!0}),jc}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),F6=Oe({resource:d().url(),authorization_servers:I(lt).optional(),jwks_uri:d().url().optional(),scopes_supported:I(d()).optional(),bearer_methods_supported:I(d()).optional(),resource_signing_alg_values_supported:I(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:ne().optional(),authorization_details_types_supported:I(d()).optional(),dpop_signing_alg_values_supported:I(d()).optional(),dpop_bound_access_tokens_required:ne().optional()}),l0=Oe({issuer:d(),authorization_endpoint:lt,token_endpoint:lt,registration_endpoint:lt.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),service_documentation:lt.optional(),revocation_endpoint:lt.optional(),revocation_endpoint_auth_methods_supported:I(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:I(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:I(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:I(d()).optional(),code_challenge_methods_supported:I(d()).optional(),client_id_metadata_document_supported:ne().optional()}),H6=Oe({issuer:d(),authorization_endpoint:lt,token_endpoint:lt,userinfo_endpoint:lt.optional(),jwks_uri:lt,registration_endpoint:lt.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),acr_values_supported:I(d()).optional(),subject_types_supported:I(d()),id_token_signing_alg_values_supported:I(d()),id_token_encryption_alg_values_supported:I(d()).optional(),id_token_encryption_enc_values_supported:I(d()).optional(),userinfo_signing_alg_values_supported:I(d()).optional(),userinfo_encryption_alg_values_supported:I(d()).optional(),userinfo_encryption_enc_values_supported:I(d()).optional(),request_object_signing_alg_values_supported:I(d()).optional(),request_object_encryption_alg_values_supported:I(d()).optional(),request_object_encryption_enc_values_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),display_values_supported:I(d()).optional(),claim_types_supported:I(d()).optional(),claims_supported:I(d()).optional(),service_documentation:d().optional(),claims_locales_supported:I(d()).optional(),ui_locales_supported:I(d()).optional(),claims_parameter_supported:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:lt.optional(),op_tos_uri:lt.optional(),client_id_metadata_document_supported:ne().optional()}),B6=C({...H6.shape,...l0.pick({code_challenge_methods_supported:!0}).shape}),J6=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:dm().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),W6=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),u0=lt.optional().or(O("").transform(()=>{})),G6=C({redirect_uris:I(lt),token_endpoint_auth_method:d().optional(),grant_types:I(d()).optional(),response_types:I(d()).optional(),client_name:d().optional(),client_uri:lt.optional(),logo_uri:u0,scope:d().optional(),contacts:I(d()).optional(),tos_uri:u0,policy_uri:d().optional(),jwks_uri:lt.optional(),jwks:mt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),K6=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),Y6=G6.merge(K6);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function Q6(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function X6({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}let nt=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Zl=class extends nt{};Zl.errorCode="invalid_request";let pi=class extends nt{};pi.errorCode="invalid_client";let hi=class extends nt{};hi.errorCode="invalid_grant";let fi=class extends nt{};fi.errorCode="unauthorized_client";let Vl=class extends nt{};Vl.errorCode="unsupported_grant_type";let Fl=class extends nt{};Fl.errorCode="invalid_scope";let Hl=class extends nt{};Hl.errorCode="access_denied";let rs=class extends nt{};rs.errorCode="server_error";let Bl=class extends nt{};Bl.errorCode="temporarily_unavailable";let Jl=class extends nt{};Jl.errorCode="unsupported_response_type";let Wl=class extends nt{};Wl.errorCode="unsupported_token_type";let Gl=class extends nt{};Gl.errorCode="invalid_token";let Kl=class extends nt{};Kl.errorCode="method_not_allowed";let Yl=class extends nt{};Yl.errorCode="too_many_requests";let mi=class extends nt{};mi.errorCode="invalid_client_metadata";let Ql=class extends nt{};Ql.errorCode="insufficient_scope";class Xl extends nt{}Xl.errorCode="invalid_target";const eT={[Zl.errorCode]:Zl,[pi.errorCode]:pi,[hi.errorCode]:hi,[fi.errorCode]:fi,[Vl.errorCode]:Vl,[Fl.errorCode]:Fl,[Hl.errorCode]:Hl,[rs.errorCode]:rs,[Bl.errorCode]:Bl,[Jl.errorCode]:Jl,[Wl.errorCode]:Wl,[Gl.errorCode]:Gl,[Kl.errorCode]:Kl,[Yl.errorCode]:Yl,[mi.errorCode]:mi,[Ql.errorCode]:Ql,[Xl.errorCode]:Xl};let Ft=class extends Error{constructor(e){super(e??"Unauthorized")}};function tT(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const eu="code",tu="S256";function rT(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&tT(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function nT(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":sT(s,o,r);return;case"client_secret_post":oT(s,o,n);return;case"none":aT(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function sT(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function oT(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function aT(t,e){e.set("client_id",t)}async function d0(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=W6.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=eT[s]||rs;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new rs(s)}}async function $n(t,e){try{return await ru(t,e)}catch(r){if(r instanceof pi||r instanceof fi)return await t.invalidateCredentials?.("all"),await ru(t,e);if(r instanceof hi)return await t.invalidateCredentials?.("tokens"),await ru(t,e);throw r}}async function ru(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await lT(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",e));const c=await cT(e,t,a),l=await fT(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=l?.client_id_metadata_document_supported===!0,w=t.clientMetadataUrl;if(w&&!iT(w))throw new mi(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(_&&w)u={client_id:w},await t.saveClientInformation?.(u);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const y=await yT(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(y),u=y}}const h=!t.redirectUrl;if(r!==void 0||h){const _=await vT(t,i,{metadata:l,resource:c,authorizationCode:r,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}const f=await t.tokens();if(f?.refresh_token)try{const _=await _T(i,{metadata:l,clientInformation:u,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof nt)||_ instanceof rs))throw _}const p=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:v}=await mT(i,{metadata:l,clientInformation:u,state:p,redirectUrl:t.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(v),await t.redirectToAuthorization(m),"REDIRECT"}function iT(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function cT(t,e,r){const n=Q6(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!X6({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 gi(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=nu(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=nu(t,"scope")||void 0,i=nu(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function nu(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}async function lT(t,e,r=fetch){const n=await pT(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return F6.parse(await n.json())}async function su(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?su(t,void 0,r):void 0;throw n}}function uT(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function p0(t,e,r=fetch){return await su(t,{"MCP-Protocol-Version":e},r)}function dT(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function pT(t,e,r,n){const s=new URL(t),o=n?.protocolVersion??Xa;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const c=uT(e,s.pathname);a=new URL(c,n?.metadataServerUrl??s),a.search=s.search}let i=await p0(a,o,r);if(!n?.metadataUrl&&dT(i,s.pathname)){const c=new URL(`/.well-known/${e}`,s);i=await p0(c,o,r)}return i}function hT(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function fT(t,{fetchFn:e=fetch,protocolVersion:r=Xa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=hT(t);for(const{url:o,type:a}of s){const i=await su(o,n,e);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?l0.parse(await i.json()):B6.parse(await i.json())}}}async function mT(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(eu))throw new Error(`Incompatible auth server: does not support response type ${eu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(tu))throw new Error(`Incompatible auth server: does not support code challenge method ${tu}`)}else i=new URL("/authorize",t);const c=await Dl(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",eu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",tu),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}function gT(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function h0(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:a}){const i=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),s)await s(c,r,i,e);else if(n){const u=e?.token_endpoint_auth_methods_supported??[],h=rT(n,u);nT(h,n,c,r)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!l.ok)throw await d0(l);return J6.parse(await l.json())}async function _T(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await h0(t,{metadata:e,tokenRequestParams:i,clientInformation:r,addClientAuthentication:o,resource:s,fetchFn:a});return{refresh_token:n,...c}}async function vT(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:o}={}){const a=t.clientMetadata.scope;let i;if(t.prepareTokenRequest&&(i=await t.prepareTokenRequest(a)),!i){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const l=await t.codeVerifier();i=gT(s,l,t.redirectUrl)}const c=await t.clientInformation();return h0(e,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function yT(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await d0(o);return Y6.parse(await o.json())}let wT=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},f0=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=c0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Ft("No auth provider");let e;try{e=await $n(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Ft;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=di(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new uo(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await e(s,{...o,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:c,scope:l}=gi(i);this._resourceMetadataUrl=c,this._scope=l}return i}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{if(s.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const o=new wT(s.code,s.message,s);n(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{const o=s;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=s=>{const o=s;let a;try{a=Wn.parse(JSON.parse(o.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Ft("No auth provider");if(await $n(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._endpoint,n);if(!s.ok){const o=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=gi(s);if(this._resourceMetadataUrl=a,this._scope=i,await $n(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};class En extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(o){s=n0({onEvent:a=>{o.enqueue(a)},onError(a){e==="terminate"?o.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}const bT={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};let ns=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},ST=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=c0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??bT}async _authThenStart(){if(!this._authProvider)throw new Ft("No auth provider");let e;try{e=await $n(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Ft;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=di(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){const{resumptionToken:r}=e;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const s=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!s.ok){if(await s.body?.cancel(),s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new ns(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1,c=!1;(async()=>{try{const u=e.pipeThrough(new TextDecoderStream).pipeThrough(new En({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){const{value:p,done:m}=await u.read();if(m)break;if(p.id&&(a=p.id,i=!0,s?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{const v=Wn.parse(JSON.parse(p.data));Xs(v)&&(c=!0,o!==void 0&&(v.id=o)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ft("No auth provider");if(await $n(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{const{resumptionToken:n,onresumptiontoken:s}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ol(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const f=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ns(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:p,scope:m}=gi(i);if(this._resourceMetadataUrl=p,this._scope=m,await $n(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:p,scope:m,error:v}=gi(i);if(v==="insufficient_scope"){const _=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new ns(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=_??void 0,await $n(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ft;return this.send(e)}}throw new ns(i.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),bk(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}const u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,h=i.headers.get("content-type");if(u)if(h?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:s},!1);else if(h?.includes("application/json")){const f=await i.json(),p=Array.isArray(f)?f.map(m=>Wn.parse(m)):[Wn.parse(f)];for(const m of p)this.onmessage?.(m)}else throw await i.body?.cancel(),new ns(-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 e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new ns(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};const kT="mcp";let CT=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,kT),this._socket.onerror=n=>{const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),this.onerror?.(s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let s;try{s=Wn.parse(JSON.parse(n.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(s)}})}async close(){this._socket?.close()}send(e){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),r()})}};const Xr=Lt;(function(t,e){const r=Lt,n=Lt,s=t();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(_i,-118057+3521*-35+-2099*-233);const m0=()=>{const t=Lt,e=Lt,r={};r[t(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[e(394)]=e(414),r.ktWqD=function(a,i){return a!==i},r[t(424)]=t(391);const n=r,s=n[e(420)].split("|");let o=859*2+-3*-1039+-4835*1;for(;;){switch(s[o++]){case"0":if(n[e(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[e(405)](typeof global,"undefined"))return global;continue;case"3":if(n[e(405)](typeof globalThis,n[t(394)]))return globalThis;continue;case"4":return Function(n[t(424)])()}break}},TT=(t,e,r)=>{const n=Lt,s=Lt,o={};o.eOzBp=function(i,c){return i!==c},o.ooaJk="undefined",o[n(402)]=function(i,c){return i===c},o[n(421)]="function";const a=o;a[s(389)](typeof window,a.ooaJk)?t[s(423)](e,"*",r):n(423)in t&&a.pTvSc(typeof t[s(423)],a[n(421)])&&t.postMessage(e,r)},$T=(t,e)=>{const r=Lt,n=Lt,s={};s.nTCfA=function(a,i){return a in i},s[r(390)]="addEventListener",s[r(385)]=function(a,i){return a===i},s[r(409)]="function",s.VaHpd=n(392),s[n(384)]=r(417),s.FPOYW=function(a,i){return a!==i};const o=s;o.nTCfA(o.ogKey,t)&&o[n(385)](typeof t.addEventListener,o[n(409)])?t[n(386)](o.VaHpd,e):o[n(384)]in t&&o[r(398)](typeof t[n(417)],r(414))&&(t.onmessage=e)};class po{constructor(e){this._port=e}async[Xr(401)](){const e=Xr,r=Xr;this[e(422)]&&(this[r(422)].onmessage=n=>{var s,o;const a=e;try{const i=Wn.parse(n.data.message);(s=this.onmessage)==null||s.call(this,i,n[a(412)][a(428)])}catch(i){const c=new Error("MessageChannel failed to parse message: "+i);(o=this[a(383)])==null||o.call(this,c)}},this._port.onmessageerror=n=>{var s;const o=r,a=new Error("MessageChannel transport error: "+JSON[o(415)](n));(s=this.onerror)==null||s.call(this,a)},this[r(422)].start())}async send(e,r){const n={EoBZE:function(s){return s()},leEiG:function(s,o){return s instanceof o},cDUwk:function(s,o){return s(o)}};return new Promise((s,o)=>{var a;const i=Lt,c=Lt;try{const l={};l[i(404)]=r?.[i(404)];const u={};u[i(392)]=e,u.extra=l,this._port&&this._port[c(423)](u),n[i(399)](s)}catch(l){const u=n.leEiG(l,Error)?l:new Error(n.cDUwk(String,l));(a=this.onerror)==null||a.call(this,u),o(u)}})}async close(){var e,r;const n=Xr,s=Xr;(e=this._port)==null||e[n(393)](),this[n(422)]=void 0,(r=this[s(408)])==null||r.call(this)}}class ou extends po{constructor(e,r=m0()){const n=Xr,s={lSpBh:function(a,i,c,l){return a(i,c,l)}};super(),this._endpoint=e,this._globalObject=r;const o=new MessageChannel;this._port=o[n(410)],s[n(418)](TT,this._globalObject,{endpoint:this[n(397)]},[o[n(429)]])}}class au extends po{constructor(e,r=m0()){const n=Xr,s=Xr,o={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,c){return a(i,c)}};super(),this[n(397)]=e,this[s(388)]=r,this[s(416)]=new Promise(a=>{const i=n,c={XlglK:function(l,u){return o.HITdC(l,u)},pXlad:function(l){return o.QdDxM(l)}};o[i(427)]($T,this._globalObject,l=>{const u=i,h=i;l[u(412)]&&c.XlglK(l.data[h(396)],this._endpoint)&&(this[u(422)]=l[h(430)][-3036+-1518*-2],c.pXlad(a))})})}async listen(){return this._listen}}function _i(){const t=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return _i=function(){return t},_i()}function Lt(t,e){const r=_i();return Lt=function(n,s){return n=n-(17227+1*-16844),r[n]},Lt(t,e)}const ET=()=>{const t=new MessageChannel;return[new po(t.port1),new po(t.port2)]};(function(t,e){const r=Be,n=Be,s=t();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(vi,-411935*1+228107+208149*2);const xT=async(t,e,r)=>{var n;const s=Be,o=Be,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[s(475)]=s(411),a.SoCaE="resources/templates/list",a[o(484)]="resources/read",a[s(461)]="prompts/get",a.srIIC=o(477),a[o(436)]=o(478),a[o(442)]=s(437),a.dEmVs=s(465);const i=a,{id:c,method:l,params:u}=r;let h={};switch(l){case i.VRyiJ:h=await e.listTools(u);break;case i.VkPYu:h=await e.callTool(u);break;case i.fgMSD:h=await e.listResources(u);break;case i[o(466)]:h=await e.listResourceTemplates(u);break;case i.sthgI:h=await e[s(455)](u);break;case o(486):h=await e.subscribeResource(u);break;case s(410):h=await e.unsubscribeResource(u);break;case i[o(461)]:h=await e[o(414)](u);break;case i[s(412)]:h=await e[s(491)](u);break;case i[s(436)]:h=await e[s(478)]();break;case i.kkNqg:h=await e.complete(u);break;case s(464):h=await e.setLoggingLevel(u?.[o(443)]);break}const f={};f.result=h,f.jsonrpc=i[o(472)],f.id=c,await((n=t?.[o(488)])==null?void 0:n[s(460)](f))},IT=async(t,e,r)=>{var n;const s=Be,o=Be,a={};a[s(487)]=o(462),a.ypHTC="ping",a.fPExS=s(465);const i=a,{id:c,method:l,params:u}=r;let h={};switch(l){case"roots/list":const p={};p.method=l,p[o(446)]=u,h=await e[s(469)](p,qm);break;case"sampling/createMessage":const m={};m[s(481)]=l,m[s(446)]=u,h=await e.request(m,kl);break;case i[s(487)]:const v={};v.method=l,v[o(446)]=u,h=await e.request(v,Cl);break;case i.ypHTC:const _={};_.method=l,h=await e.request(_,kn);break}const f={};return f.result=h,f.jsonrpc=i.fPExS,f.id=c,await((n=t?.transport)==null?void 0:n.send(f)),h};function Be(t,e){const r=vi();return Be=function(n,s){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Be(t,e)}const RT=(t,e)=>{const r=Be,n=Be,s={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,c,l){return a(i,c,l)},yfZbw:"2.0"},o=t._onrequest;t[n(463)]=async(a,i)=>{var c,l,u,h,f;const p=n,m=r,{id:v,method:_}=a;try{s[p(451)](_,s.DhPFX)?await o.call(t,a,i):await s[m(474)](xT,t,e,a)}catch(w){const{code:g,message:y,data:b}=w;try{if(g){const S={};S[m(485)]=g,S[p(422)]=y,S.data=b;const k={};k[m(448)]=S,k.jsonrpc=s[p(417)],k.id=v,await((c=t?.transport)==null?void 0:c[m(460)](k))}else(u=(l=t?.transport)==null?void 0:l.onerror)==null||u.call(l,w)}catch(S){(f=(h=t?.transport)==null?void 0:h.onerror)==null||f.call(h,S)}}}},PT=(t,e)=>{const r=Be,n=Be,s={};s[r(476)]=r(439),s[r(431)]=function(a,i){return a!==i},s.UPdQt="notifications/cancelled";const o=s;t[r(421)]=async a=>{var i,c;const l=r,u=n,{method:h,params:f}=a;if(h!==o[l(476)]&&(o.QWYMz(h,o.UPdQt)||f?.[u(490)]))try{await e[l(445)](a)}catch(p){(c=(i=t?.[l(488)])==null?void 0:i[l(480)])==null||c.call(i,p)}}},OT=(t,e)=>async r=>{var n,s,o,a,i;const c=Be,l=Be,u={TJhyV:function(h,f,p,m){return h(f,p,m)},MMNTY:c(465)};try{return await u.TJhyV(IT,t,e,r)}catch(h){const{code:f,message:p,data:m}=h;try{if(f){const v={};v.code=f,v[c(422)]=p,v[l(419)]=m;const _={};_[c(448)]=v,_[c(424)]=u.MMNTY,_.id=r.id,await((n=t?.transport)==null?void 0:n[l(460)](_))}else(o=(s=t?.transport)==null?void 0:s[c(480)])==null||o.call(s,h)}catch(v){(i=(a=t?.[c(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},AT=(t,e)=>async r=>{var n,s,o;const a=Be,i=Be,c={};c.xmcLM=function(f,p){return f!==p},c.xSWLt="notifications/initialized",c[a(420)]=i(453);const l=c,{method:u,params:h}=r;if(l.xmcLM(u,l.xSWLt)&&(l.xmcLM(u,l[i(420)])||h?.[i(490)]))try{const f={...r};f.jsonrpc=a(465),await((n=e?.[a(488)])==null?void 0:n.send(f))}catch(f){(o=(s=t?.transport)==null?void 0:s.onerror)==null||o.call(s,f)}};function vi(){const t=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return vi=function(){return t},vi()}const MT=(t,e)=>async r=>{var n,s,o,a,i,c;const l=Be,u=Be,h={};h.kSvAZ=l(465);const f=h;try{await((n=e?.[u(488)])==null?void 0:n[u(460)](r))}catch(p){const{code:m,message:v,data:_}=p;try{if(m){const w={};w.code=m,w.message=v,w.data=_;const g={};g.error=w,g[u(424)]=f.kSvAZ,g.id=r.id,await((s=t?.transport)==null?void 0:s.send(g))}else(a=(o=t?.transport)==null?void 0:o[l(480)])==null||a.call(o,p)}catch(w){(c=(i=t?.[l(488)])==null?void 0:i[u(480)])==null||c.call(i,w)}}},iu=()=>{const t=Be,e={rgPZO:function(c,l){return c!==l},VWsxO:function(c,l){return c(l)},FjTAY:"function"},r=[],n=(c,l)=>{const u=Be;if(l){const h=[];for(const f of r)try{h.push(f(c,l))}catch{}for(const f of h)if(e.rgPZO(f,null))return f}else for(const h of r)try{e[u(427)](h,c)}catch{}},s=c=>{const l=Be,u=Be;typeof c===e[l(456)]&&!r.includes(c)&&r[u(471)](c)},o=c=>{const l=Be,u=r[l(415)](c);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const c=Be;r[c(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[t(447)]=s,i.removeListener=o,i.clearListener=a,i},NT=t=>{const e=Be,r=Be,n={UlqiY:function(s){return s()},jsmFN:function(s){return s()}};{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(423)](iu);t._onresponse=s,t[r(438)]=o,t.removeResponseListener=a,t.clearResponseListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(489)](iu);t[e(432)]=s,t[r(473)]=o,t.removeRequestListener=a,t.clearRequestListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n.jsmFN(iu);t.fallbackNotificationHandler=s,t[e(444)]=o,t.removeNotificationListener=a,t[r(426)]=i}},LT=(t,{beforeInit:e,afterInit:r}={})=>{const n=Be,s=Be,o={HucXo:function(i,c){return i===c},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,c){return i(c)},UynHf:function(i,c){return i===c},yCyFn:function(i){return i()}},a=new Map(t._notificationHandlers);t[n(454)].clear(),t._notificationHandlers.clear(),o.HucXo(typeof e,o.HicFO)&&o[n(435)](e),o[n(467)](t[n(449)][s(428)],n(449))&&(t[s(413)]=t[s(449)]),o.DclXr(NT,t),t[s(438)](i=>{const c=n;t.originalOnResponse[c(440)](t,i)}),o[n(429)](typeof r,o.HicFO)&&o[s(425)](r),t[s(444)](i=>{const c=s,{method:l}=i,u=a[c(483)](l);o[c(467)](typeof u,"function")&&u(i)})},qT=Mr;(function(t,e){const r=Mr,n=Mr,s=t();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(yi,995159+-6*-266138+-1619768);const jT=()=>{const t=Mr,e=Mr,r={};r.svuxn=function(s,o){return s&o},r.ZUPdr=function(s,o){return s===o},r[t(227)]=function(s,o){return s===o},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[e(227)](typeof crypto,"object")&&crypto[t(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,s=>{const o=t,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[o(225)](s,"x")?a:n[o(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},UT=t=>{const e=Mr,r=Mr,n=new Uint8Array(t);return crypto[e(221)](n),Array[r(218)](n,s=>s[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[e(213)]("")},en={};en[qT(211)]=jT,en.randomBytes=UT;function Mr(t,e){const r=yi();return Mr=function(n,s){return n=n-(-7373+7187*1+395),r[n]},Mr(t,e)}function yi(){const t=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return yi=function(){return t},yi()}function Nr(t,e){const r=wi();return Nr=function(n,s){return n=n-(-1483*3+-5564+20*513),r[n]},Nr(t,e)}const tr=Nr,ho=Nr;(function(t,e){const r=Nr,n=Nr,s=t();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(wi,-4*308317+753182*2+658196);const zT=(t,e)=>{const r=Nr,n=Nr,s={olCWX:function(c,l,u){return c(l,u)},sfXDX:function(c,l,u){return c(l,u)},ksWFu:function(c,l,u){return c(l,u)}};s[r(283)](RT,t,e),PT(t,e);const o=s[n(283)](OT,e,t),a=s[n(294)](MT,e,t),i=s[r(277)](AT,e,t);e.addRequestListener(o),e.addResponseListener(a),e[n(287)](i),t.onclose=()=>{const c=r,l=n;e[c(247)](o),e.removeResponseListener(a),e[l(252)](i)}},cu=(t,e,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,c){return a(i,c)}},s=()=>{var a;n.QhPqi(r,f0)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Nr(295)])==null||i.close()})),n.Qalmc(zT,t,e)},o={};o.afterInit=s,n.Qalmc(LT,e,o)},g0=(t,e=en[tr(299)]())=>{const r=tr,n=tr,s={RVabx:function(u,h,f){return u(h,f)},crCTs:"include"},o={};o["sse-session-id"]=e;const a=o,i={};i["sse-session-id"]=e;const c={};c.headers=i,c.credentials=s[r(304)];const l={requestInit:c,eventSourceInit:{async fetch(u,h){const f=r,p=r,m=new Headers(h?.[f(268)]||{});Object.entries(a).forEach(([_,w])=>{m.set(_,w)});const v={...h};return v.headers=m,s[p(279)](fetch,u,v)},withCredentials:!0}};return t&&(l[r(280)].headers.Authorization="Bearer "+t,a.Authorization=n(256)+t),l},_0=(t,e=en[tr(299)]())=>{const r=ho,n=tr,s={};s[r(271)]="include";const o=s,a={};a["stream-session-id"]=e;const i={};i[n(268)]=a,i.credentials=o[r(271)];const c={};c.requestInit=i;const l=c;return t&&(l[n(280)][r(268)][n(301)]=r(256)+t),l},lu=async(t,e,r)=>{const n=tr,s=tr,o={rRtFD:function(i){return i()},ToRAF:function(i,c){return i instanceof c}},a=o[n(276)](r);try{return await t[s(260)](a),a}catch(i){if(o[n(275)](i,Ft)){const c=await e();return await a[n(257)](c),await lu(t,e,r)}else throw i}},v0=(t,e)=>{const r=ho,n=ho,s={};s[r(267)]=function(a,i){return a in i},s.timcZ="waitForOAuthCode",s[r(253)]=function(a,i){return a===i},s.ufiEQ=r(285),s[n(250)]=r(293);const o=s;if(o.oGmBG(o[r(258)],t))return t[n(278)];if(o[n(253)](typeof e,o.ufiEQ))return e;throw new Error(o.daYBw)};function wi(){const t=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return wi=function(){return t},wi()}const DT=async t=>{const e=ho,r=tr,n={GKDjq:function(P,q,N){return P(q,N)},JzpWy:e(281),mcbiU:"1.0.0",CfBXU:function(P){return P()},kdowC:function(P,q,N,z){return P(q,N,z)},KkViY:"sessionId"},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,eventSourceInit:u,waitForOAuthCode:h}=t,f={};f[r(305)]=c,f.requestInit=l,f.eventSourceInit=u;const p=f,m=i||en[r(299)](),v=n[e(289)](g0,a,m);if(l){const P={...v.requestInit,...l};P[r(268)]={...v[r(280)][e(268)],...l.headers},p.requestInit=P}else p.requestInit=v[e(280)];if(u){const P={...v[e(270)],...u};p.eventSourceInit=P}else p.eventSourceInit=v[e(270)];const _={};_[e(254)]=!0;const w={};w.roots=_,w[e(298)]={},w[r(303)]={};const g=w,y={};y.name=n[r(261)],y[e(288)]=n.mcbiU;const b={};b[e(251)]=g;const S=new Il(y,b),k=()=>new f0(new URL(o),p);let T=n[e(282)](k);if(c){const P=v0(c,h);T=await n[e(263)](lu,S,P,k)}else await S.connect(T);cu(S,s,T),T.sessionId=T[r(274)].searchParams[e(297)](n.KkViY);const x={};return x.transport=T,x.sessionId=T[r(286)],x},ZT=async t=>{const e=ho,r=tr,n={wfHUn:function(P,q,N){return P(q,N)},tUMle:"mcp-stream-proxy-client",omKPe:e(248),rSiEq:function(P){return P()},PdsSn:function(P,q,N,z){return P(q,N,z)}},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,reconnectionOptions:u,waitForOAuthCode:h}=t,f={};f.authProvider=c,f.requestInit=l,f.reconnectionOptions=u;const p=f,m=i||en.randomUUID(),v=n[r(272)](_0,a,m);if(l){const P={...v[e(280)],...l};P.headers={...v.requestInit[e(268)],...l.headers},p.requestInit=P}else p[r(280)]=v[r(280)];const _={};_[r(254)]=!0;const w={};w.roots=_,w[e(298)]={},w[e(303)]={};const g=w,y={};y.name=n[e(262)],y.version=n.omKPe;const b={};b.capabilities=g;const S=new Il(y,b),k=()=>new ST(new URL(o),p);let T=n.rSiEq(k);if(c){const P=n[e(272)](v0,c,h);T=await n[e(296)](lu,S,P,k)}else await S[e(260)](T);n.PdsSn(cu,S,s,T);const x={};return x.transport=T,x[r(286)]=T[r(286)],x},VT=async t=>{const e=tr,r=tr,n={eZwNI:function(w,g,y,b){return w(g,y,b)}},{client:s,url:o,token:a,sessionId:i}=t,c={};c[e(254)]=!0;const l={};l[r(290)]=c,l.sampling={},l.elicitation={};const u=l,h={};h.name="mcp-socket-proxy-client",h.version=r(248);const f={};f[r(251)]=u;const p=new Il(h,f),m=i||en[r(299)](),v=new CT(new URL(o+"?sessionId="+m+r(265)+a));await p.connect(v),n[e(259)](cu,p,s,v);const _={};return _.transport=v,_[r(286)]=m,_},tn=rr,fo=rr;(function(t,e){const r=rr,n=rr,s=t();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(bi,1297719+-42747*-22+-1289197);function rr(t,e){const r=bi();return rr=function(n,s){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},rr(t,e)}const FT=()=>en.randomBytes(-8746+-382*-23);class HT{constructor(e){const r=rr,n=rr,s={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:o,state:a,redirectCallback:i,getAuthCodeByState:c,waitForOAuthCode:l}=e;this._clientMetadata=o,this[r(206)]=o.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||s.HbwOh(FT),this._redirectCallback=i||this[n(202)],this[n(195)]=c||this[r(191)],this.waitForOAuthCode=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,n,s,o,a,i;const c=rr,l=rr,u={};u[c(198)]="GET";const h=await fetch(e,u);!h.ok&&((n=(r=this[l(207)])[l(196)])==null||n.call(r,c(208)+h[l(205)]));const f=await this[l(195)](this._redirectUrl,this[c(197)]);if(!f.ok){(o=(s=this[c(207)]).reject)==null||o.call(s,"Failed to fetch auth code: "+f[l(205)]);return}const p=await f.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,p.code)}async[tn(191)](e,r){const n=tn,s={};s.xAOmI="POST";const o=s,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(e,{method:o.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const e=this._callBackPromise;return()=>new Promise((r,n)=>{const s=rr;e.resolve=r,e[s(196)]=n})}get redirectUrl(){return this[tn(206)]}get[fo(190)](){return this._clientMetadata}[tn(213)](){return this[tn(197)]}[fo(218)](){return this[fo(200)]}[tn(194)](e){this._clientInformation=e}tokens(){return this[fo(210)]}saveTokens(e){const r=fo;this[r(210)]=e}redirectToAuthorization(e){this._redirectCallback(e)}saveCodeVerifier(e){this._codeVerifier=e}[tn(212)](){const e=tn,r={};r[e(215)]=e(214);const n=r;if(!this[e(209)])throw new Error(n.mMdVl);return this[e(209)]}}function bi(){const t=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return bi=function(){return t},bi()}(function(t,e){for(var r=ki,n=ki,s=t();;)try{var o=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(o===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(Si,262*-2438+1346066*-1+2*1373311);function Si(){var t=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Si=function(){return t},Si()}function ki(t,e){var r=Si();return ki=function(n,s){n=n-287;var o=r[n];return o},ki(t,e)}function nr(t){return!!t._zod}function mo(t){const e=Object.values(t);if(e.length===0)return jm({});const r=e.every(nr),n=e.every(s=>!nr(s));if(r)return jm(t);if(n)return lf(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ci(t,e){return nr(t)?Ba(t,e):t.safeParse(e)}async function uu(t,e){return nr(t)?await Vc(t,e):await t.safeParseAsync(e)}function go(t){var e,r;if(!t)return;let n;if(nr(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function _o(t){var e;if(t){if(typeof t=="object"){const r=t,n=t;if(!r._def&&!n._zod){const s=Object.values(t);if(s.length>0&&s.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return mo(t)}}if(nr(t)){const n=(e=t._zod)===null||e===void 0?void 0:e.def;if(n&&(n.typeName==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function du(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){const e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function BT(t){var e,r,n,s;if(nr(t))return(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.description;const o=t;return(n=t.description)!==null&&n!==void 0?n:(s=o._def)===null||s===void 0?void 0:s.description}function JT(t){var e,r,n;if(nr(t))return((r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.typeName)==="ZodOptional";const s=t;return typeof t.isOptional=="function"?t.isOptional():((n=s._def)===null||n===void 0?void 0:n.typeName)==="ZodOptional"}function y0(t){var e;if(nr(t)){const a=(e=t._zod)===null||e===void 0?void 0:e.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const s=t.value;if(s!==void 0)return s}const vo="2025-06-18",w0=[vo,"2025-03-26","2024-11-05","2024-10-07"],Ti="2.0",vr=tl(t=>t!==null&&(typeof t=="object"||typeof t=="function")),b0=ee([d(),M().int()]),S0=d(),WT=Oe({progressToken:b0.optional()}),sr=Oe({_meta:WT.optional()}),It=C({method:d(),params:sr.optional()}),ss=Oe({_meta:ie(d(),he()).optional()}),or=C({method:d(),params:ss.optional()}),Ht=Oe({_meta:ie(d(),he()).optional()}),$i=ee([d(),M().int()]),k0=C({jsonrpc:O(Ti),id:$i,...It.shape}).strict(),C0=t=>k0.safeParse(t).success,T0=C({jsonrpc:O(Ti),...or.shape}).strict(),GT=t=>T0.safeParse(t).success,$0=C({jsonrpc:O(Ti),id:$i,result:Ht}).strict(),pu=t=>$0.safeParse(t).success;var Me;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Me||(Me={}));const E0=C({jsonrpc:O(Ti),id:$i,error:C({code:M().int(),message:d(),data:Q(he())})}).strict(),KT=t=>E0.safeParse(t).success,rn=ee([k0,T0,$0,E0]),xn=Ht.strict(),YT=ss.extend({requestId:$i,reason:d().optional()}),hu=or.extend({method:O("notifications/cancelled"),params:YT}),QT=C({src:d(),mimeType:d().optional(),sizes:I(d()).optional()}),yo=C({icons:I(QT).optional()}),os=C({name:d(),title:d().optional()}),x0=os.extend({...os.shape,...yo.shape,version:d(),websiteUrl:d().optional()}),XT=Ys(C({applyDefaults:ne().optional()}),ie(d(),he())),e$=rl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ys(C({form:XT.optional(),url:vr.optional()}),ie(d(),he()).optional())),t$=C({experimental:ie(d(),vr).optional(),sampling:C({context:vr.optional(),tools:vr.optional()}).optional(),elicitation:e$.optional(),roots:C({listChanged:ne().optional()}).optional()}),r$=sr.extend({protocolVersion:d(),capabilities:t$,clientInfo:x0}),I0=It.extend({method:O("initialize"),params:r$}),n$=C({experimental:ie(d(),vr).optional(),logging:vr.optional(),completions:vr.optional(),prompts:Q(C({listChanged:Q(ne())})),resources:C({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:C({listChanged:ne().optional()}).optional()}),R0=Ht.extend({protocolVersion:d(),capabilities:n$,serverInfo:x0,instructions:d().optional()}),fu=or.extend({method:O("notifications/initialized")}),s$=t=>fu.safeParse(t).success,mu=It.extend({method:O("ping")}),o$=C({progress:M(),total:Q(M()),message:Q(d())}),a$=C({...ss.shape,...o$.shape,progressToken:b0}),gu=or.extend({method:O("notifications/progress"),params:a$}),i$=sr.extend({cursor:S0.optional()}),Ei=It.extend({params:i$.optional()}),xi=Ht.extend({nextCursor:Q(S0)}),P0=C({uri:d(),mimeType:Q(d()),_meta:ie(d(),he()).optional()}),O0=P0.extend({text:d()}),_u=d().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),A0=P0.extend({blob:_u}),M0=C({...os.shape,...yo.shape,uri:d(),description:Q(d()),mimeType:Q(d()),_meta:Q(Oe({}))}),c$=C({...os.shape,...yo.shape,uriTemplate:d(),description:Q(d()),mimeType:Q(d()),_meta:Q(Oe({}))}),Ii=Ei.extend({method:O("resources/list")}),N0=xi.extend({resources:I(M0)}),vu=Ei.extend({method:O("resources/templates/list")}),L0=xi.extend({resourceTemplates:I(c$)}),yu=sr.extend({uri:d()}),l$=yu,wu=It.extend({method:O("resources/read"),params:l$}),q0=Ht.extend({contents:I(ee([O0,A0]))}),j0=or.extend({method:O("notifications/resources/list_changed")}),u$=yu,U0=It.extend({method:O("resources/subscribe"),params:u$}),d$=yu,z0=It.extend({method:O("resources/unsubscribe"),params:d$}),p$=ss.extend({uri:d()}),D0=or.extend({method:O("notifications/resources/updated"),params:p$}),h$=C({name:d(),description:Q(d()),required:Q(ne())}),f$=C({...os.shape,...yo.shape,description:Q(d()),arguments:Q(I(h$)),_meta:Q(Oe({}))}),bu=Ei.extend({method:O("prompts/list")}),Z0=xi.extend({prompts:I(f$)}),m$=sr.extend({name:d(),arguments:ie(d(),d()).optional()}),Su=It.extend({method:O("prompts/get"),params:m$}),V0=C({type:O("text"),text:d(),_meta:ie(d(),he()).optional()}),F0=C({type:O("image"),data:_u,mimeType:d(),_meta:ie(d(),he()).optional()}),H0=C({type:O("audio"),data:_u,mimeType:d(),_meta:ie(d(),he()).optional()}),g$=C({type:O("tool_use"),name:d(),id:d(),input:C({}).passthrough(),_meta:Q(C({}).passthrough())}).passthrough(),_$=C({type:O("resource"),resource:ee([O0,A0]),_meta:ie(d(),he()).optional()}),v$=M0.extend({type:O("resource_link")}),ku=ee([V0,F0,H0,v$,_$]),y$=C({role:we(["user","assistant"]),content:ku}),B0=Ht.extend({description:Q(d()),messages:I(y$)}),J0=or.extend({method:O("notifications/prompts/list_changed")}),w$=C({title:d().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),W0=C({...os.shape,...yo.shape,description:d().optional(),inputSchema:C({type:O("object"),properties:ie(d(),vr).optional(),required:I(d()).optional()}).catchall(he()),outputSchema:C({type:O("object"),properties:ie(d(),vr).optional(),required:I(d()).optional()}).catchall(he()).optional(),annotations:Q(w$),_meta:ie(d(),he()).optional()}),Cu=Ei.extend({method:O("tools/list")}),G0=xi.extend({tools:I(W0)}),Ri=Ht.extend({content:I(ku).default([]),structuredContent:ie(d(),he()).optional(),isError:Q(ne())});Ri.or(Ht.extend({toolResult:he()}));const b$=sr.extend({name:d(),arguments:Q(ie(d(),he()))}),Tu=It.extend({method:O("tools/call"),params:b$}),K0=or.extend({method:O("notifications/tools/list_changed")}),Pi=we(["debug","info","notice","warning","error","critical","alert","emergency"]),S$=sr.extend({level:Pi}),Oi=It.extend({method:O("logging/setLevel"),params:S$}),k$=ss.extend({level:Pi,logger:d().optional(),data:he()}),Y0=or.extend({method:O("notifications/message"),params:k$}),C$=C({name:d().optional()}),T$=C({hints:Q(I(C$)),costPriority:Q(M().min(0).max(1)),speedPriority:Q(M().min(0).max(1)),intelligencePriority:Q(M().min(0).max(1))}),$$=C({mode:Q(we(["auto","required","none"]))}),E$=C({type:O("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:I(ku).default([]),structuredContent:C({}).passthrough().optional(),isError:Q(ne()),_meta:Q(C({}).passthrough())}).passthrough(),Ai=Xe("type",[V0,F0,H0,g$,E$]),x$=C({role:we(["user","assistant"]),content:ee([Ai,I(Ai)]),_meta:Q(C({}).passthrough())}).passthrough(),I$=sr.extend({messages:I(x$),modelPreferences:T$.optional(),systemPrompt:d().optional(),includeContext:we(["none","thisServer","allServers"]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:I(d()).optional(),metadata:vr.optional(),tools:Q(I(W0)),toolChoice:Q($$)}),Q0=It.extend({method:O("sampling/createMessage"),params:I$}),X0=Ht.extend({model:d(),stopReason:Q(we(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:we(["user","assistant"]),content:ee([Ai,I(Ai)])}),R$=C({type:O("boolean"),title:d().optional(),description:d().optional(),default:ne().optional()}),P$=C({type:O("string"),title:d().optional(),description:d().optional(),minLength:M().optional(),maxLength:M().optional(),format:we(["email","uri","date","date-time"]).optional(),default:d().optional()}),O$=C({type:we(["number","integer"]),title:d().optional(),description:d().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),A$=C({type:O("string"),title:d().optional(),description:d().optional(),enum:I(d()),default:d().optional()}),M$=C({type:O("string"),title:d().optional(),description:d().optional(),oneOf:I(C({const:d(),title:d()})),default:d().optional()}),N$=C({type:O("string"),title:d().optional(),description:d().optional(),enum:I(d()),enumNames:I(d()).optional(),default:d().optional()}),L$=ee([A$,M$]),q$=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:M().optional(),maxItems:M().optional(),items:C({type:O("string"),enum:I(d())}),default:I(d()).optional()}),j$=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:M().optional(),maxItems:M().optional(),items:C({anyOf:I(C({const:d(),title:d()}))}),default:I(d()).optional()}),U$=ee([q$,j$]),z$=ee([N$,L$,U$]),D$=ee([z$,R$,P$,O$]),Z$=sr.extend({mode:O("form").optional(),message:d(),requestedSchema:C({type:O("object"),properties:ie(d(),D$),required:I(d()).optional()})}),V$=sr.extend({mode:O("url"),message:d(),elicitationId:d(),url:d().url()}),F$=ee([Z$,V$]),$u=It.extend({method:O("elicitation/create"),params:F$}),H$=ss.extend({elicitationId:d()}),B$=or.extend({method:O("notifications/elicitation/complete"),params:H$}),Mi=Ht.extend({action:we(["accept","decline","cancel"]),content:ie(d(),ee([d(),M(),ne(),I(d())])).optional()}),J$=C({type:O("ref/resource"),uri:d()}),W$=C({type:O("ref/prompt"),name:d()}),G$=sr.extend({ref:ee([W$,J$]),argument:C({name:d(),value:d()}),context:C({arguments:ie(d(),d()).optional()}).optional()}),Eu=It.extend({method:O("completion/complete"),params:G$});function K$(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Y$(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const e2=Ht.extend({completion:Oe({values:I(d()).max(100),total:Q(M().int()),hasMore:Q(ne())})}),Q$=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ie(d(),he()).optional()}),t2=It.extend({method:O("roots/list")}),r2=Ht.extend({roots:I(Q$)}),n2=or.extend({method:O("notifications/roots/list_changed")});ee([mu,I0,Eu,Oi,Su,bu,Ii,vu,wu,U0,z0,Tu,Cu]),ee([hu,gu,fu,n2]),ee([xn,X0,Mi,r2]),ee([mu,Q0,$u,t2]),ee([hu,gu,Y0,D0,j0,K0,J0,B$]),ee([xn,R0,e2,B0,Z0,N0,L0,q0,Ri,G0]);class Ne extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Me.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new X$(s.elicitations,r)}return new Ne(e,r,n)}}class X$ extends Ne{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Me.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}}function e5(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function s2(t,e){var r,n,s;return nr(t)?Wc(t,{target:e5(e?.target),io:(r=e?.pipeStrategy)!==null&&r!==void 0?r:"input"}):k6(t,{strictUnions:(n=e?.strictUnions)!==null&&n!==void 0?n:!0,pipeStrategy:(s=e?.pipeStrategy)!==null&&s!==void 0?s:"input"})}function o2(t){const e=go(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=y0(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function a2(t,e){const r=Ci(t,e);if(!r.success)throw r.error;return r.data}const t5=6e4;class i2{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(hu,r=>{const n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(gu,r=>{this._onprogress(r)}),this.setRequestHandler(mu,r=>({}))}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ne.fromError(Me.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,s;this._transport=e;const o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};const a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{a?.(c),this._onerror(c)};const i=(s=this._transport)===null||s===void 0?void 0:s.onmessage;this._transport.onmessage=(c,l)=>{i?.(c,l),pu(c)||KT(c)?this._onresponse(c):C0(c)?this._onrequest(c,l):GT(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const n=Ne.fromError(Me.ConnectionClosed,"Connection closed");for(const s of r.values())s(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var n,s;const o=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,a=this._transport;if(o===void 0){a?.send({jsonrpc:"2.0",id:e.id,error:{code:Me.MethodNotFound,message:"Method not found"}}).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:a?.sessionId,_meta:(s=e.params)===null||s===void 0?void 0:s._meta,sendNotification:l=>this.notification(l,{relatedRequestId:e.id}),sendRequest:(l,u,h)=>this.request(l,u,{...h,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>o(e,c)).then(l=>{if(!i.signal.aborted)return a?.send({result:l,jsonrpc:"2.0",id:e.id})},l=>{var u;if(!i.signal.aborted)return a?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Me.InternalError,message:(u=l.message)!==null&&u!==void 0?u:"Internal error",...l.data!==void 0&&{data:l.data}}})}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){a(c);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),pu(e))n(e);else{const s=Ne.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}=n??{};return new Promise((i,c)=>{var l,u,h,f,p,m;if(!this._transport){c(new Error("Not connected"));return}((l=this._options)===null||l===void 0?void 0:l.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=n?.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,_={...e,jsonrpc:"2.0",id:v};n?.onprogress&&(this._progressHandlers.set(v,n.onprogress),_.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:v}});const w=b=>{var S;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`))),c(b)};this._responseHandlers.set(v,b=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(b instanceof Error)return c(b);try{const k=Ci(r,b.result);k.success?i(k.data):c(k.error)}catch(k){c(k)}}}),(f=n?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var b;w((b=n?.signal)===null||b===void 0?void 0:b.reason)});const g=(p=n?.timeout)!==null&&p!==void 0?p:t5,y=()=>w(Ne.fromError(Me.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(v,g,n?.maxTotalTimeout,y,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(_,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(v),c(b)})})}async notification(e,r){var n,s;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((s=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&s!==void 0?s:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const l={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(l,r).catch(u=>this._onerror(u))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const n=o2(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=a2(e,s);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=o2(e);this._notificationHandlers.set(n,s=>{const o=a2(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function c2(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function l2(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];c2(a)&&c2(o)?r[s]={...a,...o}:r[s]=o}return r}function r5(){const t=new Jh.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return t0(t),t}class u2{constructor(e){this._ajv=e??r5()}getValidator(e){var r;const n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return s=>n(s)?{valid:!0,data:s,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class n5 extends i2{constructor(e,r){var n,s;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Pi.options.map((o,a)=>[o,a])),this.isMessageIgnored=(o,a)=>{const i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new u2,this.setRequestHandler(I0,o=>this._oninitialize(o)),this.setNotificationHandler(fu,()=>{var o;return(o=this.oninitialized)===null||o===void 0?void 0:o.call(this)}),this._capabilities.logging&&this.setRequestHandler(Oi,async(o,a)=>{var i;const c=a.sessionId||((i=a.requestInfo)===null||i===void 0?void 0:i.headers["mcp-session-id"])||void 0,{level:l}=o.params,u=Pi.safeParse(l);return u.success&&this._loggingLevels.set(c,u.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=l2(this._capabilities,e)}assertCapabilityForMethod(e){var r,n,s;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((s=this._clientCapabilities)===null||s===void 0)&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){var r,n;switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break}}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:w0.includes(r)?r:vo,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"},xn)}async createMessage(e,r){var n,s;if((e.tools||e.toolChoice)&&!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||s===void 0)&&s.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const o=e.messages[e.messages.length-1],a=Array.isArray(o.content)?o.content:[o.content],i=a.some(h=>h.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(h=>h.type==="tool_use");if(i){if(a.some(h=>h.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){const h=new Set(l.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(a.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(h.size!==f.size||![...h].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.request({method:"sampling/createMessage",params:e},X0,r)}async elicitInput(e,r){var n,s,o,a,i;switch((n=e.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((o=(s=this._clientCapabilities)===null||s===void 0?void 0:s.elicitation)===null||o===void 0)&&o.url))throw new Error("Client does not support url elicitation.");const l=e;return this.request({method:"elicitation/create",params:l},Mi,r)}case"form":{if(!(!((i=(a=this._clientCapabilities)===null||a===void 0?void 0:a.elicitation)===null||i===void 0)&&i.form))throw new Error("Client does not support form elicitation.");const l=e.mode==="form"?e:{...e,mode:"form"},u=await this.request({method:"elicitation/create",params:l},Mi,r);if(u.action==="accept"&&u.content&&l.requestedSchema)try{const f=this._jsonSchemaValidator.getValidator(l.requestedSchema)(u.content);if(!f.valid)throw new Ne(Me.InvalidParams,`Elicitation response content does not match requested schema: ${f.errorMessage}`)}catch(h){throw h instanceof Ne?h:new Ne(Me.InternalError,`Error validating elicitation response: ${h instanceof Error?h.message:String(h)}`)}return u}}}createElicitationCompletionNotifier(e,r){var n,s;if(!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||s===void 0)&&s.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},r2,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const xu=Symbol.for("mcp.completable");function s5(t,e){return Object.defineProperty(t,xu,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function o5(t){return!!t&&typeof t=="object"&&xu in t}function a5(t){const e=t[xu];return e?.complete}var d2;(function(t){t.Completable="McpCompletable"})(d2||(d2={}));const p2=1e6,Iu=1e6,h2=1e4,i5=1e6;class Lr{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){Lr.validateLength(e,p2,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const a=e.indexOf("}",s);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>h2)throw new Error(`Template contains too many expressions (max ${h2})`);const i=e.slice(s+1,a),c=this.getOperator(i),l=i.includes("*"),u=this.getNames(i),h=u[0];for(const f of u)Lr.validateLength(f,Iu,"Variable name");r.push({name:h,operator:c,names:u,exploded:l}),s=a+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return Lr.validateLength(e,Iu,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const a=e.names.map(c=>{const l=r[c];if(l===void 0)return"";const u=Array.isArray(l)?l.map(h=>this.encodeValue(h,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){const a=e.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[e.name];if(n===void 0)return"";const o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const o of e.names)Lr.validateLength(o,Iu,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){const a=e.names[o],i=o===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const s=e.name;switch(e.operator){case"":n=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){Lr.validateLength(e,p2,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const c=this.partToRegExp(i);for(const{pattern:l,name:u}of c)r+=l,n.push({name:u,exploded:i.exploded})}r+="$",Lr.validateLength(r,i5,"Generated regex pattern");const s=new RegExp(r),o=e.match(s);if(!o)return null;const a={};for(let i=0;i<n.length;i++){const{name:c,exploded:l}=n[i],u=o[i+1],h=c.replace("*","");l&&u.includes(",")?a[h]=u.split(","):a[h]=u}return a}}const c5=/^[A-Za-z0-9._-]{1,128}$/;function l5(t){const e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!c5.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function u5(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function f2(t){const e=l5(t);return u5(t,e.warnings),e.isValid}class m2{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new n5(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(nn(Cu)),this.server.assertCanSetRequestHandler(nn(Tu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Cu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const n={name:e,title:r.title,description:r.description,inputSchema:(()=>{const s=_o(r.inputSchema);return s?s2(s,{strictUnions:!0,pipeStrategy:"input"}):p5})(),annotations:r.annotations,_meta:r._meta};if(r.outputSchema){const s=_o(r.outputSchema);s&&(n.outputSchema=s2(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Tu,async(e,r)=>{const n=this._registeredTools[e.params.name];let s;try{if(!n)throw new Ne(Me.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Ne(Me.InvalidParams,`Tool ${e.params.name} disabled`);if(n.inputSchema){const o=n.callback,a=_o(n.inputSchema),i=a??n.inputSchema,c=await uu(i,e.params.arguments);if(!c.success)throw new Ne(Me.InvalidParams,`Input validation error: Invalid arguments for tool ${e.params.name}: ${du(c.error)}`);const l=c.data;s=await Promise.resolve(o(l,r))}else{const o=n.callback;s=await Promise.resolve(o(r))}if(n.outputSchema&&!s.isError){if(!s.structuredContent)throw new Ne(Me.InvalidParams,`Output validation error: Tool ${e.params.name} has an output schema but no structured content was provided`);const o=_o(n.outputSchema),a=await uu(o,s.structuredContent);if(!a.success)throw new Ne(Me.InvalidParams,`Output validation error: Invalid structured content for tool ${e.params.name}: ${du(a.error)}`)}}catch(o){if(o instanceof Ne&&o.code===Me.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}return s}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(nn(Eu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Eu,async e=>{switch(e.params.ref.type){case"ref/prompt":return K$(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Y$(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ne(Me.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new Ne(Me.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Ne(Me.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return wo;const s=go(n.argsSchema),o=s?.[e.params.argument.name];if(!o5(o))return wo;const a=a5(o);if(!a)return wo;const i=await a(e.params.argument.value,e.params.context);return _2(i)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return wo;throw new Ne(Me.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return wo;const o=await s(e.params.argument.value,e.params.context);return _2(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(nn(Ii)),this.server.assertCanSetRequestHandler(nn(vu)),this.server.assertCanSetRequestHandler(nn(wu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ii,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),s=[];for(const o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;const a=await o.resourceTemplate.listCallback(r);for(const i of a.resources)s.push({...o.metadata,...i})}return{resources:[...n,...s]}}),this.server.setRequestHandler(vu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(wu,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new Ne(Me.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const o of Object.values(this._registeredResourceTemplates)){const a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new Ne(Me.InvalidParams,`Resource ${n} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(nn(bu)),this.server.assertCanSetRequestHandler(nn(Su)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(bu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?f5(r.argsSchema):void 0}))})),this.server.setRequestHandler(Su,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new Ne(Me.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Ne(Me.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=_o(n.argsSchema),o=await uu(s,e.params.arguments);if(!o.success)throw new Ne(Me.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${du(o.error)}`);const a=o.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const s=n.callback;return await Promise.resolve(s(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());const o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const a=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){const a={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,s,o){const a={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.template<"u"&&(a.resourceTemplate=i.template),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._registeredResourceTemplates[e]=a,a}_createRegisteredPrompt(e,r,n,s,o){const a={title:r,description:n,argsSchema:s===void 0?void 0:mo(s),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=mo(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,a}_createRegisteredTool(e,r,n,s,o,a,i,c){f2(e);const l={title:r,description:n,inputSchema:g2(s),outputSchema:g2(o),annotations:a,_meta:i,callback:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(typeof u.name=="string"&&f2(u.name),delete this._registeredTools[e],u.name&&(this._registeredTools[u.name]=l)),typeof u.title<"u"&&(l.title=u.title),typeof u.description<"u"&&(l.description=u.description),typeof u.paramsSchema<"u"&&(l.inputSchema=mo(u.paramsSchema)),typeof u.callback<"u"&&(l.callback=u.callback),typeof u.annotations<"u"&&(l.annotations=u.annotations),typeof u._meta<"u"&&(l._meta=u._meta),typeof u.enabled<"u"&&(l.enabled=u.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const c=r[0];Ru(c)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ru(r[0])&&(a=r.shift())):typeof c=="object"&&c!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,n,s,o,a,void 0,i)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:o,inputSchema:a,outputSchema:i,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,s,o,a,i,c,l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());const o=r[0],a=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:o,argsSchema:a}=r,i=this._createRegisteredPrompt(e,s,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class d5{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Lr(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var r;return(r=this._callbacks.complete)===null||r===void 0?void 0:r[e]}}const p5={type:"object",properties:{}};function Ru(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(h5)}function h5(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function g2(t){if(t)return Ru(t)?mo(t):t}function f5(t){const e=go(t);return e?Object.entries(e).map(([r,n])=>{const s=BT(n),o=JT(n);return{name:r,description:s,required:!o}}):[]}function nn(t){const e=go(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=y0(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function _2(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const wo={completion:{values:[],hasMore:!1}};function m5(t){var e;return t.title!==void 0&&t.title!==""?t.title:!((e=t.annotations)===null||e===void 0)&&e.title?t.annotations.title:t.name}class bo{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new bo,r=new bo;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r?.authInfo}})}}class g5{constructor(e,r){const n={name:"web-mcp-server",version:"1.0.0"},s={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new m2(e||n,r||{capabilities:s}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=o=>{this.onerror?.(o)},this.server.server.setRequestHandler(Oi,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new au(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,n){return this.server.registerTool(e,r,n)}registerPrompt(e,r,n){return this.server.registerPrompt(e,r,n)}registerResource(e,r,n,s){return typeof r=="string"?this.server.registerResource(e,r,n,s):this.server.registerResource(e,r,n,s)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,n){return this.server.server.request(e,r,n)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(U0,e)}onUnsubscribe(e){this.server.server.setRequestHandler(z0,e)}onSetLogLevel(e){this.server.server.setRequestHandler(Oi,e)}onListResources(e){this.server.server.setRequestHandler(Ii,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(n2,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const _5=(t,e)=>new au(t,e),v5=()=>ET(),y5=t=>t instanceof au,w5=t=>t instanceof m2;function Ni(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Ni(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)Ni(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)Ni(r,e)}}function b5(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class v2 extends i2{constructor(e,r){var n,s;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new u2}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=l2(this._capabilities,e)}setRequestHandler(e,r){var n,s,o;const a=go(e),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let c;if(nr(i)){const u=i,h=(n=u._zod)===null||n===void 0?void 0:n.def;c=(s=h?.value)!==null&&s!==void 0?s:u.value}else{const u=i,h=u._def;c=(o=h?.value)!==null&&o!==void 0?o:u.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="elicitation/create"){const u=async(h,f)=>{var p,m,v;const _=Ci($u,h);if(!_.success){const P=_.error instanceof Error?_.error.message:String(_.error);throw new Ne(Me.InvalidParams,`Invalid elicitation request: ${P}`)}const{params:w}=_.data,g=(p=w.mode)!==null&&p!==void 0?p:"form",{supportsFormMode:y,supportsUrlMode:b}=b5(this._capabilities.elicitation);if(g==="form"&&!y)throw new Ne(Me.InvalidParams,"Client does not support form-mode elicitation requests");if(g==="url"&&!b)throw new Ne(Me.InvalidParams,"Client does not support URL-mode elicitation requests");const S=await Promise.resolve(r(h,f)),k=Ci(Mi,S);if(!k.success){const P=k.error instanceof Error?k.error.message:String(k.error);throw new Ne(Me.InvalidParams,`Invalid elicitation result: ${P}`)}const T=k.data,x=g==="form"?w.requestedSchema:void 0;if(g==="form"&&T.action==="accept"&&T.content&&x&&!((v=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||v===void 0)&&v.applyDefaults)try{Ni(x,T.content)}catch{}return T};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:vo,capabilities:this._capabilities,clientInfo:this._clientInfo}},R0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!w0.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,s,o,a;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},xn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},e2,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},xn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},B0,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Z0,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},N0,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},L0,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},q0,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},xn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},xn,r)}async callTool(e,r=Ri,n){const s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new Ne(Me.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new Ne(Me.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof Ne?a:new Ne(Me.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema){const n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},G0,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function Pu(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function y2(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Pu(e.headers),...Pu(n.headers)}:e.headers};return t(r,s)}:t}const ut=em().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:nl.custom,message:"URL must be parseable",fatal:!0}),jc}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),S5=Oe({resource:d().url(),authorization_servers:I(ut).optional(),jwks_uri:d().url().optional(),scopes_supported:I(d()).optional(),bearer_methods_supported:I(d()).optional(),resource_signing_alg_values_supported:I(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:ne().optional(),authorization_details_types_supported:I(d()).optional(),dpop_signing_alg_values_supported:I(d()).optional(),dpop_bound_access_tokens_required:ne().optional()}),w2=Oe({issuer:d(),authorization_endpoint:ut,token_endpoint:ut,registration_endpoint:ut.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),service_documentation:ut.optional(),revocation_endpoint:ut.optional(),revocation_endpoint_auth_methods_supported:I(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:I(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:I(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:I(d()).optional(),code_challenge_methods_supported:I(d()).optional(),client_id_metadata_document_supported:ne().optional()}),k5=Oe({issuer:d(),authorization_endpoint:ut,token_endpoint:ut,userinfo_endpoint:ut.optional(),jwks_uri:ut,registration_endpoint:ut.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),acr_values_supported:I(d()).optional(),subject_types_supported:I(d()),id_token_signing_alg_values_supported:I(d()),id_token_encryption_alg_values_supported:I(d()).optional(),id_token_encryption_enc_values_supported:I(d()).optional(),userinfo_signing_alg_values_supported:I(d()).optional(),userinfo_encryption_alg_values_supported:I(d()).optional(),userinfo_encryption_enc_values_supported:I(d()).optional(),request_object_signing_alg_values_supported:I(d()).optional(),request_object_encryption_alg_values_supported:I(d()).optional(),request_object_encryption_enc_values_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),display_values_supported:I(d()).optional(),claim_types_supported:I(d()).optional(),claims_supported:I(d()).optional(),service_documentation:d().optional(),claims_locales_supported:I(d()).optional(),ui_locales_supported:I(d()).optional(),claims_parameter_supported:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:ut.optional(),op_tos_uri:ut.optional(),client_id_metadata_document_supported:ne().optional()}),C5=C({...k5.shape,...w2.pick({code_challenge_methods_supported:!0}).shape}),b2=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:M().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),T5=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),S2=ut.optional().or(O("").transform(()=>{})),$5=C({redirect_uris:I(ut),token_endpoint_auth_method:d().optional(),grant_types:I(d()).optional(),response_types:I(d()).optional(),client_name:d().optional(),client_uri:ut.optional(),logo_uri:S2,scope:d().optional(),contacts:I(d()).optional(),tos_uri:S2,policy_uri:d().optional(),jwks_uri:ut.optional(),jwks:mt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),E5=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),x5=$5.merge(E5);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function I5(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function R5({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}class dt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Ou extends dt{}Ou.errorCode="invalid_request";let Li=class extends dt{};Li.errorCode="invalid_client";let qi=class extends dt{};qi.errorCode="invalid_grant";let ji=class extends dt{};ji.errorCode="unauthorized_client";class Au extends dt{}Au.errorCode="unsupported_grant_type";class Mu extends dt{}Mu.errorCode="invalid_scope";class Nu extends dt{}Nu.errorCode="access_denied";let as=class extends dt{};as.errorCode="server_error";class Lu extends dt{}Lu.errorCode="temporarily_unavailable";class qu extends dt{}qu.errorCode="unsupported_response_type";class ju extends dt{}ju.errorCode="unsupported_token_type";class Uu extends dt{}Uu.errorCode="invalid_token";class zu extends dt{}zu.errorCode="method_not_allowed";class Du extends dt{}Du.errorCode="too_many_requests";class Ui extends dt{}Ui.errorCode="invalid_client_metadata";class Zu extends dt{}Zu.errorCode="insufficient_scope";const P5={[Ou.errorCode]:Ou,[Li.errorCode]:Li,[qi.errorCode]:qi,[ji.errorCode]:ji,[Au.errorCode]:Au,[Mu.errorCode]:Mu,[Nu.errorCode]:Nu,[as.errorCode]:as,[Lu.errorCode]:Lu,[qu.errorCode]:qu,[ju.errorCode]:ju,[Uu.errorCode]:Uu,[zu.errorCode]:zu,[Du.errorCode]:Du,[Ui.errorCode]:Ui,[Zu.errorCode]:Zu};let ar=class extends Error{constructor(e){super(e??"Unauthorized")}};function O5(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const Vu="code",Fu="S256";function k2(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&O5(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function C2(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":A5(s,o,r);return;case"client_secret_post":M5(s,o,n);return;case"none":N5(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function A5(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function M5(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function N5(t,e){e.set("client_id",t)}async function Hu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=T5.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=P5[s]||as;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new as(s)}}async function In(t,e){var r,n;try{return await Bu(t,e)}catch(s){if(s instanceof Li||s instanceof ji)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Bu(t,e);if(s instanceof qi)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await Bu(t,e);throw s}}async function Bu(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){var a,i;let c,l;try{c=await j5(e,{resourceMetadataUrl:s},o),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}l||(l=new URL("/",e));const u=await q5(e,t,c),h=await V5(l,{fetchFn:o});let f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const w=h?.client_id_metadata_document_supported===!0,g=t.clientMetadataUrl;if(g&&!L5(g))throw new Ui(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${g}`);if(w&&g)f={client_id:g},await((a=t.saveClientInformation)===null||a===void 0?void 0:a.call(t,f));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await J5(l,{metadata:h,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(b),f=b}}if(r!==void 0){const w=await t.codeVerifier(),g=await H5(l,{metadata:h,clientInformation:f,authorizationCode:r,codeVerifier:w,redirectUri:t.redirectUrl,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}const p=await t.tokens();if(p?.refresh_token)try{const w=await B5(l,{metadata:h,clientInformation:f,refreshToken:p.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof dt)||w instanceof as))throw w}const m=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:_}=await F5(l,{metadata:h,clientInformation:f,state:m,redirectUrl:t.redirectUrl,scope:n||((i=c?.scopes_supported)===null||i===void 0?void 0:i.join(" "))||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(_),await t.redirectToAuthorization(v),"REDIRECT"}function L5(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function q5(t,e,r){const n=I5(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!R5({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 zi(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=Ju(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=Ju(t,"scope")||void 0,i=Ju(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function Ju(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}async function j5(t,e,r=fetch){const n=await D5(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return S5.parse(await n.json())}async function Wu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Wu(t,void 0,r):void 0;throw n}}function U5(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function T2(t,e,r=fetch){return await Wu(t,{"MCP-Protocol-Version":e},r)}function z5(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function D5(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!==null&&s!==void 0?s:vo;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const u=U5(e,a.pathname);c=new URL(u,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:a),c.search=a.search}let l=await T2(c,i,r);if(!n?.metadataUrl&&z5(l,a.pathname)){const u=new URL(`/.well-known/${e}`,a);l=await T2(u,i,r)}return l}function Z5(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function V5(t,{fetchFn:e=fetch,protocolVersion:r=vo}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=Z5(t);for(const{url:o,type:a}of s){const i=await Wu(o,n,e);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?w2.parse(await i.json()):C5.parse(await i.json())}}}async function F5(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Vu))throw new Error(`Incompatible auth server: does not support response type ${Vu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Fu))throw new Error(`Incompatible auth server: does not support code challenge method ${Fu}`)}else i=new URL("/authorize",t);const c=await Dl(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",Vu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Fu),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}async function H5(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:c}){var l;const u="authorization_code",h=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(f,p,t,e);else{const v=(l=e?.token_endpoint_auth_methods_supported)!==null&&l!==void 0?l:[],_=k2(r,v);C2(_,r,f,p)}a&&p.set("resource",a.href);const m=await(c??fetch)(h,{method:"POST",headers:f,body:p});if(!m.ok)throw await Hu(m);return b2.parse(await m.json())}async function B5(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const c="refresh_token";let l;if(e){if(l=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(u,h,t,e);else{const p=(i=e?.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],m=k2(r,p);C2(m,r,u,h)}s&&h.set("resource",s.href);const f=await(a??fetch)(l,{method:"POST",headers:u,body:h});if(!f.ok)throw await Hu(f);return b2.parse({refresh_token:n,...await f.json()})}async function J5(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Hu(o);return x5.parse(await o.json())}class W5 extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class Gu{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=y2(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new ar("No auth provider");let r;try{r=await In(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new ar;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;const s=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,a)=>{this._eventSource=new uo(this._url.href,{...this._eventSourceInit,fetch:async(i,c)=>{const l=await this._commonHeaders();l.set("Accept","text/event-stream");const u=await s(i,{...c,headers:l});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:f}=zi(u);this._resourceMetadataUrl=h,this._scope=f}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var c;if(i.code===401&&this._authProvider){this._authThenStart().then(o,a);return}const l=new W5(i.code,i.message,i);a(l),(c=this.onerror)===null||c===void 0||c.call(this,l)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var c;const l=i;try{if(this._endpoint=new URL(l.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(c=this.onerror)===null||c===void 0||c.call(this,u),this.close();return}o()}),this._eventSource.onmessage=i=>{var c,l;const u=i;let h;try{h=rn.parse(JSON.parse(u.data))}catch(f){(c=this.onerror)===null||c===void 0||c.call(this,f);return}(l=this.onmessage)===null||l===void 0||l.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new ar("No auth provider");if(await In(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,s;if(!this._endpoint)throw new Error("Not connected");try{const o=await this._commonHeaders();o.set("content-type","application/json");const a={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!i.ok){if(i.status===401&&this._authProvider){const{resourceMetadataUrl:l,scope:u}=zi(i);if(this._resourceMetadataUrl=l,this._scope=u,await In(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar;return this.send(e)}const c=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${c}`)}}catch(o){throw(s=this.onerror)===null||s===void 0||s.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}}const G5={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class So extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Di{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=y2(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:G5}async _authThenStart(){var e;if(!this._authProvider)throw new ar("No auth provider");let r;try{r=await In(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new ar;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(r.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Pu((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,s;const{resumptionToken:o}=e;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new So(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){var n;const s=this._reconnectionOptions.maxRetries;if(s>0&&r>=s){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1;(async()=>{var l,u,h,f;try{const p=e.pipeThrough(new TextDecoderStream).pipeThrough(new En({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){const{value:v,done:_}=await p.read();if(_)break;if(v.id&&(a=v.id,i=!0,s?.(v.id)),!v.event||v.event==="message")try{const w=rn.parse(JSON.parse(v.data));o!==void 0&&pu(w)&&(w.id=o),(l=this.onmessage)===null||l===void 0||l.call(this,w)}catch(w){(u=this.onerror)===null||u===void 0||u.call(this,w)}}(n||i)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(p){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${p}`)),(n||i)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(v){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${v instanceof Error?v.message:String(v)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ar("No auth provider");if(await In(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,s,o,a;try{const{resumptionToken:i,onresumptiontoken:c}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:C0(e)?e.id:void 0}).catch(_=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,_)});return}const l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},h=await((s=this._fetch)!==null&&s!==void 0?s:fetch)(this._url,u),f=h.headers.get("mcp-session-id");if(f&&(this._sessionId=f),!h.ok){if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new So(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:w,scope:g}=zi(h);if(this._resourceMetadataUrl=w,this._scope=g,await In(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar;return this._hasCompletedAuthFlow=!0,this.send(e)}if(h.status===403&&this._authProvider){const{resourceMetadataUrl:w,scope:g,error:y}=zi(h);if(y==="insufficient_scope"){const b=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===b)throw new So(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),w&&(this._resourceMetadataUrl=w),this._lastUpscopingHeader=b??void 0,await In(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar;return this.send(e)}}const _=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${_}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){s$(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(_=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,_)});return}const m=(Array.isArray(e)?e:[e]).filter(_=>"method"in _&&"id"in _&&_.id!==void 0).length>0,v=h.headers.get("content-type");if(m)if(v?.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:c},!1);else if(v?.includes("application/json")){const _=await h.json(),w=Array.isArray(_)?_.map(g=>rn.parse(g)):[rn.parse(_)];for(const g of w)(o=this.onmessage)===null||o===void 0||o.call(this,g)}else throw new So(-1,`Unexpected content type: ${v}`)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{const s=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:s,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(!a.ok&&a.status!==405)throw new So(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}const K5="mcp";class Y5{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,K5),this._socket.onerror=n=>{var s;const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),(s=this.onerror)===null||s===void 0||s.call(this,o)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var s,o;let a;try{a=rn.parse(JSON.parse(n.data))}catch(i){(s=this.onerror)===null||s===void 0||s.call(this,i);return}(o=this.onmessage)===null||o===void 0||o.call(this,a)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,n)=>{var s;if(!this._socket){n(new Error("Not connected"));return}(s=this._socket)===null||s===void 0||s.send(JSON.stringify(e)),r()})}}class $2{constructor(e,r){const n={name:"web-mcp-client",version:"1.0.0"},s={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new v2(e||n,r||{capabilities:s}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=o=>{this.onerror?.(o)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:s,type:o,agent:a,onError:i}=e;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:s};let h;return await(async()=>{const{transport:p,sessionId:m}=o==="sse"?await DT(u):o==="socket"?await VT(u):await ZT(u);p.onerror=async v=>{i?.(v)},h={transport:p,sessionId:m}})(),h}const c=new URL(r);let l;if(o==="channel"&&(l=new ou(r),await this.client.connect(l)),o==="sse"){const u=g0(n,s);l=new Gu(c,u),await this.client.connect(l)}if(o==="socket"&&(l=new Y5(new URL(`${r}?sessionId=${s}&token=${n}`)),l.sessionId=s,await this.client.connect(l)),typeof l>"u"){const u=_0(n,s);l=new Di(c,u),await this.client.connect(l)}return this.transport=l,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,Ri,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,n){return this.client.request(e,r,n)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler($u,e)}onCreateMessage(e){this.client.setRequestHandler(Q0,e)}onListRoots(e){this.client.setRequestHandler(t2,e)}onToolListChanged(e){this.client.setNotificationHandler(K0,e)}onPromptListChanged(e){this.client.setNotificationHandler(J0,e)}onResourceListChanged(e){this.client.setNotificationHandler(j0,e)}onResourceUpdated(e){this.client.setNotificationHandler(D0,e)}onLoggingMessage(e){this.client.setNotificationHandler(Y0,e)}async onPagehide(e){e.persisted||(E2(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const Q5=(t,e)=>new Gu(t,e),X5=(t,e)=>new Di(t,e),eE=(t,e)=>new ou(t,e),tE=t=>t instanceof Gu,E2=t=>t instanceof Di,rE=t=>t instanceof ou,nE=t=>t instanceof v2,is=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},x2=(t,e,r)=>{const n=async function(s){s.source===window&&s.data.type===t&&s.data.direction===r&&await e(s.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Ku=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(s=>{chrome.tabs.sendMessage(s.id,{type:t,data:e,direction:r,tabId:s.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},Yu=(t,e,r,n)=>{const s=(o,a,i)=>{if(o.type===t&&o.direction===r&&(!n||n&&o.tabId===n)){const{data:c}=o;e(c,a,i),i(a)}};return chrome.runtime.onMessage.addListener(s),()=>chrome.runtime.onMessage.removeListener(s)};class I2{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=Yu("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=rn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const s=n.tabIds[n.tabIds.length-1];Ku("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:s,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const R2=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class sE{constructor(e=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||R2(),this._messageListener1=x2("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=x2("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=rn.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&is("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),is("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&e.result?.content&&is("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{is("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class oE{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||R2(),this.tabId=r,Yu("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Yu("mcp-client-to-server",e=>{if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const r=rn.parse(e.mcpMessage);this.onmessage?.(r),e.mcpMessage.params?.name&&is("update-page-app-message",{status:"run",message:e.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),Ku("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&e.result?.content&&is("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,Ku("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var cs={},Qu,P2;function aE(){return P2||(P2=1,Qu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Qu}var Xu={},sn={},O2;function Rn(){if(O2)return sn;O2=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return sn.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},sn.getSymbolTotalCodewords=function(n){return e[n]},sn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},sn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},sn.isKanjiModeEnabled=function(){return typeof t<"u"},sn.toSJIS=function(n){return t(n)},sn}var ed={},A2;function td(){return A2||(A2=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,s){if(t.isValid(n))return n;try{return e(n)}catch{return s}}})(ed)),ed}var rd,M2;function iE(){if(M2)return rd;M2=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},rd=t,rd}var nd,N2;function cE(){if(N2)return nd;N2=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,s){const o=e*this.size+r;this.data[o]=n,s&&(this.reservedBit[o]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},nd=t,nd}var sd={},L2;function lE(){return L2||(L2=1,(function(t){const e=Rn().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const s=Math.floor(n/7)+2,o=e(n),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,i=[o-7];for(let c=1;c<s-1;c++)i[c]=i[c-1]-a;return i.push(6),i.reverse()},t.getPositions=function(n){const s=[],o=t.getRowColCoords(n),a=o.length;for(let i=0;i<a;i++)for(let c=0;c<a;c++)i===0&&c===0||i===0&&c===a-1||i===a-1&&c===0||s.push([o[i],o[c]]);return s}})(sd)),sd}var od={},q2;function uE(){if(q2)return od;q2=1;const t=Rn().getSymbolSize,e=7;return od.getPositions=function(n){const s=t(n);return[[0,0],[s-e,0],[0,s-e]]},od}var ad={},j2;function dE(){return j2||(j2=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let a=0,i=0,c=0,l=null,u=null;for(let h=0;h<o;h++){i=c=0,l=u=null;for(let f=0;f<o;f++){let p=s.get(h,f);p===l?i++:(i>=5&&(a+=e.N1+(i-5)),l=p,i=1),p=s.get(f,h),p===u?c++:(c>=5&&(a+=e.N1+(c-5)),u=p,c=1)}i>=5&&(a+=e.N1+(i-5)),c>=5&&(a+=e.N1+(c-5))}return a},t.getPenaltyN2=function(s){const o=s.size;let a=0;for(let i=0;i<o-1;i++)for(let c=0;c<o-1;c++){const l=s.get(i,c)+s.get(i,c+1)+s.get(i+1,c)+s.get(i+1,c+1);(l===4||l===0)&&a++}return a*e.N2},t.getPenaltyN3=function(s){const o=s.size;let a=0,i=0,c=0;for(let l=0;l<o;l++){i=c=0;for(let u=0;u<o;u++)i=i<<1&2047|s.get(l,u),u>=10&&(i===1488||i===93)&&a++,c=c<<1&2047|s.get(u,l),u>=10&&(c===1488||c===93)&&a++}return a*e.N3},t.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let c=0;c<a;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function r(n,s,o){switch(n){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(s,o){const a=o.size;for(let i=0;i<a;i++)for(let c=0;c<a;c++)o.isReserved(c,i)||o.xor(c,i,r(s,c,i))},t.getBestMask=function(s,o){const a=Object.keys(t.Patterns).length;let i=0,c=1/0;for(let l=0;l<a;l++){o(l),t.applyMask(l,s);const u=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(l,s),u<c&&(c=u,i=l)}return i}})(ad)),ad}var Zi={},U2;function z2(){if(U2)return Zi;U2=1;const t=td(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Zi.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},Zi.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return r[(s-1)*4+0];case t.M:return r[(s-1)*4+1];case t.Q:return r[(s-1)*4+2];case t.H:return r[(s-1)*4+3];default:return}},Zi}var id={},ko={},D2;function pE(){if(D2)return ko;D2=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let s=0;s<255;s++)t[s]=n,e[n]=s,n<<=1,n&256&&(n^=285);for(let s=255;s<512;s++)t[s]=t[s-255]})(),ko.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},ko.exp=function(n){return t[n]},ko.mul=function(n,s){return n===0||s===0?0:t[e[n]+e[s]]},ko}var Z2;function hE(){return Z2||(Z2=1,(function(t){const e=pE();t.mul=function(n,s){const o=new Uint8Array(n.length+s.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<s.length;i++)o[a+i]^=e.mul(n[a],s[i]);return o},t.mod=function(n,s){let o=new Uint8Array(n);for(;o.length-s.length>=0;){const a=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],a);let i=0;for(;i<o.length&&o[i]===0;)i++;o=o.slice(i)}return o},t.generateECPolynomial=function(n){let s=new Uint8Array([1]);for(let o=0;o<n;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})(id)),id}var cd,V2;function fE(){if(V2)return cd;V2=1;const t=hE();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const s=new Uint8Array(n.length+this.degree);s.set(n);const o=t.mod(s,this.genPoly),a=this.degree-o.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(o,a),i}return o},cd=e,cd}var ld={},ud={},dd={},F2;function H2(){return F2||(F2=1,dd.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),dd}var yr={},B2;function J2(){if(B2)return yr;B2=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
44
|
-
]))+`;
|
|
45
|
-
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},
|
|
46
|
-
Suggested mode is: `+e.toString(b));switch(
|
|
43
|
+
`&&n++}}return[e,r]}class i0 extends Event{constructor(e,r){var n,s;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(s=r?.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(c0(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(c0(this),r)}}function E6(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function ul(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(ul).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${ul(t.cause)}`:t.message:`${t}`}function c0(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var l0=t=>{throw TypeError(t)},dl=(t,e,r)=>e.has(t)||l0("Cannot "+r),Ie=(t,e,r)=>(dl(t,e,"read from private field"),r?r.call(t):e.get(t)),et=(t,e,r)=>e.has(t)?l0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,n)=>(dl(t,e,"write to private field"),e.set(t,r),r),Tr=(t,e,r)=>(dl(t,e,"access private method"),r),Ct,mn,Un,Ga,Ka,Ks,Zn,Ys,Vr,Fn,Vn,Hn,Qs,Yt,pl,fl,hl,u0,ml,gl,Xs,yl,_l;class Ya extends EventTarget{constructor(e,r){var n,s;super(),et(this,Yt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,et(this,Ct),et(this,mn),et(this,Un),et(this,Ga),et(this,Ka),et(this,Ks),et(this,Zn),et(this,Ys,null),et(this,Vr),et(this,Fn),et(this,Vn,null),et(this,Hn,null),et(this,Qs,null),et(this,fl,async o=>{var a;Ie(this,Fn).reset();const{body:i,redirected:c,status:l,headers:u}=o;if(l===204){Tr(this,Yt,Xs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?We(this,Un,new URL(o.url)):We(this,Un,void 0),l!==200){Tr(this,Yt,Xs).call(this,`Non-200 status code (${l})`,l);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Tr(this,Yt,Xs).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(Ie(this,Ct)===this.CLOSED)return;We(this,Ct,this.OPEN);const p=new Event("open");if((a=Ie(this,Qs))==null||a.call(this,p),this.dispatchEvent(p),typeof i!="object"||!i||!("getReader"in i)){Tr(this,Yt,Xs).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const h=new TextDecoder,d=i.getReader();let f=!0;do{const{done:v,value:y}=await d.read();y&&Ie(this,Fn).feed(h.decode(y,{stream:!v})),v&&(f=!1,Ie(this,Fn).reset(),Tr(this,Yt,yl).call(this))}while(f)}),et(this,hl,o=>{We(this,Vr,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Tr(this,Yt,yl).call(this,ul(o))}),et(this,ml,o=>{typeof o.id=="string"&&We(this,Ys,o.id);const a=new MessageEvent(o.event||"message",{data:o.data,origin:Ie(this,Un)?Ie(this,Un).origin:Ie(this,mn).origin,lastEventId:o.id||""});Ie(this,Hn)&&(!o.event||o.event==="message")&&Ie(this,Hn).call(this,a),this.dispatchEvent(a)}),et(this,gl,o=>{We(this,Ks,o)}),et(this,_l,()=>{We(this,Zn,void 0),Ie(this,Ct)===this.CONNECTING&&Tr(this,Yt,pl).call(this)});try{if(e instanceof URL)We(this,mn,e);else if(typeof e=="string")We(this,mn,new URL(e,x6()));else throw new Error("Invalid URL")}catch{throw E6("An invalid or illegal string was specified")}We(this,Fn,a0({onEvent:Ie(this,ml),onRetry:Ie(this,gl)})),We(this,Ct,this.CONNECTING),We(this,Ks,3e3),We(this,Ka,(n=r?.fetch)!=null?n:globalThis.fetch),We(this,Ga,(s=r?.withCredentials)!=null?s:!1),Tr(this,Yt,pl).call(this)}get readyState(){return Ie(this,Ct)}get url(){return Ie(this,mn).href}get withCredentials(){return Ie(this,Ga)}get onerror(){return Ie(this,Vn)}set onerror(e){We(this,Vn,e)}get onmessage(){return Ie(this,Hn)}set onmessage(e){We(this,Hn,e)}get onopen(){return Ie(this,Qs)}set onopen(e){We(this,Qs,e)}addEventListener(e,r,n){const s=r;super.addEventListener(e,s,n)}removeEventListener(e,r,n){const s=r;super.removeEventListener(e,s,n)}close(){Ie(this,Zn)&&clearTimeout(Ie(this,Zn)),Ie(this,Ct)!==this.CLOSED&&(Ie(this,Vr)&&Ie(this,Vr).abort(),We(this,Ct,this.CLOSED),We(this,Vr,void 0))}}Ct=new WeakMap,mn=new WeakMap,Un=new WeakMap,Ga=new WeakMap,Ka=new WeakMap,Ks=new WeakMap,Zn=new WeakMap,Ys=new WeakMap,Vr=new WeakMap,Fn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Qs=new WeakMap,Yt=new WeakSet,pl=function(){We(this,Ct,this.CONNECTING),We(this,Vr,new AbortController),Ie(this,Ka)(Ie(this,mn),Tr(this,Yt,u0).call(this)).then(Ie(this,fl)).catch(Ie(this,hl))},fl=new WeakMap,hl=new WeakMap,u0=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ie(this,Ys)?{"Last-Event-ID":Ie(this,Ys)}:void 0},cache:"no-store",signal:(t=Ie(this,Vr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},ml=new WeakMap,gl=new WeakMap,Xs=function(t,e){var r;Ie(this,Ct)!==this.CLOSED&&We(this,Ct,this.CLOSED);const n=new i0("error",{code:e,message:t});(r=Ie(this,Vn))==null||r.call(this,n),this.dispatchEvent(n)},yl=function(t,e){var r;if(Ie(this,Ct)===this.CLOSED)return;We(this,Ct,this.CONNECTING);const n=new i0("error",{code:e,message:t});(r=Ie(this,Vn))==null||r.call(this,n),this.dispatchEvent(n),We(this,Zn,setTimeout(Ie(this,_l),Ie(this,Ks)))},_l=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function x6(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Qa(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function d0(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Qa(e.headers),...Qa(n.headers)}:e.headers};return t(r,s)}:t}let vl;vl=globalThis.crypto;async function I6(t){return(await vl).getRandomValues(new Uint8Array(t))}async function R6(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await I6(t-n.length);for(const o of s)o<r&&(n+=e[o%e.length])}return n}async function P6(t){return await R6(t)}async function O6(t){const e=await(await vl).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function p0(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await P6(t),r=await O6(e);return{code_verifier:e,code_challenge:r}}const it=S9().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:ih.custom,message:"URL must be parseable",fatal:!0}),sf}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),A6=Ke({resource:m().url(),authorization_servers:M(it).optional(),jwks_uri:m().url().optional(),scopes_supported:M(m()).optional(),bearer_methods_supported:M(m()).optional(),resource_signing_alg_values_supported:M(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:M(m()).optional(),dpop_signing_alg_values_supported:M(m()).optional(),dpop_bound_access_tokens_required:me().optional()}),f0=Ke({issuer:m(),authorization_endpoint:it,token_endpoint:it,registration_endpoint:it.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),response_modes_supported:M(m()).optional(),grant_types_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional(),service_documentation:it.optional(),revocation_endpoint:it.optional(),revocation_endpoint_auth_methods_supported:M(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:M(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:M(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:M(m()).optional(),code_challenge_methods_supported:M(m()).optional(),client_id_metadata_document_supported:me().optional()}),M6=Ke({issuer:m(),authorization_endpoint:it,token_endpoint:it,userinfo_endpoint:it.optional(),jwks_uri:it,registration_endpoint:it.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),response_modes_supported:M(m()).optional(),grant_types_supported:M(m()).optional(),acr_values_supported:M(m()).optional(),subject_types_supported:M(m()),id_token_signing_alg_values_supported:M(m()),id_token_encryption_alg_values_supported:M(m()).optional(),id_token_encryption_enc_values_supported:M(m()).optional(),userinfo_signing_alg_values_supported:M(m()).optional(),userinfo_encryption_alg_values_supported:M(m()).optional(),userinfo_encryption_enc_values_supported:M(m()).optional(),request_object_signing_alg_values_supported:M(m()).optional(),request_object_encryption_alg_values_supported:M(m()).optional(),request_object_encryption_enc_values_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional(),display_values_supported:M(m()).optional(),claim_types_supported:M(m()).optional(),claims_supported:M(m()).optional(),service_documentation:m().optional(),claims_locales_supported:M(m()).optional(),ui_locales_supported:M(m()).optional(),claims_parameter_supported:me().optional(),request_parameter_supported:me().optional(),request_uri_parameter_supported:me().optional(),require_request_uri_registration:me().optional(),op_policy_uri:it.optional(),op_tos_uri:it.optional(),client_id_metadata_document_supported:me().optional()}),N6=T({...M6.shape,...f0.pick({code_challenge_methods_supported:!0}).shape}),L6=T({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:ch().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),j6=T({error:m(),error_description:m().optional(),error_uri:m().optional()}),h0=it.optional().or(L("").transform(()=>{})),q6=T({redirect_uris:M(it),token_endpoint_auth_method:m().optional(),grant_types:M(m()).optional(),response_types:M(m()).optional(),client_name:m().optional(),client_uri:it.optional(),logo_uri:h0,scope:m().optional(),contacts:M(m()).optional(),tos_uri:h0,policy_uri:m().optional(),jwks_uri:it.optional(),jwks:ht().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),z6=T({client_id:m(),client_secret:m().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),D6=q6.merge(z6);T({error:m(),error_description:m().optional()}).strip(),T({token:m(),token_type_hint:m().optional()}).strip();function U6(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Z6({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}class tt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class wl extends tt{}wl.errorCode="invalid_request";let Xa=class extends tt{};Xa.errorCode="invalid_client";let ei=class extends tt{};ei.errorCode="invalid_grant";let ti=class extends tt{};ti.errorCode="unauthorized_client";class bl extends tt{}bl.errorCode="unsupported_grant_type";class kl extends tt{}kl.errorCode="invalid_scope";class Sl extends tt{}Sl.errorCode="access_denied";let Bn=class extends tt{};Bn.errorCode="server_error";class Cl extends tt{}Cl.errorCode="temporarily_unavailable";class Tl extends tt{}Tl.errorCode="unsupported_response_type";class $l extends tt{}$l.errorCode="unsupported_token_type";class El extends tt{}El.errorCode="invalid_token";class xl extends tt{}xl.errorCode="method_not_allowed";class Il extends tt{}Il.errorCode="too_many_requests";class ri extends tt{}ri.errorCode="invalid_client_metadata";class Rl extends tt{}Rl.errorCode="insufficient_scope";class Pl extends tt{}Pl.errorCode="invalid_target";const F6={[wl.errorCode]:wl,[Xa.errorCode]:Xa,[ei.errorCode]:ei,[ti.errorCode]:ti,[bl.errorCode]:bl,[kl.errorCode]:kl,[Sl.errorCode]:Sl,[Bn.errorCode]:Bn,[Cl.errorCode]:Cl,[Tl.errorCode]:Tl,[$l.errorCode]:$l,[El.errorCode]:El,[xl.errorCode]:xl,[Il.errorCode]:Il,[ri.errorCode]:ri,[Rl.errorCode]:Rl,[Pl.errorCode]:Pl};let zt=class extends Error{constructor(e){super(e??"Unauthorized")}};function V6(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const Ol="code",Al="S256";function H6(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&V6(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function B6(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":J6(s,o,r);return;case"client_secret_post":W6(s,o,n);return;case"none":G6(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function J6(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function W6(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function G6(t,e){e.set("client_id",t)}async function m0(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=j6.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=F6[s]||Bn;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Bn(s)}}async function gn(t,e){try{return await Ml(t,e)}catch(r){if(r instanceof Xa||r instanceof ti)return await t.invalidateCredentials?.("all"),await Ml(t,e);if(r instanceof ei)return await t.invalidateCredentials?.("tokens"),await Ml(t,e);throw r}}async function Ml(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await Q6(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",e));const c=await Y6(e,t,a),l=await nS(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const y=l?.client_id_metadata_document_supported===!0,w=t.clientMetadataUrl;if(w&&!K6(w))throw new ri(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await t.saveClientInformation?.(u);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const _=await cS(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(_),u=_}}const p=!t.redirectUrl;if(r!==void 0||p){const y=await iS(t,i,{metadata:l,resource:c,authorizationCode:r,fetchFn:o});return await t.saveTokens(y),"AUTHORIZED"}const h=await t.tokens();if(h?.refresh_token)try{const y=await aS(i,{metadata:l,clientInformation:u,refreshToken:h.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof tt)||y instanceof Bn))throw y}const d=t.state?await t.state():void 0,{authorizationUrl:f,codeVerifier:v}=await sS(i,{metadata:l,clientInformation:u,state:d,redirectUrl:t.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(v),await t.redirectToAuthorization(f),"REDIRECT"}function K6(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Y6(t,e,r){const n=U6(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Z6({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function ni(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=Nl(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=Nl(t,"scope")||void 0,i=Nl(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function Nl(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}async function Q6(t,e,r=fetch){const n=await tS(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return A6.parse(await n.json())}async function Ll(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Ll(t,void 0,r):void 0;throw n}}function X6(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function g0(t,e,r=fetch){return await Ll(t,{"MCP-Protocol-Version":e},r)}function eS(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function tS(t,e,r,n){const s=new URL(t),o=n?.protocolVersion??zs;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const c=X6(e,s.pathname);a=new URL(c,n?.metadataServerUrl??s),a.search=s.search}let i=await g0(a,o,r);if(!n?.metadataUrl&&eS(i,s.pathname)){const c=new URL(`/.well-known/${e}`,s);i=await g0(c,o,r)}return i}function rS(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function nS(t,{fetchFn:e=fetch,protocolVersion:r=zs}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=rS(t);for(const{url:o,type:a}of s){const i=await Ll(o,n,e);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?f0.parse(await i.json()):N6.parse(await i.json())}}}async function sS(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Ol))throw new Error(`Incompatible auth server: does not support response type ${Ol}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Al))throw new Error(`Incompatible auth server: does not support code challenge method ${Al}`)}else i=new URL("/authorize",t);const c=await p0(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",Ol),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Al),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}function oS(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function y0(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:a}){const i=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),s)await s(c,r,i,e);else if(n){const u=e?.token_endpoint_auth_methods_supported??[],p=H6(n,u);B6(p,n,c,r)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!l.ok)throw await m0(l);return L6.parse(await l.json())}async function aS(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await y0(t,{metadata:e,tokenRequestParams:i,clientInformation:r,addClientAuthentication:o,resource:s,fetchFn:a});return{refresh_token:n,...c}}async function iS(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:o}={}){const a=t.clientMetadata.scope;let i;if(t.prepareTokenRequest&&(i=await t.prepareTokenRequest(a)),!i){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const l=await t.codeVerifier();i=oS(s,l,t.redirectUrl)}const c=await t.clientInformation();return y0(e,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function cS(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await m0(o);return D6.parse(await o.json())}class lS extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class eo{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=d0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let e;try{e=await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zt;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=Qa(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await e(s,{...o,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:c,scope:l}=ni(i);this._resourceMetadataUrl=c,this._scope=l}return i}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{if(s.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const o=new lS(s.code,s.message,s);n(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{const o=s;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=s=>{const o=s;let a;try{a=Cr.parse(JSON.parse(o.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new zt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._endpoint,n);if(!s.ok){const o=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=ni(s);if(this._resourceMetadataUrl=a,this._scope=i,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}await s.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}}class Jn extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(o){s=a0({onEvent:a=>{o.enqueue(a)},onError(a){e==="terminate"?o.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}const uS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Wn extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class to{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=d0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??uS}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let e;try{e=await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=Qa(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){const{resumptionToken:r}=e;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const s=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!s.ok){if(await s.body?.cancel(),s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Wn(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1,c=!1;(async()=>{try{const u=e.pipeThrough(new TextDecoderStream).pipeThrough(new Jn({onRetry:d=>{this._serverRetryMs=d}})).getReader();for(;;){const{value:d,done:f}=await u.read();if(f)break;if(d.id&&(a=d.id,i=!0,s?.(d.id)),!!d.data&&(!d.event||d.event==="message"))try{const v=Cr.parse(JSON.parse(d.data));Us(v)&&(c=!0,o!==void 0&&(v.id=o)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(d){this.onerror?.(new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{const{resumptionToken:n,onresumptiontoken:s}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:$c(e)?e.id:void 0}).catch(h=>this.onerror?.(h));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const h=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Wn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:d,scope:f}=ni(i);if(this._resourceMetadataUrl=d,this._scope=f,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:d,scope:f,error:v}=ni(i);if(v==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Wn(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),d&&(this._resourceMetadataUrl=d),this._lastUpscopingHeader=y??void 0,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(e)}}throw new Wn(i.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),$4(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}const u=(Array.isArray(e)?e:[e]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,p=i.headers.get("content-type");if(u)if(p?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:s},!1);else if(p?.includes("application/json")){const h=await i.json(),d=Array.isArray(h)?h.map(f=>Cr.parse(f)):[Cr.parse(h)];for(const f of d)this.onmessage?.(f)}else throw await i.body?.cancel(),new Wn(-1,`Unexpected content type: ${p}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Wn(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}const dS="mcp";class _0{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,dS),this._socket.onerror=n=>{const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),this.onerror?.(s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let s;try{s=Cr.parse(JSON.parse(n.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(s)}})}async close(){this._socket?.close()}send(e){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),r()})}}const Hr=Pt;(function(t,e){const r=Pt,n=Pt,s=t();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(si,-118057+3521*-35+-2099*-233);const v0=()=>{const t=Pt,e=Pt,r={};r[t(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[e(394)]=e(414),r.ktWqD=function(a,i){return a!==i},r[t(424)]=t(391);const n=r,s=n[e(420)].split("|");let o=859*2+-3*-1039+-4835*1;for(;;){switch(s[o++]){case"0":if(n[e(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[e(405)](typeof global,"undefined"))return global;continue;case"3":if(n[e(405)](typeof globalThis,n[t(394)]))return globalThis;continue;case"4":return Function(n[t(424)])()}break}},pS=(t,e,r)=>{const n=Pt,s=Pt,o={};o.eOzBp=function(i,c){return i!==c},o.ooaJk="undefined",o[n(402)]=function(i,c){return i===c},o[n(421)]="function";const a=o;a[s(389)](typeof window,a.ooaJk)?t[s(423)](e,"*",r):n(423)in t&&a.pTvSc(typeof t[s(423)],a[n(421)])&&t.postMessage(e,r)},fS=(t,e)=>{const r=Pt,n=Pt,s={};s.nTCfA=function(a,i){return a in i},s[r(390)]="addEventListener",s[r(385)]=function(a,i){return a===i},s[r(409)]="function",s.VaHpd=n(392),s[n(384)]=r(417),s.FPOYW=function(a,i){return a!==i};const o=s;o.nTCfA(o.ogKey,t)&&o[n(385)](typeof t.addEventListener,o[n(409)])?t[n(386)](o.VaHpd,e):o[n(384)]in t&&o[r(398)](typeof t[n(417)],r(414))&&(t.onmessage=e)};class ro{constructor(e){this._port=e}async[Hr(401)](){const e=Hr,r=Hr;this[e(422)]&&(this[r(422)].onmessage=n=>{var s,o;const a=e;try{const i=Cr.parse(n.data.message);(s=this.onmessage)==null||s.call(this,i,n[a(412)][a(428)])}catch(i){const c=new Error("MessageChannel failed to parse message: "+i);(o=this[a(383)])==null||o.call(this,c)}},this._port.onmessageerror=n=>{var s;const o=r,a=new Error("MessageChannel transport error: "+JSON[o(415)](n));(s=this.onerror)==null||s.call(this,a)},this[r(422)].start())}async send(e,r){const n={EoBZE:function(s){return s()},leEiG:function(s,o){return s instanceof o},cDUwk:function(s,o){return s(o)}};return new Promise((s,o)=>{var a;const i=Pt,c=Pt;try{const l={};l[i(404)]=r?.[i(404)];const u={};u[i(392)]=e,u.extra=l,this._port&&this._port[c(423)](u),n[i(399)](s)}catch(l){const u=n.leEiG(l,Error)?l:new Error(n.cDUwk(String,l));(a=this.onerror)==null||a.call(this,u),o(u)}})}async close(){var e,r;const n=Hr,s=Hr;(e=this._port)==null||e[n(393)](),this[n(422)]=void 0,(r=this[s(408)])==null||r.call(this)}}class jl extends ro{constructor(e,r=v0()){const n=Hr,s={lSpBh:function(a,i,c,l){return a(i,c,l)}};super(),this._endpoint=e,this._globalObject=r;const o=new MessageChannel;this._port=o[n(410)],s[n(418)](pS,this._globalObject,{endpoint:this[n(397)]},[o[n(429)]])}}class ql extends ro{constructor(e,r=v0()){const n=Hr,s=Hr,o={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,c){return a(i,c)}};super(),this[n(397)]=e,this[s(388)]=r,this[s(416)]=new Promise(a=>{const i=n,c={XlglK:function(l,u){return o.HITdC(l,u)},pXlad:function(l){return o.QdDxM(l)}};o[i(427)](fS,this._globalObject,l=>{const u=i,p=i;l[u(412)]&&c.XlglK(l.data[p(396)],this._endpoint)&&(this[u(422)]=l[p(430)][-3036+-1518*-2],c.pXlad(a))})})}async listen(){return this._listen}}function si(){const t=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return si=function(){return t},si()}function Pt(t,e){const r=si();return Pt=function(n,s){return n=n-(17227+1*-16844),r[n]},Pt(t,e)}const hS=()=>{const t=new MessageChannel;return[new ro(t.port1),new ro(t.port2)]};(function(t,e){const r=Fe,n=Fe,s=t();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(oi,-411935*1+228107+208149*2);const mS=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[s(475)]=s(411),a.SoCaE="resources/templates/list",a[o(484)]="resources/read",a[s(461)]="prompts/get",a.srIIC=o(477),a[o(436)]=o(478),a[o(442)]=s(437),a.dEmVs=s(465);const i=a,{id:c,method:l,params:u}=r;let p={};switch(l){case i.VRyiJ:p=await e.listTools(u);break;case i.VkPYu:p=await e.callTool(u);break;case i.fgMSD:p=await e.listResources(u);break;case i[o(466)]:p=await e.listResourceTemplates(u);break;case i.sthgI:p=await e[s(455)](u);break;case o(486):p=await e.subscribeResource(u);break;case s(410):p=await e.unsubscribeResource(u);break;case i[o(461)]:p=await e[o(414)](u);break;case i[s(412)]:p=await e[s(491)](u);break;case i[s(436)]:p=await e[s(478)]();break;case i.kkNqg:p=await e.complete(u);break;case s(464):p=await e.setLoggingLevel(u?.[o(443)]);break}const h={};h.result=p,h.jsonrpc=i[o(472)],h.id=c,await((n=t?.[o(488)])==null?void 0:n[s(460)](h))},gS=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a[s(487)]=o(462),a.ypHTC="ping",a.fPExS=s(465);const i=a,{id:c,method:l,params:u}=r;let p={};switch(l){case"roots/list":const d={};d.method=l,d[o(446)]=u,p=await e[s(469)](d,rl);break;case"sampling/createMessage":const f={};f[s(481)]=l,f[s(446)]=u,p=await e.request(f,Ha);break;case i[s(487)]:const v={};v.method=l,v[o(446)]=u,p=await e.request(v,Js);break;case i.ypHTC:const y={};y.method=l,p=await e.request(y,Fr);break}const h={};return h.result=p,h.jsonrpc=i.fPExS,h.id=c,await((n=t?.transport)==null?void 0:n.send(h)),p};function Fe(t,e){const r=oi();return Fe=function(n,s){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Fe(t,e)}const yS=(t,e)=>{const r=Fe,n=Fe,s={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,c,l){return a(i,c,l)},yfZbw:"2.0"},o=t._onrequest;t[n(463)]=async(a,i)=>{var c,l,u,p,h;const d=n,f=r,{id:v,method:y}=a;try{s[d(451)](y,s.DhPFX)?await o.call(t,a,i):await s[f(474)](mS,t,e,a)}catch(w){const{code:g,message:_,data:b}=w;try{if(g){const k={};k[f(485)]=g,k[d(422)]=_,k.data=b;const S={};S[f(448)]=k,S.jsonrpc=s[d(417)],S.id=v,await((c=t?.transport)==null?void 0:c[f(460)](S))}else(u=(l=t?.transport)==null?void 0:l.onerror)==null||u.call(l,w)}catch(k){(h=(p=t?.transport)==null?void 0:p.onerror)==null||h.call(p,k)}}}},_S=(t,e)=>{const r=Fe,n=Fe,s={};s[r(476)]=r(439),s[r(431)]=function(a,i){return a!==i},s.UPdQt="notifications/cancelled";const o=s;t[r(421)]=async a=>{var i,c;const l=r,u=n,{method:p,params:h}=a;if(p!==o[l(476)]&&(o.QWYMz(p,o.UPdQt)||h?.[u(490)]))try{await e[l(445)](a)}catch(d){(c=(i=t?.[l(488)])==null?void 0:i[l(480)])==null||c.call(i,d)}}},vS=(t,e)=>async r=>{var n,s,o,a,i;const c=Fe,l=Fe,u={TJhyV:function(p,h,d,f){return p(h,d,f)},MMNTY:c(465)};try{return await u.TJhyV(gS,t,e,r)}catch(p){const{code:h,message:d,data:f}=p;try{if(h){const v={};v.code=h,v[c(422)]=d,v[l(419)]=f;const y={};y[c(448)]=v,y[c(424)]=u.MMNTY,y.id=r.id,await((n=t?.transport)==null?void 0:n[l(460)](y))}else(o=(s=t?.transport)==null?void 0:s[c(480)])==null||o.call(s,p)}catch(v){(i=(a=t?.[c(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},wS=(t,e)=>async r=>{var n,s,o;const a=Fe,i=Fe,c={};c.xmcLM=function(h,d){return h!==d},c.xSWLt="notifications/initialized",c[a(420)]=i(453);const l=c,{method:u,params:p}=r;if(l.xmcLM(u,l.xSWLt)&&(l.xmcLM(u,l[i(420)])||p?.[i(490)]))try{const h={...r};h.jsonrpc=a(465),await((n=e?.[a(488)])==null?void 0:n.send(h))}catch(h){(o=(s=t?.transport)==null?void 0:s.onerror)==null||o.call(s,h)}};function oi(){const t=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return oi=function(){return t},oi()}const bS=(t,e)=>async r=>{var n,s,o,a,i,c;const l=Fe,u=Fe,p={};p.kSvAZ=l(465);const h=p;try{await((n=e?.[u(488)])==null?void 0:n[u(460)](r))}catch(d){const{code:f,message:v,data:y}=d;try{if(f){const w={};w.code=f,w.message=v,w.data=y;const g={};g.error=w,g[u(424)]=h.kSvAZ,g.id=r.id,await((s=t?.transport)==null?void 0:s.send(g))}else(a=(o=t?.transport)==null?void 0:o[l(480)])==null||a.call(o,d)}catch(w){(c=(i=t?.[l(488)])==null?void 0:i[u(480)])==null||c.call(i,w)}}},zl=()=>{const t=Fe,e={rgPZO:function(c,l){return c!==l},VWsxO:function(c,l){return c(l)},FjTAY:"function"},r=[],n=(c,l)=>{const u=Fe;if(l){const p=[];for(const h of r)try{p.push(h(c,l))}catch{}for(const h of p)if(e.rgPZO(h,null))return h}else for(const p of r)try{e[u(427)](p,c)}catch{}},s=c=>{const l=Fe,u=Fe;typeof c===e[l(456)]&&!r.includes(c)&&r[u(471)](c)},o=c=>{const l=Fe,u=r[l(415)](c);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const c=Fe;r[c(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[t(447)]=s,i.removeListener=o,i.clearListener=a,i},kS=t=>{const e=Fe,r=Fe,n={UlqiY:function(s){return s()},jsmFN:function(s){return s()}};{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(423)](zl);t._onresponse=s,t[r(438)]=o,t.removeResponseListener=a,t.clearResponseListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(489)](zl);t[e(432)]=s,t[r(473)]=o,t.removeRequestListener=a,t.clearRequestListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n.jsmFN(zl);t.fallbackNotificationHandler=s,t[e(444)]=o,t.removeNotificationListener=a,t[r(426)]=i}},SS=(t,{beforeInit:e,afterInit:r}={})=>{const n=Fe,s=Fe,o={HucXo:function(i,c){return i===c},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,c){return i(c)},UynHf:function(i,c){return i===c},yCyFn:function(i){return i()}},a=new Map(t._notificationHandlers);t[n(454)].clear(),t._notificationHandlers.clear(),o.HucXo(typeof e,o.HicFO)&&o[n(435)](e),o[n(467)](t[n(449)][s(428)],n(449))&&(t[s(413)]=t[s(449)]),o.DclXr(kS,t),t[s(438)](i=>{const c=n;t.originalOnResponse[c(440)](t,i)}),o[n(429)](typeof r,o.HicFO)&&o[s(425)](r),t[s(444)](i=>{const c=s,{method:l}=i,u=a[c(483)](l);o[c(467)](typeof u,"function")&&u(i)})},CS=$r;(function(t,e){const r=$r,n=$r,s=t();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ai,995159+-6*-266138+-1619768);const TS=()=>{const t=$r,e=$r,r={};r.svuxn=function(s,o){return s&o},r.ZUPdr=function(s,o){return s===o},r[t(227)]=function(s,o){return s===o},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[e(227)](typeof crypto,"object")&&crypto[t(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,s=>{const o=t,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[o(225)](s,"x")?a:n[o(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},$S=t=>{const e=$r,r=$r,n=new Uint8Array(t);return crypto[e(221)](n),Array[r(218)](n,s=>s[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[e(213)]("")},Br={};Br[CS(211)]=TS,Br.randomBytes=$S;function $r(t,e){const r=ai();return $r=function(n,s){return n=n-(-7373+7187*1+395),r[n]},$r(t,e)}function ai(){const t=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return ai=function(){return t},ai()}function Er(t,e){const r=ii();return Er=function(n,s){return n=n-(-1483*3+-5564+20*513),r[n]},Er(t,e)}const Qt=Er,no=Er;(function(t,e){const r=Er,n=Er,s=t();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ii,-4*308317+753182*2+658196);const ES=(t,e)=>{const r=Er,n=Er,s={olCWX:function(c,l,u){return c(l,u)},sfXDX:function(c,l,u){return c(l,u)},ksWFu:function(c,l,u){return c(l,u)}};s[r(283)](yS,t,e),_S(t,e);const o=s[n(283)](vS,e,t),a=s[n(294)](bS,e,t),i=s[r(277)](wS,e,t);e.addRequestListener(o),e.addResponseListener(a),e[n(287)](i),t.onclose=()=>{const c=r,l=n;e[c(247)](o),e.removeResponseListener(a),e[l(252)](i)}},Dl=(t,e,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,c){return a(i,c)}},s=()=>{var a;n.QhPqi(r,eo)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Er(295)])==null||i.close()})),n.Qalmc(ES,t,e)},o={};o.afterInit=s,n.Qalmc(SS,e,o)},w0=(t,e=Br[Qt(299)]())=>{const r=Qt,n=Qt,s={RVabx:function(u,p,h){return u(p,h)},crCTs:"include"},o={};o["sse-session-id"]=e;const a=o,i={};i["sse-session-id"]=e;const c={};c.headers=i,c.credentials=s[r(304)];const l={requestInit:c,eventSourceInit:{async fetch(u,p){const h=r,d=r,f=new Headers(p?.[h(268)]||{});Object.entries(a).forEach(([y,w])=>{f.set(y,w)});const v={...p};return v.headers=f,s[d(279)](fetch,u,v)},withCredentials:!0}};return t&&(l[r(280)].headers.Authorization="Bearer "+t,a.Authorization=n(256)+t),l},b0=(t,e=Br[Qt(299)]())=>{const r=no,n=Qt,s={};s[r(271)]="include";const o=s,a={};a["stream-session-id"]=e;const i={};i[n(268)]=a,i.credentials=o[r(271)];const c={};c.requestInit=i;const l=c;return t&&(l[n(280)][r(268)][n(301)]=r(256)+t),l},Ul=async(t,e,r)=>{const n=Qt,s=Qt,o={rRtFD:function(i){return i()},ToRAF:function(i,c){return i instanceof c}},a=o[n(276)](r);try{return await t[s(260)](a),a}catch(i){if(o[n(275)](i,zt)){const c=await e();return await a[n(257)](c),await Ul(t,e,r)}else throw i}},k0=(t,e)=>{const r=no,n=no,s={};s[r(267)]=function(a,i){return a in i},s.timcZ="waitForOAuthCode",s[r(253)]=function(a,i){return a===i},s.ufiEQ=r(285),s[n(250)]=r(293);const o=s;if(o.oGmBG(o[r(258)],t))return t[n(278)];if(o[n(253)](typeof e,o.ufiEQ))return e;throw new Error(o.daYBw)};function ii(){const t=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return ii=function(){return t},ii()}const xS=async t=>{const e=no,r=Qt,n={GKDjq:function(R,j,O){return R(j,O)},JzpWy:e(281),mcbiU:"1.0.0",CfBXU:function(R){return R()},kdowC:function(R,j,O,D){return R(j,O,D)},KkViY:"sessionId"},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,eventSourceInit:u,waitForOAuthCode:p}=t,h={};h[r(305)]=c,h.requestInit=l,h.eventSourceInit=u;const d=h,f=i||Br[r(299)](),v=n[e(289)](w0,a,f);if(l){const R={...v.requestInit,...l};R[r(268)]={...v[r(280)][e(268)],...l.headers},d.requestInit=R}else d.requestInit=v[e(280)];if(u){const R={...v[e(270)],...u};d.eventSourceInit=R}else d.eventSourceInit=v[e(270)];const y={};y[e(254)]=!0;const w={};w.roots=y,w[e(298)]={},w[r(303)]={};const g=w,_={};_.name=n[r(261)],_[e(288)]=n.mcbiU;const b={};b[e(251)]=g;const k=new Gs(_,b),S=()=>new eo(new URL(o),d);let C=n[e(282)](S);if(c){const R=k0(c,p);C=await n[e(263)](Ul,k,R,S)}else await k.connect(C);Dl(k,s,C),C.sessionId=C[r(274)].searchParams[e(297)](n.KkViY);const x={};return x.transport=C,x.sessionId=C[r(286)],x},IS=async t=>{const e=no,r=Qt,n={wfHUn:function(R,j,O){return R(j,O)},tUMle:"mcp-stream-proxy-client",omKPe:e(248),rSiEq:function(R){return R()},PdsSn:function(R,j,O,D){return R(j,O,D)}},{client:s,url:o,token:a,sessionId:i,authProvider:c,requestInit:l,reconnectionOptions:u,waitForOAuthCode:p}=t,h={};h.authProvider=c,h.requestInit=l,h.reconnectionOptions=u;const d=h,f=i||Br.randomUUID(),v=n[r(272)](b0,a,f);if(l){const R={...v[e(280)],...l};R.headers={...v.requestInit[e(268)],...l.headers},d.requestInit=R}else d[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[e(298)]={},w[e(303)]={};const g=w,_={};_.name=n[e(262)],_.version=n.omKPe;const b={};b.capabilities=g;const k=new Gs(_,b),S=()=>new to(new URL(o),d);let C=n.rSiEq(S);if(c){const R=n[e(272)](k0,c,p);C=await n[e(296)](Ul,k,R,S)}else await k[e(260)](C);n.PdsSn(Dl,k,s,C);const x={};return x.transport=C,x[r(286)]=C[r(286)],x},RS=async t=>{const e=Qt,r=Qt,n={eZwNI:function(w,g,_,b){return w(g,_,b)}},{client:s,url:o,token:a,sessionId:i}=t,c={};c[e(254)]=!0;const l={};l[r(290)]=c,l.sampling={},l.elicitation={};const u=l,p={};p.name="mcp-socket-proxy-client",p.version=r(248);const h={};h[r(251)]=u;const d=new Gs(p,h),f=i||Br[r(299)](),v=new _0(new URL(o+"?sessionId="+f+r(265)+a));await d.connect(v),n[e(259)](Dl,d,s,v);const y={};return y.transport=v,y[r(286)]=f,y},Jr=Xt,so=Xt;(function(t,e){const r=Xt,n=Xt,s=t();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ci,1297719+-42747*-22+-1289197);function Xt(t,e){const r=ci();return Xt=function(n,s){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Xt(t,e)}const PS=()=>Br.randomBytes(-8746+-382*-23);class OS{constructor(e){const r=Xt,n=Xt,s={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:o,state:a,redirectCallback:i,getAuthCodeByState:c,waitForOAuthCode:l}=e;this._clientMetadata=o,this[r(206)]=o.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||s.HbwOh(PS),this._redirectCallback=i||this[n(202)],this[n(195)]=c||this[r(191)],this.waitForOAuthCode=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,n,s,o,a,i;const c=Xt,l=Xt,u={};u[c(198)]="GET";const p=await fetch(e,u);!p.ok&&((n=(r=this[l(207)])[l(196)])==null||n.call(r,c(208)+p[l(205)]));const h=await this[l(195)](this._redirectUrl,this[c(197)]);if(!h.ok){(o=(s=this[c(207)]).reject)==null||o.call(s,"Failed to fetch auth code: "+h[l(205)]);return}const d=await h.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,d.code)}async[Jr(191)](e,r){const n=Jr,s={};s.xAOmI="POST";const o=s,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(e,{method:o.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const e=this._callBackPromise;return()=>new Promise((r,n)=>{const s=Xt;e.resolve=r,e[s(196)]=n})}get redirectUrl(){return this[Jr(206)]}get[so(190)](){return this._clientMetadata}[Jr(213)](){return this[Jr(197)]}[so(218)](){return this[so(200)]}[Jr(194)](e){this._clientInformation=e}tokens(){return this[so(210)]}saveTokens(e){const r=so;this[r(210)]=e}redirectToAuthorization(e){this._redirectCallback(e)}saveCodeVerifier(e){this._codeVerifier=e}[Jr(212)](){const e=Jr,r={};r[e(215)]=e(214);const n=r;if(!this[e(209)])throw new Error(n.mMdVl);return this[e(209)]}}function ci(){const t=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return ci=function(){return t},ci()}(function(t,e){for(var r=ui,n=ui,s=t();;)try{var o=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(o===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(li,262*-2438+1346066*-1+2*1373311);function li(){var t=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return li=function(){return t},li()}function ui(t,e){var r=li();return ui=function(n,s){n=n-287;var o=r[n];return o},ui(t,e)}class AS{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}class MS extends Kh{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Za.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{const o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new r0,this.setRequestHandler(mh,n=>this._oninitialize(n)),this.setNotificationHandler(Rc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fa,async(n,s)=>{const o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=Za.safeParse(a);return i.success&&this._loggingLevels.set(o,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new AS(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qh(this._capabilities,e)}setRequestHandler(e,r){const s=Dn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Jt(s)){const i=s;o=i._zod?.def?.value??i.value}else{const i=s;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){const i=async(c,l)=>{const u=Wt(Ua,c);if(!u.success){const f=u.error instanceof Error?u.error.message:String(u.error);throw new re(oe.InvalidParams,`Invalid tools/call request: ${f}`)}const{params:p}=u.data,h=await Promise.resolve(r(c,l));if(p.task){const f=Wt(Ln,h);if(!f.success){const v=f.error instanceof Error?f.error.message:String(f.error);throw new re(oe.InvalidParams,`Invalid task creation result: ${v}`)}return f.data}const d=Wt(qn,h);if(!d.success){const f=d.error instanceof Error?d.error.message:String(d.error);throw new re(oe.InvalidParams,`Invalid tools/call result: ${f}`)}return d.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){s0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&n0(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:lh.includes(r)?r:zs,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fr)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=a?Array.isArray(a.content)?a.content:[a.content]:[],c=i.some(l=>l.type==="tool_use");if(o){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){const l=new Set(i.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Oh,r):this.request({method:"sampling/createMessage",params:e},Ha,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const s=e;return this.request({method:"elicitation/create",params:s},Js,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Js,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!i.valid)throw new re(oe.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof re?a:new re(oe.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},rl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Zl=Symbol.for("mcp.completable");function NS(t,e){return Object.defineProperty(t,Zl,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function S0(t){return!!t&&typeof t=="object"&&Zl in t}function LS(t){return t[Zl]?.complete}var C0;(function(t){t.Completable="McpCompletable"})(C0||(C0={}));const T0=1e6,Fl=1e6,$0=1e4,jS=1e6;class xr{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){xr.validateLength(e,T0,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const a=e.indexOf("}",s);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>$0)throw new Error(`Template contains too many expressions (max ${$0})`);const i=e.slice(s+1,a),c=this.getOperator(i),l=i.includes("*"),u=this.getNames(i),p=u[0];for(const h of u)xr.validateLength(h,Fl,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),s=a+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return xr.validateLength(e,Fl,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const a=e.names.map(c=>{const l=r[c];if(l===void 0)return"";const u=Array.isArray(l)?l.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){const a=e.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[e.name];if(n===void 0)return"";const o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const o of e.names)xr.validateLength(o,Fl,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){const a=e.names[o],i=o===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const s=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){xr.validateLength(e,T0,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const c=this.partToRegExp(i);for(const{pattern:l,name:u}of c)r+=l,n.push({name:u,exploded:i.exploded})}r+="$",xr.validateLength(r,jS,"Generated regex pattern");const s=new RegExp(r),o=e.match(s);if(!o)return null;const a={};for(let i=0;i<n.length;i++){const{name:c,exploded:l}=n[i],u=o[i+1],p=c.replace("*","");l&&u.includes(",")?a[p]=u.split(","):a[p]=u}return a}}const qS=/^[A-Za-z0-9._-]{1,128}$/;function zS(t){const e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!qS.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function DS(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function E0(t){const e=zS(t);return DS(t,e.warnings),e.isValid}class US{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){const s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}class x0{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new MS(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new US(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Wr(Yc)),this.server.assertCanSetRequestHandler(Wr(Ua)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Yc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const n={name:e,title:r.title,description:r.description,inputSchema:(()=>{const s=Ws(r.inputSchema);return s?Jh(s,{strictUnions:!0,pipeStrategy:"input"}):FS})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const s=Ws(r.outputSchema);s&&(n.outputSchema=Jh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ua,async(e,r)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new re(oe.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Tool ${e.params.name} disabled`);const s=!!e.params.task,o=n.execution?.taskSupport,a="createTask"in n.handler;if((o==="required"||o==="optional")&&!a)throw new re(oe.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new re(oe.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&a)return await this.handleAutomaticTaskPolling(n,e,r);const i=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,i,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof re&&n.code===oe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;const o=Ws(e.inputSchema)??e.inputSchema,a=await nl(o,r);if(!a.success){const i="error"in a?a.error:"Unknown error",c=sl(i);throw new re(oe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new re(oe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=Ws(e.outputSchema),o=await nl(s,r.structuredContent);if(!o.success){const a="error"in o?o.error:"Unknown error",i=sl(a);throw new re(oe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(e,r,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(e.inputSchema){const i=s;return await Promise.resolve(i.createTask(r,a))}else{const i=s;return await Promise.resolve(i.createTask(a))}}if(e.inputSchema){const a=s;return await Promise.resolve(a(r,n))}else{const a=s;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,a={...n,taskStore:n.taskStore},i=s?await Promise.resolve(o.createTask(s,a)):await Promise.resolve(o.createTask(a)),c=i.task.taskId;let l=i.task;const u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(h=>setTimeout(h,u));const p=await n.taskStore.getTask(c);if(!p)throw new re(oe.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Wr(tl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(tl,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ck(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Tk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new re(oe.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new re(oe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return oo;const o=Dn(n.argsSchema)?.[e.params.argument.name];if(!S0(o))return oo;const a=LS(o);if(!a)return oo;const i=await a(e.params.argument.value,e.params.context);return P0(i)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return oo;throw new re(oe.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return oo;const o=await s(e.params.argument.value,e.params.context);return P0(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Wr(Da)),this.server.assertCanSetRequestHandler(Wr(Dc)),this.server.assertCanSetRequestHandler(Wr(Zc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Da,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),s=[];for(const o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;const a=await o.resourceTemplate.listCallback(r);for(const i of a.resources)s.push({...o.metadata,...i})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Dc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Zc,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new re(oe.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const o of Object.values(this._registeredResourceTemplates)){const a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new re(oe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Wr(Vc)),this.server.assertCanSetRequestHandler(Wr(Hc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Vc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?HS(r.argsSchema):void 0}))})),this.server.setRequestHandler(Hc,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new re(oe.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new re(oe.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=Ws(n.argsSchema),o=await nl(s,e.params.arguments);if(!o.success){const c="error"in o?o.error:"Unknown error",l=sl(c);throw new re(oe.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}const a=o.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());const o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const a=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){const a={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,s,o){const a={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=a)),typeof l.title<"u"&&(a.title=l.title),typeof l.template<"u"&&(a.resourceTemplate=l.template),typeof l.metadata<"u"&&(a.metadata=l.metadata),typeof l.callback<"u"&&(a.readCallback=l.callback),typeof l.enabled<"u"&&(a.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,n,s,o){const a={title:r,description:n,argsSchema:s===void 0?void 0:zn(s),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=zn(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,s&&Object.values(s).some(c=>{const l=c instanceof Bt?c._def?.innerType:c;return S0(l)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,n,s,o,a,i,c,l){E0(e);const u={title:r,description:n,inputSchema:R0(s),outputSchema:R0(o),annotations:a,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&E0(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=zn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=zn(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const c=r[0];Vl(c)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Vl(r[0])&&(a=r.shift())):typeof c=="object"&&c!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,n,s,o,a,{taskSupport:"forbidden"},void 0,i)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:o,inputSchema:a,outputSchema:i,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,s,o,a,i,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());const o=r[0],a=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:o,argsSchema:a}=r,i=this._createRegisteredPrompt(e,s,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class ZS{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new xr(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}}const FS={type:"object",properties:{}};function I0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function VS(t){return"_def"in t||"_zod"in t||I0(t)}function Vl(t){return typeof t!="object"||t===null||VS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(I0)}function R0(t){if(t)return Vl(t)?zn(t):t}function HS(t){const e=Dn(t);return e?Object.entries(e).map(([r,n])=>{const s=Rk(n),o=Pk(n);return{name:r,description:s,required:!o}}):[]}function Wr(t){const r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=jh(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function P0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const oo={completion:{values:[],hasMore:!1}};function BS(t){return t.title!==void 0&&t.title!==""?t.title:"annotations"in t&&t.annotations?.title?t.annotations.title:t.name}class ao{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new ao,r=new ao;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(;this._messageQueue.length>0;){const e=this._messageQueue.shift();this.onmessage?.(e.message,e.extra)}}async close(){const e=this._otherTransport;this._otherTransport=void 0,await e?.close(),this.onclose?.()}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r?.authInfo}})}}class JS{constructor(e,r){const n={name:"web-mcp-server",version:"1.0.0"},s={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new x0(e||n,r||{capabilities:s}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=o=>{this.onerror?.(o)},this.server.server.setRequestHandler(Fa,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new ql(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,n){return this.server.registerTool(e,r,n)}registerPrompt(e,r,n){return this.server.registerPrompt(e,r,n)}registerResource(e,r,n,s){return typeof r=="string"?this.server.registerResource(e,r,n,s):this.server.registerResource(e,r,n,s)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,n){return this.server.server.request(e,r,n)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(Ch,e)}onUnsubscribe(e){this.server.server.setRequestHandler(Th,e)}onSetLogLevel(e){this.server.server.setRequestHandler(Fa,e)}onListResources(e){this.server.server.setRequestHandler(Da,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(Nh,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const WS=(t,e)=>new ql(t,e),GS=()=>hS(),KS=t=>t instanceof ql,YS=t=>t instanceof x0;class O0{constructor(e,r){const n={name:"web-mcp-client",version:"1.0.0"},s={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Gs(e||n,r||{capabilities:s}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=o=>{this.onerror?.(o)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:s,type:o,agent:a,onError:i}=e;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:s};let p;return await(async()=>{const{transport:d,sessionId:f}=o==="sse"?await xS(u):o==="socket"?await RS(u):await IS(u);d.onerror=async v=>{i?.(v)},p={transport:d,sessionId:f}})(),p}const c=new URL(r);let l;if(o==="channel"&&(l=new jl(r),await this.client.connect(l)),o==="sse"){const u=w0(n,s);l=new eo(c,u),await this.client.connect(l)}if(o==="socket"&&(l=new _0(new URL(`${r}?sessionId=${s}&token=${n}`)),l.sessionId=s,await this.client.connect(l)),typeof l>"u"){const u=b0(n,s);l=new to(c,u),await this.client.connect(l)}return this.transport=l,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,qn,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,n){return this.client.request(e,r,n)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(el,e)}onCreateMessage(e){this.client.setRequestHandler(Xc,e)}onListRoots(e){this.client.setRequestHandler(Mh,e)}onToolListChanged(e){this.client.setNotificationHandler(Qc,e)}onPromptListChanged(e){this.client.setNotificationHandler(Kc,e)}onResourceListChanged(e){this.client.setNotificationHandler(Fc,e)}onResourceUpdated(e){this.client.setNotificationHandler($h,e)}onLoggingMessage(e){this.client.setNotificationHandler(Ph,e)}async onPagehide(e){e.persisted||(A0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const QS=(t,e)=>new eo(t,e),XS=(t,e)=>new to(t,e),e5=(t,e)=>new jl(t,e),t5=t=>t instanceof eo,A0=t=>t instanceof to,r5=t=>t instanceof jl,n5=t=>t instanceof Gs,Gn=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},M0=(t,e,r)=>{const n=async function(s){s.source===window&&s.data.type===t&&s.data.direction===r&&await e(s.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Hl=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(s=>{chrome.tabs.sendMessage(s.id,{type:t,data:e,direction:r,tabId:s.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},Bl=(t,e,r,n)=>{const s=(o,a,i)=>{if(o.type===t&&o.direction===r&&(!n||n&&o.tabId===n)){const{data:c}=o;e(c,a,i),i(a)}};return chrome.runtime.onMessage.addListener(s),()=>chrome.runtime.onMessage.removeListener(s)};class N0{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=Bl("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Cr.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const s=n.tabIds[n.tabIds.length-1];Hl("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:s,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const L0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class s5{constructor(e=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||L0(),this._messageListener1=M0("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.error("【Page Svr Transport】 notifyRegistration失败:",r)})},"content->page"),this._messageListener2=M0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=Cr.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Gn("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Gn("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class o5{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||L0(),this.tabId=r,Bl("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Bl("mcp-client-to-server",e=>{if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const r=Cr.parse(e.mcpMessage);this.onmessage?.(r),e.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:e.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),Hl("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,Hl("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Kn={},Jl,j0;function a5(){return j0||(j0=1,Jl=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Jl}var Wl={},Gr={},q0;function yn(){if(q0)return Gr;q0=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Gr.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},Gr.getSymbolTotalCodewords=function(n){return e[n]},Gr.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Gr.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Gr.isKanjiModeEnabled=function(){return typeof t<"u"},Gr.toSJIS=function(n){return t(n)},Gr}var Gl={},z0;function Kl(){return z0||(z0=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,s){if(t.isValid(n))return n;try{return e(n)}catch{return s}}})(Gl)),Gl}var Yl,D0;function i5(){if(D0)return Yl;D0=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Yl=t,Yl}var Ql,U0;function c5(){if(U0)return Ql;U0=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,s){const o=e*this.size+r;this.data[o]=n,s&&(this.reservedBit[o]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Ql=t,Ql}var Xl={},Z0;function l5(){return Z0||(Z0=1,(function(t){const e=yn().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const s=Math.floor(n/7)+2,o=e(n),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,i=[o-7];for(let c=1;c<s-1;c++)i[c]=i[c-1]-a;return i.push(6),i.reverse()},t.getPositions=function(n){const s=[],o=t.getRowColCoords(n),a=o.length;for(let i=0;i<a;i++)for(let c=0;c<a;c++)i===0&&c===0||i===0&&c===a-1||i===a-1&&c===0||s.push([o[i],o[c]]);return s}})(Xl)),Xl}var eu={},F0;function u5(){if(F0)return eu;F0=1;const t=yn().getSymbolSize,e=7;return eu.getPositions=function(n){const s=t(n);return[[0,0],[s-e,0],[0,s-e]]},eu}var tu={},V0;function d5(){return V0||(V0=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let a=0,i=0,c=0,l=null,u=null;for(let p=0;p<o;p++){i=c=0,l=u=null;for(let h=0;h<o;h++){let d=s.get(p,h);d===l?i++:(i>=5&&(a+=e.N1+(i-5)),l=d,i=1),d=s.get(h,p),d===u?c++:(c>=5&&(a+=e.N1+(c-5)),u=d,c=1)}i>=5&&(a+=e.N1+(i-5)),c>=5&&(a+=e.N1+(c-5))}return a},t.getPenaltyN2=function(s){const o=s.size;let a=0;for(let i=0;i<o-1;i++)for(let c=0;c<o-1;c++){const l=s.get(i,c)+s.get(i,c+1)+s.get(i+1,c)+s.get(i+1,c+1);(l===4||l===0)&&a++}return a*e.N2},t.getPenaltyN3=function(s){const o=s.size;let a=0,i=0,c=0;for(let l=0;l<o;l++){i=c=0;for(let u=0;u<o;u++)i=i<<1&2047|s.get(l,u),u>=10&&(i===1488||i===93)&&a++,c=c<<1&2047|s.get(u,l),u>=10&&(c===1488||c===93)&&a++}return a*e.N3},t.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let c=0;c<a;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function r(n,s,o){switch(n){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(s,o){const a=o.size;for(let i=0;i<a;i++)for(let c=0;c<a;c++)o.isReserved(c,i)||o.xor(c,i,r(s,c,i))},t.getBestMask=function(s,o){const a=Object.keys(t.Patterns).length;let i=0,c=1/0;for(let l=0;l<a;l++){o(l),t.applyMask(l,s);const u=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(l,s),u<c&&(c=u,i=l)}return i}})(tu)),tu}var di={},H0;function B0(){if(H0)return di;H0=1;const t=Kl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return di.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},di.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return r[(s-1)*4+0];case t.M:return r[(s-1)*4+1];case t.Q:return r[(s-1)*4+2];case t.H:return r[(s-1)*4+3];default:return}},di}var ru={},io={},J0;function p5(){if(J0)return io;J0=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let s=0;s<255;s++)t[s]=n,e[n]=s,n<<=1,n&256&&(n^=285);for(let s=255;s<512;s++)t[s]=t[s-255]})(),io.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},io.exp=function(n){return t[n]},io.mul=function(n,s){return n===0||s===0?0:t[e[n]+e[s]]},io}var W0;function f5(){return W0||(W0=1,(function(t){const e=p5();t.mul=function(n,s){const o=new Uint8Array(n.length+s.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<s.length;i++)o[a+i]^=e.mul(n[a],s[i]);return o},t.mod=function(n,s){let o=new Uint8Array(n);for(;o.length-s.length>=0;){const a=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],a);let i=0;for(;i<o.length&&o[i]===0;)i++;o=o.slice(i)}return o},t.generateECPolynomial=function(n){let s=new Uint8Array([1]);for(let o=0;o<n;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})(ru)),ru}var nu,G0;function h5(){if(G0)return nu;G0=1;const t=f5();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const s=new Uint8Array(n.length+this.degree);s.set(n);const o=t.mod(s,this.genPoly),a=this.degree-o.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(o,a),i}return o},nu=e,nu}var su={},ou={},au={},K0;function Y0(){return K0||(K0=1,au.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),au}var ur={},Q0;function X0(){if(Q0)return ur;Q0=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
44
|
+
]))+`;ur.KANJI=new RegExp(r,"g"),ur.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ur.BYTE=new RegExp(n,"g"),ur.NUMERIC=new RegExp(t,"g"),ur.ALPHANUMERIC=new RegExp(e,"g");const s=new RegExp("^"+r+"$"),o=new RegExp("^"+t+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ur.testKanji=function(c){return s.test(c)},ur.testNumeric=function(c){return o.test(c)},ur.testAlphanumeric=function(c){return a.test(c)},ur}var em;function _n(){return em||(em=1,(function(t){const e=Y0(),r=X0();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(o,a){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?o.ccBits[0]:a<27?o.ccBits[1]:o.ccBits[2]},t.getBestModeForData=function(o){return r.testNumeric(o)?t.NUMERIC:r.testAlphanumeric(o)?t.ALPHANUMERIC:r.testKanji(o)?t.KANJI:t.BYTE},t.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},t.isValid=function(o){return o&&o.bit&&o.ccBits};function n(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+s)}}t.from=function(o,a){if(t.isValid(o))return o;try{return n(o)}catch{return a}}})(ou)),ou}var tm;function m5(){return tm||(tm=1,(function(t){const e=yn(),r=B0(),n=Kl(),s=_n(),o=Y0(),a=7973,i=e.getBCHDigit(a);function c(h,d,f){for(let v=1;v<=40;v++)if(d<=t.getCapacity(v,f,h))return v}function l(h,d){return s.getCharCountIndicator(h,d)+4}function u(h,d){let f=0;return h.forEach(function(v){const y=l(v.mode,d);f+=y+v.getBitsLength()}),f}function p(h,d){for(let f=1;f<=40;f++)if(u(h,f)<=t.getCapacity(f,d,s.MIXED))return f}t.from=function(d,f){return o.isValid(d)?parseInt(d,10):f},t.getCapacity=function(d,f,v){if(!o.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=s.BYTE);const y=e.getSymbolTotalCodewords(d),w=r.getTotalCodewordsCount(d,f),g=(y-w)*8;if(v===s.MIXED)return g;const _=g-l(v,d);switch(v){case s.NUMERIC:return Math.floor(_/10*3);case s.ALPHANUMERIC:return Math.floor(_/11*2);case s.KANJI:return Math.floor(_/13);case s.BYTE:default:return Math.floor(_/8)}},t.getBestVersionForData=function(d,f){let v;const y=n.from(f,n.M);if(Array.isArray(d)){if(d.length>1)return p(d,y);if(d.length===0)return 1;v=d[0]}else v=d;return c(v.mode,v.getLength(),y)},t.getEncodedBits=function(d){if(!o.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;e.getBCHDigit(f)-i>=0;)f^=a<<e.getBCHDigit(f)-i;return d<<12|f}})(su)),su}var iu={},rm;function g5(){if(rm)return iu;rm=1;const t=yn(),e=1335,r=21522,n=t.getBCHDigit(e);return iu.getEncodedBits=function(o,a){const i=o.bit<<3|a;let c=i<<10;for(;t.getBCHDigit(c)-n>=0;)c^=e<<t.getBCHDigit(c)-n;return(i<<10|c)^r},iu}var cu={},lu,nm;function y5(){if(nm)return lu;nm=1;const t=_n();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let s,o,a;for(s=0;s+3<=this.data.length;s+=3)o=this.data.substr(s,3),a=parseInt(o,10),n.put(a,10);const i=this.data.length-s;i>0&&(o=this.data.substr(s),a=parseInt(o,10),n.put(a,i*3+1))},lu=e,lu}var uu,sm;function _5(){if(sm)return uu;sm=1;const t=_n(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(s){return 11*Math.floor(s/2)+6*(s%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(s){let o;for(o=0;o+2<=this.data.length;o+=2){let a=e.indexOf(this.data[o])*45;a+=e.indexOf(this.data[o+1]),s.put(a,11)}this.data.length%2&&s.put(e.indexOf(this.data[o]),6)},uu=r,uu}var du,om;function v5(){if(om)return du;om=1;const t=_n();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,s=this.data.length;n<s;n++)r.put(this.data[n],8)},du=e,du}var pu,am;function w5(){if(am)return pu;am=1;const t=_n(),e=yn();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(s){return s*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let s;for(s=0;s<this.data.length;s++){let o=e.toSJIS(this.data[s]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[s]+`
|
|
45
|
+
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},pu=r,pu}var fu={exports:{}},im;function b5(){return im||(im=1,(function(t){var e={single_source_shortest_paths:function(r,n,s){var o={},a={};a[n]=0;var i=e.PriorityQueue.make();i.push(n,0);for(var c,l,u,p,h,d,f,v,y;!i.empty();){c=i.pop(),l=c.value,p=c.cost,h=r[l]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],f=p+d,v=a[u],y=typeof a[u]>"u",(y||v>f)&&(a[u]=f,i.push(u,f),o[u]=l))}if(typeof s<"u"&&typeof a[s]>"u"){var w=["Could not find a path from ",n," to ",s,"."].join("");throw new Error(w)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var s=[],o=n;o;)s.push(o),r[o],o=r[o];return s.reverse(),s},find_path:function(r,n,s){var o=e.single_source_shortest_paths(r,n,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,s={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(s[o]=n[o]);return s.queue=[],s.sorter=r.sorter||n.default_sorter,s},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var s={value:r,cost:n};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(fu)),fu.exports}var cm;function k5(){return cm||(cm=1,(function(t){const e=_n(),r=y5(),n=_5(),s=v5(),o=w5(),a=X0(),i=yn(),c=b5();function l(w){return unescape(encodeURIComponent(w)).length}function u(w,g,_){const b=[];let k;for(;(k=w.exec(_))!==null;)b.push({data:k[0],index:k.index,mode:g,length:k[0].length});return b}function p(w){const g=u(a.NUMERIC,e.NUMERIC,w),_=u(a.ALPHANUMERIC,e.ALPHANUMERIC,w);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,e.BYTE,w),k=u(a.KANJI,e.KANJI,w)):(b=u(a.BYTE_KANJI,e.BYTE,w),k=[]),g.concat(_,b,k).sort(function(C,x){return C.index-x.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.length}})}function h(w,g){switch(g){case e.NUMERIC:return r.getBitsLength(w);case e.ALPHANUMERIC:return n.getBitsLength(w);case e.KANJI:return o.getBitsLength(w);case e.BYTE:return s.getBitsLength(w)}}function d(w){return w.reduce(function(g,_){const b=g.length-1>=0?g[g.length-1]:null;return b&&b.mode===_.mode?(g[g.length-1].data+=_.data,g):(g.push(_),g)},[])}function f(w){const g=[];for(let _=0;_<w.length;_++){const b=w[_];switch(b.mode){case e.NUMERIC:g.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:g.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:g.push([b,{data:b.data,mode:e.BYTE,length:l(b.data)}]);break;case e.BYTE:g.push([{data:b.data,mode:e.BYTE,length:l(b.data)}])}}return g}function v(w,g){const _={},b={start:{}};let k=["start"];for(let S=0;S<w.length;S++){const C=w[S],x=[];for(let R=0;R<C.length;R++){const j=C[R],O=""+S+R;x.push(O),_[O]={node:j,lastCount:0},b[O]={};for(let D=0;D<k.length;D++){const U=k[D];_[U]&&_[U].node.mode===j.mode?(b[U][O]=h(_[U].lastCount+j.length,j.mode)-h(_[U].lastCount,j.mode),_[U].lastCount+=j.length):(_[U]&&(_[U].lastCount=j.length),b[U][O]=h(j.length,j.mode)+4+e.getCharCountIndicator(j.mode,g))}}k=x}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:_}}function y(w,g){let _;const b=e.getBestModeForData(w);if(_=e.from(g,b),_!==e.BYTE&&_.bit<b.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(_)+`.
|
|
46
|
+
Suggested mode is: `+e.toString(b));switch(_===e.KANJI&&!i.isKanjiModeEnabled()&&(_=e.BYTE),_){case e.NUMERIC:return new r(w);case e.ALPHANUMERIC:return new n(w);case e.KANJI:return new o(w);case e.BYTE:return new s(w)}}t.fromArray=function(g){return g.reduce(function(_,b){return typeof b=="string"?_.push(y(b,null)):b.data&&_.push(y(b.data,b.mode)),_},[])},t.fromString=function(g,_){const b=p(g,i.isKanjiModeEnabled()),k=f(b),S=v(k,_),C=c.find_path(S.map,"start","end"),x=[];for(let R=1;R<C.length-1;R++)x.push(S.table[C[R]].node);return t.fromArray(d(x))},t.rawSplit=function(g){return t.fromArray(p(g,i.isKanjiModeEnabled()))}})(cu)),cu}var lm;function S5(){if(lm)return Wl;lm=1;const t=yn(),e=Kl(),r=i5(),n=c5(),s=l5(),o=u5(),a=d5(),i=B0(),c=h5(),l=m5(),u=g5(),p=_n(),h=k5();function d(S,C){const x=S.size,R=o.getPositions(C);for(let j=0;j<R.length;j++){const O=R[j][0],D=R[j][1];for(let U=-1;U<=7;U++)if(!(O+U<=-1||x<=O+U))for(let V=-1;V<=7;V++)D+V<=-1||x<=D+V||(U>=0&&U<=6&&(V===0||V===6)||V>=0&&V<=6&&(U===0||U===6)||U>=2&&U<=4&&V>=2&&V<=4?S.set(O+U,D+V,!0,!0):S.set(O+U,D+V,!1,!0))}}function f(S){const C=S.size;for(let x=8;x<C-8;x++){const R=x%2===0;S.set(x,6,R,!0),S.set(6,x,R,!0)}}function v(S,C){const x=s.getPositions(C);for(let R=0;R<x.length;R++){const j=x[R][0],O=x[R][1];for(let D=-2;D<=2;D++)for(let U=-2;U<=2;U++)D===-2||D===2||U===-2||U===2||D===0&&U===0?S.set(j+D,O+U,!0,!0):S.set(j+D,O+U,!1,!0)}}function y(S,C){const x=S.size,R=l.getEncodedBits(C);let j,O,D;for(let U=0;U<18;U++)j=Math.floor(U/3),O=U%3+x-8-3,D=(R>>U&1)===1,S.set(j,O,D,!0),S.set(O,j,D,!0)}function w(S,C,x){const R=S.size,j=u.getEncodedBits(C,x);let O,D;for(O=0;O<15;O++)D=(j>>O&1)===1,O<6?S.set(O,8,D,!0):O<8?S.set(O+1,8,D,!0):S.set(R-15+O,8,D,!0),O<8?S.set(8,R-O-1,D,!0):O<9?S.set(8,15-O-1+1,D,!0):S.set(8,15-O-1,D,!0);S.set(R-8,8,1,!0)}function g(S,C){const x=S.size;let R=-1,j=x-1,O=7,D=0;for(let U=x-1;U>0;U-=2)for(U===6&&U--;;){for(let V=0;V<2;V++)if(!S.isReserved(j,U-V)){let ne=!1;D<C.length&&(ne=(C[D]>>>O&1)===1),S.set(j,U-V,ne),O--,O===-1&&(D++,O=7)}if(j+=R,j<0||x<=j){j-=R,R=-R;break}}}function _(S,C,x){const R=new r;x.forEach(function(V){R.put(V.mode.bit,4),R.put(V.getLength(),p.getCharCountIndicator(V.mode,S)),V.write(R)});const j=t.getSymbolTotalCodewords(S),O=i.getTotalCodewordsCount(S,C),D=(j-O)*8;for(R.getLengthInBits()+4<=D&&R.put(0,4);R.getLengthInBits()%8!==0;)R.putBit(0);const U=(D-R.getLengthInBits())/8;for(let V=0;V<U;V++)R.put(V%2?17:236,8);return b(R,S,C)}function b(S,C,x){const R=t.getSymbolTotalCodewords(C),j=i.getTotalCodewordsCount(C,x),O=R-j,D=i.getBlocksCount(C,x),U=R%D,V=D-U,ne=Math.floor(R/D),fe=Math.floor(O/D),de=fe+1,te=ne-fe,ye=new c(te);let H=0;const P=new Array(D),F=new Array(D);let q=0;const E=new Uint8Array(S.buffer);for(let _e=0;_e<D;_e++){const pe=_e<V?fe:de;P[_e]=E.slice(H,H+pe),F[_e]=ye.encode(P[_e]),H+=pe,q=Math.max(q,pe)}const I=new Uint8Array(R);let $=0,B,G;for(B=0;B<q;B++)for(G=0;G<D;G++)B<P[G].length&&(I[$++]=P[G][B]);for(B=0;B<te;B++)for(G=0;G<D;G++)I[$++]=F[G][B];return I}function k(S,C,x,R){let j;if(Array.isArray(S))j=h.fromArray(S);else if(typeof S=="string"){let ne=C;if(!ne){const fe=h.rawSplit(S);ne=l.getBestVersionForData(fe,x)}j=h.fromString(S,ne||40)}else throw new Error("Invalid data");const O=l.getBestVersionForData(j,x);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=O;else if(C<O)throw new Error(`
|
|
47
47
|
The chosen QR Code version cannot contain this amount of data.
|
|
48
|
-
Minimum version required to store current data is: `+
|
|
49
|
-
`);const
|
|
50
|
-
`;return typeof i=="function"&&i(null,
|
|
48
|
+
Minimum version required to store current data is: `+O+`.
|
|
49
|
+
`);const D=_(C,x,j),U=t.getSymbolSize(C),V=new n(U);return d(V,C),f(V),v(V,C),w(V,x,0),C>=7&&y(V,C),g(V,D),isNaN(R)&&(R=a.getBestMask(V,w.bind(null,V,x))),a.applyMask(R,V),w(V,x,R),{modules:V,version:C,errorCorrectionLevel:x,maskPattern:R,segments:j}}return Wl.create=function(C,x){if(typeof C>"u"||C==="")throw new Error("No input text");let R=e.M,j,O;return typeof x<"u"&&(R=e.from(x.errorCorrectionLevel,e.M),j=l.from(x.version),O=a.from(x.maskPattern),x.toSJISFunc&&t.setToSJISFunction(x.toSJISFunc)),k(C,j,R,O)},Wl}var hu={},mu={},um;function dm(){return um||(um=1,(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const s=parseInt(n.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+n.slice(0,6).join("")}}t.getOptions=function(n){n||(n={}),n.color||(n.color={});const s=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:o,scale:o?4:a,margin:s,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},t.getScale=function(n,s){return s.width&&s.width>=n+s.margin*2?s.width/(n+s.margin*2):s.scale},t.getImageWidth=function(n,s){const o=t.getScale(n,s);return Math.floor((n+s.margin*2)*o)},t.qrToImageData=function(n,s,o){const a=s.modules.size,i=s.modules.data,c=t.getScale(a,o),l=Math.floor((a+o.margin*2)*c),u=o.margin*c,p=[o.color.light,o.color.dark];for(let h=0;h<l;h++)for(let d=0;d<l;d++){let f=(h*l+d)*4,v=o.color.light;if(h>=u&&d>=u&&h<l-u&&d<l-u){const y=Math.floor((h-u)/c),w=Math.floor((d-u)/c);v=p[i[y*a+w]?1:0]}n[f++]=v.r,n[f++]=v.g,n[f++]=v.b,n[f]=v.a}}})(mu)),mu}var pm;function C5(){return pm||(pm=1,(function(t){const e=dm();function r(s,o,a){s.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=a,o.width=a,o.style.height=a+"px",o.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(o,a,i){let c=i,l=a;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),a||(l=n()),c=e.getOptions(c);const u=e.getImageWidth(o.modules.size,c),p=l.getContext("2d"),h=p.createImageData(u,u);return e.qrToImageData(h.data,o,c),r(p,l,u),p.putImageData(h,0,0),l},t.renderToDataURL=function(o,a,i){let c=i;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),c||(c={});const l=t.render(o,a,c),u=c.type||"image/png",p=c.rendererOpts||{};return l.toDataURL(u,p.quality)}})(hu)),hu}var gu={},fm;function T5(){if(fm)return gu;fm=1;const t=dm();function e(s,o){const a=s.a/255,i=o+'="'+s.hex+'"';return a<1?i+" "+o+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(s,o,a){let i=s+o;return typeof a<"u"&&(i+=" "+a),i}function n(s,o,a){let i="",c=0,l=!1,u=0;for(let p=0;p<s.length;p++){const h=Math.floor(p%o),d=Math.floor(p/o);!h&&!l&&(l=!0),s[p]?(u++,p>0&&h>0&&s[p-1]||(i+=l?r("M",h+a,.5+d+a):r("m",c,0),c=0,l=!1),h+1<o&&s[p+1]||(i+=r("h",u),u=0)):c++}return i}return gu.render=function(o,a,i){const c=t.getOptions(a),l=o.modules.size,u=o.modules.data,p=l+c.margin*2,h=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+p+"v"+p+'H0z"/>':"",d="<path "+e(c.color.dark,"stroke")+' d="'+n(u,l,c.margin)+'"/>',f='viewBox="0 0 '+p+" "+p+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+f+' shape-rendering="crispEdges">'+h+d+`</svg>
|
|
50
|
+
`;return typeof i=="function"&&i(null,y),y},gu}var hm;function $5(){if(hm)return Kn;hm=1;const t=a5(),e=S5(),r=C5(),n=T5();function s(o,a,i,c,l){const u=[].slice.call(arguments,1),p=u.length,h=typeof u[p-1]=="function";if(!h&&!t())throw new Error("Callback required as last argument");if(h){if(p<2)throw new Error("Too few arguments provided");p===2?(l=i,i=a,a=c=void 0):p===3&&(a.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=i,i=a,a=void 0))}else{if(p<1)throw new Error("Too few arguments provided");return p===1?(i=a,a=c=void 0):p===2&&!a.getContext&&(c=i,i=a,a=void 0),new Promise(function(d,f){try{const v=e.create(i,c);d(o(v,a,c))}catch(v){f(v)}})}try{const d=e.create(i,c);l(null,o(d,a,c))}catch(d){l(d)}}return Kn.create=e.create,Kn.toCanvas=s.bind(null,r.render),Kn.toDataURL=s.bind(null,r.renderToDataURL),Kn.toString=s.bind(null,function(o,a,i){return n.render(o,i)}),Kn}var E5=$5();const mm=rn(E5);class gm{constructor(e,{size:r=200,margin:n=4,color:s="#000",bgColor:o="#fff"}){this.value=e,this.size=r,this.margin=n,this.color=s,this.bgColor=o}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return mm.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return mm.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const x5={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class I5{constructor(e,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof e=="string"?document.querySelector(e):e,!this.el)throw new Error("Tooltip: invalid element");this.opts={...x5,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const e=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),e==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const e=this.opts.trigger;e==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):e==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):e==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const e=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
|
|
51
51
|
<div class="${this.opts.className}__arrow"></div>
|
|
52
52
|
<div class="${this.opts.className}__inner">${e}</div>
|
|
53
|
-
`}reposition(){const e=this.placementList(this.opts.placement);for(const r of e){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(e){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),s=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,c="center"]=e.split("-");let l=0,u=0;return i==="top"?l=r.top+s-n.height-a:i==="bottom"?l=r.bottom+s+a:i==="left"?u=r.left+o-n.width-a:i==="right"&&(u=r.right+o+a),(i==="top"||i==="bottom")&&(c==="start"?u=r.left+o:c==="end"?u=r.right+o-n.width:u=(r.left+r.right)/2+o-n.width/2),(i==="left"||i==="right")&&(c==="start"?l=r.top+s:c==="end"?l=r.bottom+s-n.height:l=(r.top+r.bottom)/2+s-n.height/2),{top:Math.round(l),left:Math.round(u)}}applyStyle({top:e,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${e}px`,left:`${r}px`})}checkViewport({top:e,left:r}){const s=window.innerWidth,o=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&e>=5&&r+a.width<=s-5&&e+a.height<=o-5}placementList(e){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[e.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=e=>{const r=e.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const
|
|
53
|
+
`}reposition(){const e=this.placementList(this.opts.placement);for(const r of e){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(e){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),s=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,c="center"]=e.split("-");let l=0,u=0;return i==="top"?l=r.top+s-n.height-a:i==="bottom"?l=r.bottom+s+a:i==="left"?u=r.left+o-n.width-a:i==="right"&&(u=r.right+o+a),(i==="top"||i==="bottom")&&(c==="start"?u=r.left+o:c==="end"?u=r.right+o-n.width:u=(r.left+r.right)/2+o-n.width/2),(i==="left"||i==="right")&&(c==="start"?l=r.top+s:c==="end"?l=r.bottom+s-n.height:l=(r.top+r.bottom)/2+s-n.height/2),{top:Math.round(l),left:Math.round(u)}}applyStyle({top:e,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${e}px`,left:`${r}px`})}checkViewport({top:e,left:r}){const s=window.innerWidth,o=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&e>=5&&r+a.width<=s-5&&e+a.height<=o-5}placementList(e){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[e.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=e=>{const r=e.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const ym="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(ym))return;const t=document.createElement("style");t.id=ym,t.textContent=`
|
|
54
54
|
.tiny-remoter-native-tooltip {
|
|
55
55
|
position: absolute;
|
|
56
56
|
z-index: 9999;
|
|
@@ -97,9 +97,9 @@ Minimum version required to store current data is: `+N+`.
|
|
|
97
97
|
transform: translateY(-50%);
|
|
98
98
|
border-right-color: rgba(0,0,0,.75);
|
|
99
99
|
}
|
|
100
|
-
`,document.head.appendChild(t)})();const RE="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",PE="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",OE="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",AE="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",ME="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",NE="https://agent.opentiny.design/tiny-robot",pg="https://ai.opentiny.design/next-remoter",hg=t=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:AE},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:RE},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${t.remoteUrl}`,active:!0,tip:t.remoteUrl,showCopyIcon:!0,icon:OE},{action:"remote-control",show:!0,text:"识别码",desc:`${t.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:PE}];class LE{constructor(e){if(this.isExpanded=!1,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const s=this.getImageUrl(r.icon);s&&n.appendChild(s)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new IE(n,{content:"复制",placement:"top",trigger:"hover"})},!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||pg,remoteUrl:e.remoteUrl||NE},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?hg(this.options).map(r=>{const n=e.find(s=>s.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):hg(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(t)})();const R5="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",P5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_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",O5="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_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",A5="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",M5="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",N5="https://agent.opentiny.design/tiny-robot",_m="https://ai.opentiny.design/next-remoter",vm=t=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:A5},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:R5},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${t.remoteUrl}`,active:!0,tip:t.remoteUrl,showCopyIcon:!0,icon:O5},{action:"remote-control",show:!0,text:"识别码",desc:`${t.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:P5}];class L5{constructor(e){if(this.isExpanded=!1,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const s=this.getImageUrl(r.icon);s&&n.appendChild(s)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new I5(n,{content:"复制",placement:"top",trigger:"hover"})},!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||_m,remoteUrl:e.remoteUrl||N5},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?vm(this.options).map(r=>{const n=e.find(s=>s.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):vm(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
|
-
<img style="display: block; width: 56px;" src="${
|
|
102
|
+
<img style="display: block; width: 56px;" src="${_m}/svgs/logo-next-no-bg-left.svg" alt="icon" />
|
|
103
103
|
</div>
|
|
104
104
|
`,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
|
|
105
105
|
<div class="tiny-remoter-dropdown-item" data-action="${r.action}">
|
|
@@ -112,14 +112,14 @@ Minimum version required to store current data is: `+N+`.
|
|
|
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="${M5}"/>
|
|
116
116
|
</div>
|
|
117
117
|
`:""}
|
|
118
118
|
</div>
|
|
119
119
|
</div>
|
|
120
120
|
</div>
|
|
121
121
|
</div>
|
|
122
|
-
`).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,n=r.closest(".tiny-remoter-copy-icon");if(n){e.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const o=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;o&&this.handleAction(o)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new
|
|
122
|
+
`).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,n=r.closest(".tiny-remoter-copy-icon");if(n){e.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const o=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;o&&this.handleAction(o)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new gm((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
|
|
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: `+N+`.
|
|
|
545
545
|
color: white;
|
|
546
546
|
}
|
|
547
547
|
}
|
|
548
|
-
`,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const
|
|
549
|
-
Error message: ${
|
|
550
|
-
Error message: ${ls(r)}`,cause:r}),this[Hg]=!0,this.value=e}static isInstance(e){return Se.hasMarker(e,Fg)}static wrap({value:e,cause:r}){return Cp.isInstance(r)&&r.value===e?r:new Cp({value:e,cause:r})}};Hg=GE;var Co=KE,Bg="AI_UnsupportedFunctionalityError",Jg=`vercel.ai.error.${Bg}`,YE=Symbol.for(Jg),Wg,Gg=class extends Se{constructor({functionality:e,message:r=`'${e}' functionality not supported.`}){super({name:Bg,message:r}),this[Wg]=!0,this.functionality=e}static isInstance(e){return Se.hasMarker(e,Jg)}};Wg=YE;function ds(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function QE(t,e){if(t==null)return Promise.resolve();const r=e?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(Kg());return}const o=setTimeout(()=>{a(),n()},t),a=()=>{clearTimeout(o),r?.removeEventListener("abort",i)},i=()=>{a(),s(Kg())};r?.addEventListener("abort",i)})}function Kg(){return new DOMException("Delay was aborted","AbortError")}var Hi=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function To(t){return Object.fromEntries([...t.headers])}var $o=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new Tg({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},Eo=$o();function Sd(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function On(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var XE=["fetch failed","failed to fetch"];function Yg({error:t,url:e,requestBodyValues:r}){if(On(t))return t;if(t instanceof TypeError&&XE.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new wt({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function xo(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function ex(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function on(t,...e){const r=new Headers(ex(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Qg="3.0.18",tx=()=>globalThis.fetch,Xg=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=tx()})=>{try{const a=await o(t,{method:"GET",headers:on(e,`ai-sdk/provider-utils/${Qg}`,xo()),signal:s}),i=To(a);if(!a.ok){let c;try{c=await n({response:a,url:t,requestBodyValues:{}})}catch(l){throw On(l)||wt.isInstance(l)?l:new wt({message:"Failed to process error response",cause:l,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw c.value}try{return await r({response:a,url:t,requestBodyValues:{}})}catch(c){throw c instanceof Error&&(On(c)||wt.isInstance(c))?c:new wt({message:"Failed to process successful response",cause:c,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Yg({error:a,url:t,requestBodyValues:{}})}};function rx({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function nx({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Fi({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Fi({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Fi({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Fi({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function Bi({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var sx=/"__proto__"\s*:/,ox=/"constructor"\s*:/;function e_(t){const e=JSON.parse(t);return e===null||typeof e!="object"||sx.test(t)===!1&&ox.test(t)===!1?e:ax(e)}function ax(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function kd(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return e_(t)}try{return e_(t)}finally{Error.stackTraceLimit=e}}var Ji=Symbol.for("vercel.ai.validator");function ix(t){return{[Ji]:!0,validate:t}}function cx(t){return typeof t=="object"&&t!==null&&Ji in t&&t[Ji]===!0&&"validate"in t}function ps(t){let e;return()=>(e==null&&(e=t()),e)}function lx(t){return cx(t)?t:typeof t=="function"?t():ux(t)}function ux(t){return ix(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Co({value:e,cause:r.issues})}})}async function Cd({value:t,schema:e}){const r=await ir({value:t,schema:e});if(!r.success)throw Co.wrap({value:t,cause:r.error});return r.value}async function ir({value:t,schema:e}){const r=lx(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:Co.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:Co.wrap({value:t,cause:n}),rawValue:t}}}async function dx({text:t,schema:e}){try{const r=kd(t);return e==null?r:Cd({value:r,schema:e})}catch(r){throw Vi.isInstance(r)||Co.isInstance(r)?r:new Vi({text:t,cause:r})}}async function An({text:t,schema:e}){try{const r=kd(t);return e==null?{success:!0,value:r,rawValue:r}:await ir({value:r,schema:e})}catch(r){return{success:!1,error:Vi.isInstance(r)?r:new Vi({text:t,cause:r}),rawValue:void 0}}}function t_(t){try{return kd(t),!0}catch{return!1}}function px({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new En).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await An({text:r,schema:e}))}}))}async function r_({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await ir({value:e[t],schema:r});if(!n.success)throw new Tg({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var hx=()=>globalThis.fetch,hs=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>fx({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),fx=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=hx()})=>{try{const i=await a(t,{method:"POST",headers:on(e,`ai-sdk/provider-utils/${Qg}`,xo()),body:r.content,signal:o}),c=To(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw On(u)||wt.isInstance(u)?u:new wt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(On(l)||wt.isInstance(l))?l:new wt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw Yg({error:i,url:t,requestBodyValues:r.values})}};function UM(t){return t}function n_(t){return{...t,type:"dynamic"}}async function wr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var Mn=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=To(n);if(a.trim()==="")return{responseHeaders:i,value:new wt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await dx({text:a,schema:t});return{responseHeaders:i,value:new wt({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new wt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},s_=t=>async({response:e})=>{const r=To(e);if(e.body==null)throw new ZE({});return{responseHeaders:r,value:px({stream:e.body,schema:t})}},fs=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await An({text:s,schema:t}),a=To(e);if(!o.success)throw new wt({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},mx=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},gx=Symbol("Let zodToJsonSchema decide on which parser to use"),o_={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"},_x=t=>typeof t=="string"?{...o_,name:t}:{...o_,...t};function qt(){return{}}function vx(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==U.ZodAny&&(o.items=Ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function yx(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function wx(){return{type:"boolean"}}function a_(t,e){return Ze(t.type._def,e)}var bx=(t,e)=>Ze(t.innerType._def,e);function i_(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>i_(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Sx(t)}}var Sx=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function kx(t,e){return{...Ze(t.innerType._def,e),default:t.defaultValue()}}function Cx(t,e){return e.effectStrategy==="input"?Ze(t.schema._def,e):qt()}function Tx(t){return{type:"string",enum:Array.from(t.values)}}var $x=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ex(t,e){const r=[Ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if($x(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function xx(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Td=void 0,cr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Td===void 0&&(Td=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Td),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 c_(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":lr(r,"email",n.message,e);break;case"format:idn-email":lr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,cr.email,n.message,e);break}break;case"url":lr(r,"uri",n.message,e);break;case"uuid":lr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,cr.cuid,n.message,e);break;case"cuid2":bt(r,cr.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${$d(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${$d(n.value,e)}$`),n.message,e);break;case"datetime":lr(r,"date-time",n.message,e);break;case"date":lr(r,"date",n.message,e);break;case"time":lr(r,"time",n.message,e);break;case"duration":lr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{bt(r,RegExp($d(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&lr(r,"ipv4",n.message,e),n.version!=="v4"&&lr(r,"ipv6",n.message,e);break}case"base64url":bt(r,cr.base64url,n.message,e);break;case"jwt":bt(r,cr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,cr.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,cr.ipv6Cidr,n.message,e);break}case"emoji":bt(r,cr.emoji(),n.message,e);break;case"ulid":{bt(r,cr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{lr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{bt(r,cr.base64,n.message,e);break}}break}case"nanoid":bt(r,cr.nanoid,n.message,e)}return r}function $d(t,e){return e.patternStrategy==="escape"?Rx(t):t}var Ix=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rx(t){let e="";for(let r=0;r<t.length;r++)Ix.has(t[r])||(e+="\\"),e+=t[r];return e}function lr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function bt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:l_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=l_(e,n)}function l_(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
|
|
548
|
+
`,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const j5=(t={})=>new L5(t);var wm="vercel.ai.error",q5=Symbol.for(wm),bm,z5=class b_ extends Error{constructor({name:e,message:r,cause:n}){super(r),this[bm]=!0,this.name=e,this.cause=n}static isInstance(e){return b_.hasMarker(e,wm)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};bm=q5;var we=z5,km="AI_APICallError",Sm=`vercel.ai.error.${km}`,D5=Symbol.for(Sm),Cm,gt=class extends we{constructor({message:e,url:r,requestBodyValues:n,statusCode:s,responseHeaders:o,responseBody:a,cause:i,isRetryable:c=s!=null&&(s===408||s===409||s===429||s>=500),data:l}){super({name:km,message:e,cause:i}),this[Cm]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=s,this.responseHeaders=o,this.responseBody=a,this.isRetryable=c,this.data=l}static isInstance(e){return we.hasMarker(e,Sm)}};Cm=D5;var Tm="AI_EmptyResponseBodyError",$m=`vercel.ai.error.${Tm}`,U5=Symbol.for($m),Em,Z5=class extends we{constructor({message:e="Empty response body"}={}){super({name:Tm,message:e}),this[Em]=!0}static isInstance(e){return we.hasMarker(e,$m)}};Em=U5;function Yn(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var xm="AI_InvalidArgumentError",Im=`vercel.ai.error.${xm}`,F5=Symbol.for(Im),Rm,Pm=class extends we{constructor({message:e,cause:r,argument:n}){super({name:xm,message:e,cause:r}),this[Rm]=!0,this.argument=n}static isInstance(e){return we.hasMarker(e,Im)}};Rm=F5;var Om="AI_InvalidPromptError",Am=`vercel.ai.error.${Om}`,V5=Symbol.for(Am),Mm,Qn=class extends we{constructor({prompt:e,message:r,cause:n}){super({name:Om,message:`Invalid prompt: ${r}`,cause:n}),this[Mm]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,Am)}};Mm=V5;var Nm="AI_InvalidResponseDataError",Lm=`vercel.ai.error.${Nm}`,H5=Symbol.for(Lm),jm,qm=class extends we{constructor({data:e,message:r=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Nm,message:r}),this[jm]=!0,this.data=e}static isInstance(e){return we.hasMarker(e,Lm)}};jm=H5;var zm="AI_JSONParseError",Dm=`vercel.ai.error.${zm}`,B5=Symbol.for(Dm),Um,pi=class extends we{constructor({text:e,cause:r}){super({name:zm,message:`JSON parsing failed: Text: ${e}.
|
|
549
|
+
Error message: ${Yn(r)}`,cause:r}),this[Um]=!0,this.text=e}static isInstance(e){return we.hasMarker(e,Dm)}};Um=B5;var Zm="AI_LoadAPIKeyError",Fm=`vercel.ai.error.${Zm}`,J5=Symbol.for(Fm),Vm,fi=class extends we{constructor({message:e}){super({name:Zm,message:e}),this[Vm]=!0}static isInstance(e){return we.hasMarker(e,Fm)}};Vm=J5;var Hm="AI_NoSuchModelError",Bm=`vercel.ai.error.${Hm}`,W5=Symbol.for(Bm),Jm,Wm=class extends we{constructor({errorName:t=Hm,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[Jm]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return we.hasMarker(t,Bm)}};Jm=W5;var Gm="AI_TypeValidationError",Km=`vercel.ai.error.${Gm}`,G5=Symbol.for(Km),Ym,K5=class vd extends we{constructor({value:e,cause:r}){super({name:Gm,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
550
|
+
Error message: ${Yn(r)}`,cause:r}),this[Ym]=!0,this.value=e}static isInstance(e){return we.hasMarker(e,Km)}static wrap({value:e,cause:r}){return vd.isInstance(r)&&r.value===e?r:new vd({value:e,cause:r})}};Ym=G5;var co=K5,Qm="AI_UnsupportedFunctionalityError",Xm=`vercel.ai.error.${Qm}`,Y5=Symbol.for(Xm),e2,t2=class extends we{constructor({functionality:e,message:r=`'${e}' functionality not supported.`}){super({name:Qm,message:r}),this[e2]=!0,this.functionality=e}static isInstance(e){return we.hasMarker(e,Xm)}};e2=Y5;function Xn(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function Q5(t,e){if(t==null)return Promise.resolve();const r=e?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(r2());return}const o=setTimeout(()=>{a(),n()},t),a=()=>{clearTimeout(o),r?.removeEventListener("abort",i)},i=()=>{a(),s(r2())};r?.addEventListener("abort",i)})}function r2(){return new DOMException("Delay was aborted","AbortError")}var hi=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function lo(t){return Object.fromEntries([...t.headers])}var uo=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new Pm({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},po=uo();function yu(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function vn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var X5=["fetch failed","failed to fetch"];function n2({error:t,url:e,requestBodyValues:r}){if(vn(t))return t;if(t instanceof TypeError&&X5.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new gt({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function fo(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function eC(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Kr(t,...e){const r=new Headers(eC(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var s2="3.0.18",tC=()=>globalThis.fetch,o2=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=tC()})=>{try{const a=await o(t,{method:"GET",headers:Kr(e,`ai-sdk/provider-utils/${s2}`,fo()),signal:s}),i=lo(a);if(!a.ok){let c;try{c=await n({response:a,url:t,requestBodyValues:{}})}catch(l){throw vn(l)||gt.isInstance(l)?l:new gt({message:"Failed to process error response",cause:l,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw c.value}try{return await r({response:a,url:t,requestBodyValues:{}})}catch(c){throw c instanceof Error&&(vn(c)||gt.isInstance(c))?c:new gt({message:"Failed to process successful response",cause:c,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw n2({error:a,url:t,requestBodyValues:{}})}};function rC({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function nC({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new fi({message:`${n} API key must be a string.`});if(typeof process>"u")throw new fi({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new fi({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new fi({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function mi({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var sC=/"__proto__"\s*:/,oC=/"constructor"\s*:/;function a2(t){const e=JSON.parse(t);return e===null||typeof e!="object"||sC.test(t)===!1&&oC.test(t)===!1?e:aC(e)}function aC(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function _u(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return a2(t)}try{return a2(t)}finally{Error.stackTraceLimit=e}}var gi=Symbol.for("vercel.ai.validator");function iC(t){return{[gi]:!0,validate:t}}function cC(t){return typeof t=="object"&&t!==null&&gi in t&&t[gi]===!0&&"validate"in t}function es(t){let e;return()=>(e==null&&(e=t()),e)}function lC(t){return cC(t)?t:typeof t=="function"?t():uC(t)}function uC(t){return iC(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new co({value:e,cause:r.issues})}})}async function vu({value:t,schema:e}){const r=await er({value:t,schema:e});if(!r.success)throw co.wrap({value:t,cause:r.error});return r.value}async function er({value:t,schema:e}){const r=lC(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:co.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:co.wrap({value:t,cause:n}),rawValue:t}}}async function dC({text:t,schema:e}){try{const r=_u(t);return e==null?r:vu({value:r,schema:e})}catch(r){throw pi.isInstance(r)||co.isInstance(r)?r:new pi({text:t,cause:r})}}async function wn({text:t,schema:e}){try{const r=_u(t);return e==null?{success:!0,value:r,rawValue:r}:await er({value:r,schema:e})}catch(r){return{success:!1,error:pi.isInstance(r)?r:new pi({text:t,cause:r}),rawValue:void 0}}}function i2(t){try{return _u(t),!0}catch{return!1}}function pC({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await wn({text:r,schema:e}))}}))}async function c2({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await er({value:e[t],schema:r});if(!n.success)throw new Pm({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var fC=()=>globalThis.fetch,ts=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>hC({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),hC=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=fC()})=>{try{const i=await a(t,{method:"POST",headers:Kr(e,`ai-sdk/provider-utils/${s2}`,fo()),body:r.content,signal:o}),c=lo(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw vn(u)||gt.isInstance(u)?u:new gt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(vn(l)||gt.isInstance(l))?l:new gt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw n2({error:i,url:t,requestBodyValues:r.values})}};function zR(t){return t}function l2(t){return{...t,type:"dynamic"}}async function dr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var bn=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=lo(n);if(a.trim()==="")return{responseHeaders:i,value:new gt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await dC({text:a,schema:t});return{responseHeaders:i,value:new gt({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new gt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},u2=t=>async({response:e})=>{const r=lo(e);if(e.body==null)throw new Z5({});return{responseHeaders:r,value:pC({stream:e.body,schema:t})}},rs=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await wn({text:s,schema:t}),a=lo(e);if(!o.success)throw new gt({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},mC=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},gC=Symbol("Let zodToJsonSchema decide on which parser to use"),d2={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"},yC=t=>typeof t=="string"?{...d2,name:t}:{...d2,...t};function Ot(){return{}}function _C(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function vC(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function wC(){return{type:"boolean"}}function p2(t,e){return ze(t.type._def,e)}var bC=(t,e)=>ze(t.innerType._def,e);function f2(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>f2(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return kC(t)}}var kC=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function SC(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function CC(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Ot()}function TC(t){return{type:"string",enum:Array.from(t.values)}}var $C=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function EC(t,e){const r=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if($C(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function xC(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var wu=void 0,tr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(wu===void 0&&(wu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wu),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function h2(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":rr(r,"email",n.message,e);break;case"format:idn-email":rr(r,"idn-email",n.message,e);break;case"pattern:zod":yt(r,tr.email,n.message,e);break}break;case"url":rr(r,"uri",n.message,e);break;case"uuid":rr(r,"uuid",n.message,e);break;case"regex":yt(r,n.regex,n.message,e);break;case"cuid":yt(r,tr.cuid,n.message,e);break;case"cuid2":yt(r,tr.cuid2,n.message,e);break;case"startsWith":yt(r,RegExp(`^${bu(n.value,e)}`),n.message,e);break;case"endsWith":yt(r,RegExp(`${bu(n.value,e)}$`),n.message,e);break;case"datetime":rr(r,"date-time",n.message,e);break;case"date":rr(r,"date",n.message,e);break;case"time":rr(r,"time",n.message,e);break;case"duration":rr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{yt(r,RegExp(bu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&rr(r,"ipv4",n.message,e),n.version!=="v4"&&rr(r,"ipv6",n.message,e);break}case"base64url":yt(r,tr.base64url,n.message,e);break;case"jwt":yt(r,tr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&yt(r,tr.ipv4Cidr,n.message,e),n.version!=="v4"&&yt(r,tr.ipv6Cidr,n.message,e);break}case"emoji":yt(r,tr.emoji(),n.message,e);break;case"ulid":{yt(r,tr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{rr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{yt(r,tr.base64,n.message,e);break}}break}case"nanoid":yt(r,tr.nanoid,n.message,e)}return r}function bu(t,e){return e.patternStrategy==="escape"?RC(t):t}var IC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function RC(t){let e="";for(let r=0;r<t.length;r++)IC.has(t[r])||(e+="\\"),e+=t[r];return e}function rr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function yt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:m2(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=m2(e,n)}function m2(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
|
|
551
551
|
]))`;continue}else if(s[l]==="$"){o+=`($|(?=[\r
|
|
552
552
|
]))`;continue}}if(n.s&&s[l]==="."){o+=i?`${s[l]}\r
|
|
553
553
|
`:`[${s[l]}\r
|
|
554
|
-
]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function u_(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=Ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===U.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=c_(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===U.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=a_(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function Px(t,e){if(e.mapStrategy==="record")return u_(t,e);const r=Ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qt(),n=Ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ox(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Ax(){return{not:qt()}}function Mx(){return{type:"null"}}var Ed={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nx(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ed&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ed[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Lx(t,e)}var Lx=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ze(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function qx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ed[t.innerType._def.typeName],"null"]};const r=Ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jx(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Ux(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=Dx(i),l=Ze(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=zx(t,e);return o!==void 0&&(r.additionalProperties=o),r}function zx(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dx(t){try{return t.isOptional()}catch{return!0}}var Zx=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ze(t.innerType._def,e);const n=Ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:qt()},n]}:qt()},Vx=(t,e)=>{if(e.pipeStrategy==="input")return Ze(t.in._def,e);if(e.pipeStrategy==="output")return Ze(t.out._def,e);const r=Ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Fx(t,e){return Ze(t.type._def,e)}function Hx(t,e){const n={type:"array",uniqueItems:!0,items:Ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function Bx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Jx(){return{not:qt()}}function Wx(){return qt()}var Gx=(t,e)=>Ze(t.innerType._def,e),Kx=(t,e,r)=>{switch(e){case U.ZodString:return c_(t,r);case U.ZodNumber:return jx(t);case U.ZodObject:return Ux(t,r);case U.ZodBigInt:return yx(t);case U.ZodBoolean:return wx();case U.ZodDate:return i_(t,r);case U.ZodUndefined:return Jx();case U.ZodNull:return Mx();case U.ZodArray:return vx(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Nx(t,r);case U.ZodIntersection:return Ex(t,r);case U.ZodTuple:return Bx(t,r);case U.ZodRecord:return u_(t,r);case U.ZodLiteral:return xx(t);case U.ZodEnum:return Tx(t);case U.ZodNativeEnum:return Ox(t);case U.ZodNullable:return qx(t,r);case U.ZodOptional:return Zx(t,r);case U.ZodMap:return Px(t,r);case U.ZodSet:return Hx(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return Fx(t,r);case U.ZodNaN:case U.ZodNever:return Ax();case U.ZodEffects:return Cx(t,r);case U.ZodAny:return qt();case U.ZodUnknown:return Wx();case U.ZodDefault:return kx(t,r);case U.ZodBranded:return a_(t,r);case U.ZodReadonly:return Gx(t,r);case U.ZodCatch:return bx(t,r);case U.ZodPipeline:return Vx(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})()}};function Ze(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==gx)return c}if(s&&!r){const c=Yx(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=Kx(t,t.typeName,e),i=typeof a=="function"?Ze(a(),e):a;if(i&&Qx(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var Yx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mx(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qt()):e.$refStrategy==="seen"?qt():void 0}},Qx=(t,e,r)=>(t.description&&(r.description=t.description),r),Xx=t=>{const e=_x(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},e8=(t,e)=>{var r;const n=Xx(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,h])=>{var f;return{...l,[u]:(f=Ze(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?f:qt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Ze(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:qt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},t8=e8;function r8(t,e){var r;const n=(r=void 0)!=null?r:!1;return Io(()=>t8(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function n8(t,e){var r;const n=(r=void 0)!=null?r:!1;return Io(()=>Wc(t,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await Gc(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function s8(t){return"_zod"in t}function Nn(t,e){return s8(t)?n8(t):r8(t)}var xd=Symbol.for("vercel.ai.schema");function Io(t,{validate:e}={}){return{[xd]:!0,_type:void 0,[Ji]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function o8(t){return typeof t=="object"&&t!==null&&xd in t&&t[xd]===!0&&"jsonSchema"in t&&"validate"in t}function Wi(t){return t==null?Io({properties:{},additionalProperties:!1}):o8(t)?t:typeof t=="function"?t():Nn(t)}var{btoa:a8,atob:i8}=globalThis;function Id(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=i8(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Gi(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return a8(e)}function c8(t){return t instanceof Uint8Array?Gi(t):t}function d_(t){return t?.replace(/\/$/,"")}function l8(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*p_({execute:t,input:e,options:r}){const n=t(e,r);if(l8(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var Rd,h_;function u8(){if(h_)return Rd;h_=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(u,h)=>{for(var f in h)t(u,f,{get:h[f],enumerable:!0})},o=(u,h,f,p)=>{if(h&&typeof h=="object"||typeof h=="function")for(let m of r(h))!n.call(u,m)&&m!==f&&t(u,m,{get:()=>h[m],enumerable:!(p=e(h,m))||p.enumerable});return u},a=u=>o(t({},"__esModule",{value:!0}),u),i={};s(i,{SYMBOL_FOR_REQ_CONTEXT:()=>c,getContext:()=>l}),Rd=a(i);const c=Symbol.for("@vercel/request-context");function l(){return globalThis[c]?.get?.()??{}}return Rd}var Pd,f_;function d8(){if(f_)return Pd;f_=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(h,f)=>{for(var p in f)t(h,p,{get:f[p],enumerable:!0})},o=(h,f,p,m)=>{if(f&&typeof f=="object"||typeof f=="function")for(let v of r(f))!n.call(h,v)&&v!==p&&t(h,v,{get:()=>f[v],enumerable:!(m=e(f,v))||m.enumerable});return h},a=h=>o(t({},"__esModule",{value:!0}),h),i={};s(i,{getContext:()=>c.getContext,getVercelOidcToken:()=>l,getVercelOidcTokenSync:()=>u}),Pd=a(i);var c=u8();async function l(){return""}function u(){return""}return Pd}var m_=d8(),p8="vercel.ai.gateway.error",Od=Symbol.for(p8),g_,__,jt=class _w extends(__=Error,g_=Od,__){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[g_]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return _w.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&Od in e&&e[Od]===!0}},v_="GatewayAuthenticationError",h8=`vercel.ai.gateway.error.${v_}`,y_=Symbol.for(h8),w_,b_,Ad=class vw extends(b_=jt,w_=y_,b_){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[w_]=!0,this.name=v_,this.type="authentication_error"}static isInstance(e){return jt.hasMarker(e)&&y_ in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
|
|
554
|
+
]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function g2(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=h2(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=p2(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function PC(t,e){if(e.mapStrategy==="record")return g2(t,e);const r=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ot(),n=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ot();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function OC(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function AC(){return{not:Ot()}}function MC(){return{type:"null"}}var ku={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function NC(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ku&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=ku[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return LC(t,e)}var LC=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>ze(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function jC(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[ku[t.innerType._def.typeName],"null"]};const r=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function qC(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function zC(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=UC(i),l=ze(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=DC(t,e);return o!==void 0&&(r.additionalProperties=o),r}function DC(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function UC(t){try{return t.isOptional()}catch{return!0}}var ZC=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return ze(t.innerType._def,e);const n=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ot()},n]}:Ot()},FC=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const r=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function VC(t,e){return ze(t.type._def,e)}function HC(t,e){const n={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function BC(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function JC(){return{not:Ot()}}function WC(){return Ot()}var GC=(t,e)=>ze(t.innerType._def,e),KC=(t,e,r)=>{switch(e){case z.ZodString:return h2(t,r);case z.ZodNumber:return qC(t);case z.ZodObject:return zC(t,r);case z.ZodBigInt:return vC(t);case z.ZodBoolean:return wC();case z.ZodDate:return f2(t,r);case z.ZodUndefined:return JC();case z.ZodNull:return MC();case z.ZodArray:return _C(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return NC(t,r);case z.ZodIntersection:return EC(t,r);case z.ZodTuple:return BC(t,r);case z.ZodRecord:return g2(t,r);case z.ZodLiteral:return xC(t);case z.ZodEnum:return TC(t);case z.ZodNativeEnum:return OC(t);case z.ZodNullable:return jC(t,r);case z.ZodOptional:return ZC(t,r);case z.ZodMap:return PC(t,r);case z.ZodSet:return HC(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return VC(t,r);case z.ZodNaN:case z.ZodNever:return AC();case z.ZodEffects:return CC(t,r);case z.ZodAny:return Ot();case z.ZodUnknown:return WC();case z.ZodDefault:return SC(t,r);case z.ZodBranded:return p2(t,r);case z.ZodReadonly:return GC(t,r);case z.ZodCatch:return bC(t,r);case z.ZodPipeline:return FC(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function ze(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==gC)return c}if(s&&!r){const c=YC(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=KC(t,t.typeName,e),i=typeof a=="function"?ze(a(),e):a;if(i&&QC(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var YC=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mC(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ot()):e.$refStrategy==="seen"?Ot():void 0}},QC=(t,e,r)=>(t.description&&(r.description=t.description),r),XC=t=>{const e=yC(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},eT=(t,e)=>{var r;const n=XC(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>{var h;return{...l,[u]:(h=ze(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Ot()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=ze(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Ot(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},tT=eT;function rT(t,e){var r;const n=(r=void 0)!=null?r:!1;return ho(()=>tT(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function nT(t,e){var r;const n=(r=void 0)!=null?r:!1;return ho(()=>yc(t,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await _c(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function sT(t){return"_zod"in t}function kn(t,e){return sT(t)?nT(t):rT(t)}var Su=Symbol.for("vercel.ai.schema");function ho(t,{validate:e}={}){return{[Su]:!0,_type:void 0,[gi]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function oT(t){return typeof t=="object"&&t!==null&&Su in t&&t[Su]===!0&&"jsonSchema"in t&&"validate"in t}function yi(t){return t==null?ho({properties:{},additionalProperties:!1}):oT(t)?t:typeof t=="function"?t():kn(t)}var{btoa:aT,atob:iT}=globalThis;function Cu(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=iT(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function _i(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return aT(e)}function cT(t){return t instanceof Uint8Array?_i(t):t}function y2(t){return t?.replace(/\/$/,"")}function lT(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*_2({execute:t,input:e,options:r}){const n=t(e,r);if(lT(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var Tu,v2;function uT(){if(v2)return Tu;v2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(u,p)=>{for(var h in p)t(u,h,{get:p[h],enumerable:!0})},o=(u,p,h,d)=>{if(p&&typeof p=="object"||typeof p=="function")for(let f of r(p))!n.call(u,f)&&f!==h&&t(u,f,{get:()=>p[f],enumerable:!(d=e(p,f))||d.enumerable});return u},a=u=>o(t({},"__esModule",{value:!0}),u),i={};s(i,{SYMBOL_FOR_REQ_CONTEXT:()=>c,getContext:()=>l}),Tu=a(i);const c=Symbol.for("@vercel/request-context");function l(){return globalThis[c]?.get?.()??{}}return Tu}var $u,w2;function dT(){if(w2)return $u;w2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(p,h)=>{for(var d in h)t(p,d,{get:h[d],enumerable:!0})},o=(p,h,d,f)=>{if(h&&typeof h=="object"||typeof h=="function")for(let v of r(h))!n.call(p,v)&&v!==d&&t(p,v,{get:()=>h[v],enumerable:!(f=e(h,v))||f.enumerable});return p},a=p=>o(t({},"__esModule",{value:!0}),p),i={};s(i,{getContext:()=>c.getContext,getVercelOidcToken:()=>l,getVercelOidcTokenSync:()=>u}),$u=a(i);var c=uT();async function l(){return""}function u(){return""}return $u}var b2=dT(),pT="vercel.ai.gateway.error",Eu=Symbol.for(pT),k2,S2,At=class k_ extends(S2=Error,k2=Eu,S2){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[k2]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return k_.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&Eu in e&&e[Eu]===!0}},C2="GatewayAuthenticationError",fT=`vercel.ai.gateway.error.${C2}`,T2=Symbol.for(fT),$2,E2,xu=class S_ extends(E2=At,$2=T2,E2){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[$2]=!0,this.name=C2,this.type="authentication_error"}static isInstance(e){return At.hasMarker(e)&&T2 in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
|
|
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,27 +566,27 @@ 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 vw({message:a,statusCode:s,cause:o})}},S_="GatewayInvalidRequestError",f8=`vercel.ai.gateway.error.${S_}`,k_=Symbol.for(f8),C_,T_,m8=class extends(T_=jt,C_=k_,T_){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[C_]=!0,this.name=S_,this.type="invalid_request_error"}static isInstance(t){return jt.hasMarker(t)&&k_ in t}},$_="GatewayRateLimitError",g8=`vercel.ai.gateway.error.${$_}`,E_=Symbol.for(g8),x_,I_,_8=class extends(I_=jt,x_=E_,I_){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[x_]=!0,this.name=$_,this.type="rate_limit_exceeded"}static isInstance(t){return jt.hasMarker(t)&&E_ in t}},R_="GatewayModelNotFoundError",v8=`vercel.ai.gateway.error.${R_}`,P_=Symbol.for(v8),y8=ps(()=>Nn(C({modelId:d()}))),O_,A_,M_=class extends(A_=jt,O_=P_,A_){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[O_]=!0,this.name=R_,this.type="model_not_found",this.modelId=r}static isInstance(t){return jt.hasMarker(t)&&P_ in t}},N_="GatewayInternalServerError",w8=`vercel.ai.gateway.error.${N_}`,L_=Symbol.for(w8),q_,j_,U_=class extends(j_=jt,q_=L_,j_){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[q_]=!0,this.name=N_,this.type="internal_server_error"}static isInstance(t){return jt.hasMarker(t)&&L_ in t}},z_="GatewayResponseError",b8=`vercel.ai.gateway.error.${z_}`,D_=Symbol.for(b8),Z_,V_,S8=class extends(V_=jt,Z_=D_,V_){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:s}={}){super({message:t,statusCode:e,cause:s}),this[Z_]=!0,this.name=z_,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return jt.hasMarker(t)&&D_ in t}};async function F_({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await ir({value:t,schema:k8});if(!o.success)return new S8({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:o.error,cause:n});const a=o.value,i=a.error.type,c=a.error.message;switch(i){case"authentication_error":return Ad.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new m8({message:c,statusCode:e,cause:n});case"rate_limit_exceeded":return new _8({message:c,statusCode:e,cause:n});case"model_not_found":{const l=await ir({value:a.error.param,schema:y8});return new M_({message:c,statusCode:e,modelId:l.success?l.value.modelId:void 0,cause:n})}case"internal_server_error":return new U_({message:c,statusCode:e,cause:n});default:return new U_({message:c,statusCode:e,cause:n})}}var k8=ps(()=>Nn(C({error:C({message:d(),type:d().nullish(),param:he().nullish(),code:ee([d(),M()]).nullish()})})));function an(t,e){var r;return jt.isInstance(t)?t:wt.isInstance(t)?F_({response:C8(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):F_({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function C8(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var H_="ai-gateway-auth-method";async function ms(t){const e=await ir({value:t[H_],schema:T8});return e.success?e.value:void 0}var T8=ps(()=>Nn(ee([O("api-key"),O("oidc")]))),B_=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Xg({url:`${this.config.baseURL}/config`,headers:await wr(this.config.headers()),successfulResponseHandler:fs($8),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await an(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Xg({url:`${t.origin}/v1/credits`,headers:await wr(this.config.headers()),successfulResponseHandler:fs(E8),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await an(t)}}},$8=ps(()=>Nn(C({models:I(C({id:d(),name:d(),description:d().nullish(),pricing:C({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:O("v2"),provider:d(),modelId:d()}),modelType:we(["language","embedding","image"]).nullish()}))}))),E8=ps(()=>Nn(C({balance:d(),total_used:d()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),x8=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await wr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:i}=await hs({url:this.getUrl(),headers:ds(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await wr(this.config.o11yHeaders)),body:e,successfulResponseHandler:fs(mt()),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:e},response:{headers:o,body:i},warnings:r}}catch(o){throw await an(o,await ms(s))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await wr(this.config.headers());try{const{value:o,responseHeaders:a}=await hs({url:this.getUrl(),headers:ds(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await wr(this.config.o11yHeaders)),body:e,successfulResponseHandler:s_(mt()),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,c){if(i.success){const l=i.value;if(l.type==="raw"&&!t.includeRawChunks)return;l.type==="response-metadata"&&l.timestamp&&typeof l.timestamp=="string"&&(l.timestamp=new Date(l.timestamp)),c.enqueue(l)}else c.error(i.error)}})),request:{body:e},response:{headers:a}}}catch(o){throw await an(o,await ms(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},I8=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;const o=await wr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:c}=await hs({url:this.getUrl(),headers:ds(o,e??{},this.getModelConfigHeaders(),await wr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...n?{providerOptions:n}:{}},successfulResponseHandler:fs(R8),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(s=i.usage)!=null?s:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:c}}}catch(a){throw await an(a,await ms(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},R8=ps(()=>Nn(C({embeddings:I(I(M())),usage:C({tokens:M()}).nullish(),providerMetadata:ie(d(),ie(d(),he())).optional()}))),P8=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c;const l=await wr(this.config.headers());try{const{responseHeaders:u,value:h,rawValue:f}=await hs({url:this.getUrl(),headers:ds(l,a??{},this.getModelConfigHeaders(),await wr(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...s&&{seed:s},...o&&{providerOptions:o}},successfulResponseHandler:fs(A8),failedResponseHandler:Mn({errorSchema:mt(),errorToMessage:p=>p}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:h.images,warnings:(c=h.warnings)!=null?c:[],providerMetadata:h.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw an(u,await ms(l))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},O8=C({images:I(he()).optional()}).catchall(he()),A8=C({images:I(d()),warnings:I(C({type:O("other"),message:d()})).optional(),providerMetadata:ie(d(),O8).optional()});async function M8(){var t;return(t=m_.getContext().headers)==null?void 0:t["x-vercel-id"]}var N8="2.0.18",L8="0.0.1";function q8(t={}){var e,r;let n=null,s=null;const o=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let a=0;const i=(r=d_(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",c=async()=>{const m=await U8(t);if(m)return on({Authorization:`Bearer ${m.token}`,"ai-gateway-protocol-version":L8,[H_]:m.authMethod,...t.headers},`ai-sdk/gateway/${N8}`);throw Ad.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{const m=Bi({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=Bi({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=Bi({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await M8();return{...m&&{"ai-o11y-deployment-id":m},...v&&{"ai-o11y-environment":v},..._&&{"ai-o11y-region":_},...w&&{"ai-o11y-request-id":w}}}},u=m=>new x8(m,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),h=async()=>{var m,v,_;const w=(_=(v=(m=t._internal)==null?void 0:m.currentDate)==null?void 0:v.call(m).getTime())!=null?_:Date.now();return(!n||w-a>o)&&(a=w,n=new B_({baseURL:i,headers:c,fetch:t.fetch}).getAvailableModels().then(g=>(s=g,g)).catch(async g=>{throw await an(g,await ms(await c()))})),s?Promise.resolve(s):n},f=async()=>new B_({baseURL:i,headers:c,fetch:t.fetch}).getCredits().catch(async m=>{throw await an(m,await ms(await c()))}),p=function(m){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(m)};return p.getAvailableModels=h,p.getCredits=f,p.imageModel=m=>new P8(m,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),p.languageModel=u,p.textEmbeddingModel=m=>new I8(m,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),p}var j8=q8();async function U8(t){const e=Bi({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await m_.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var z8=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ln="1.9.0",J_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function D8(t){var e=new Set([t]),r=new Set,n=t.match(J_);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function o(i){return r.add(i),!1}function a(i){return e.add(i),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(J_);if(!l)return o(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||s.major!==u.major?o(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?a(c):o(c):s.minor<=u.minor?a(c):o(c)}}var Z8=D8(Ln),V8=Ln.split(".")[0],Ro=Symbol.for("opentelemetry.js.api."+V8),Po=z8;function Oo(t,e,r,n){var s;n===void 0&&(n=!1);var o=Po[Ro]=(s=Po[Ro])!==null&&s!==void 0?s:{version:Ln};if(!n&&o[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(o.version!==Ln){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+Ln);return r.error(a.stack||a.message),!1}return o[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Ln+"."),!0}function qn(t){var e,r,n=(e=Po[Ro])===null||e===void 0?void 0:e.version;if(!(!n||!Z8(n)))return(r=Po[Ro])===null||r===void 0?void 0:r[t]}function Ao(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Ln+".");var r=Po[Ro];r&&delete r[t]}var F8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},H8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},B8=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Mo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Mo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Mo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Mo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Mo("verbose",this._namespace,e)},t})();function Mo(t,e,r){var n=qn("diag");if(n)return r.unshift(e),n[t].apply(n,H8([],F8(r),!1))}var Ut;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Ut||(Ut={}));function J8(t,e){t<Ut.NONE?t=Ut.NONE:t>Ut.ALL&&(t=Ut.ALL),e=e||{};function r(n,s){var o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",Ut.ERROR),warn:r("warn",Ut.WARN),info:r("info",Ut.INFO),debug:r("debug",Ut.DEBUG),verbose:r("verbose",Ut.VERBOSE)}}var W8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},G8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},K8="diag",br=(function(){function t(){function e(s){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var i=qn("diag");if(i)return i[s].apply(i,G8([],W8(o),!1))}}var r=this,n=function(s,o){var a,i,c;if(o===void 0&&(o={logLevel:Ut.INFO}),s===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof o=="number"&&(o={logLevel:o});var u=qn("diag"),h=J8((i=o.logLevel)!==null&&i!==void 0?i:Ut.INFO,s);if(u&&!o.suppressOverrideMessage){var f=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+f),h.warn("Current logger will overwrite one already registered from "+f)}return Oo("diag",h,r,!0)};r.setLogger=n,r.disable=function(){Ao(K8,r)},r.createComponentLogger=function(s){return new B8(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),Y8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},Q8=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},X8=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=Y8(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new t(this._entries);try{for(var a=Q8(n),i=a.next();!i.done;i=a.next()){var c=i.value;o._entries.delete(c)}}catch(l){e={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return o},t.prototype.clear=function(){return new t},t})();br.instance();function eI(t){return t===void 0&&(t={}),new X8(new Map(Object.entries(t)))}function W_(t){return Symbol.for(t)}var tI=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),rI=new tI,jn=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),nI=(function(){function t(){}return t.prototype.createGauge=function(e,r){return hI},t.prototype.createHistogram=function(e,r){return fI},t.prototype.createCounter=function(e,r){return pI},t.prototype.createUpDownCounter=function(e,r){return mI},t.prototype.createObservableGauge=function(e,r){return _I},t.prototype.createObservableCounter=function(e,r){return gI},t.prototype.createObservableUpDownCounter=function(e,r){return vI},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),Ki=(function(){function t(){}return t})(),sI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(Ki),oI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(Ki),aI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(Ki),iI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(Ki),Md=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),cI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Md),lI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Md),uI=(function(t){jn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Md),dI=new nI,pI=new sI,hI=new aI,fI=new iI,mI=new oI,gI=new cI,_I=new lI,vI=new uI,yI={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},wI={set:function(t,e,r){t!=null&&(t[e]=r)}},bI=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},SI=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},kI=(function(){function t(){}return t.prototype.active=function(){return rI},t.prototype.with=function(e,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,SI([n],bI(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),CI=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},TI=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},Nd="context",$I=new kI,Yi=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Oo(Nd,e,br.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(s=this._getContextManager()).with.apply(s,TI([e,r,n],CI(o),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return qn(Nd)||$I},t.prototype.disable=function(){this._getContextManager().disable(),Ao(Nd,br.instance())},t})(),Ld;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Ld||(Ld={}));var G_="0000000000000000",K_="00000000000000000000000000000000",EI={traceId:K_,spanId:G_,traceFlags:Ld.NONE},No=(function(){function t(e){e===void 0&&(e=EI),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})(),qd=W_("OpenTelemetry Context Key SPAN");function jd(t){return t.getValue(qd)||void 0}function xI(){return jd(Yi.getInstance().active())}function Ud(t,e){return t.setValue(qd,e)}function II(t){return t.deleteValue(qd)}function RI(t,e){return Ud(t,new No(e))}function Y_(t){var e;return(e=jd(t))===null||e===void 0?void 0:e.spanContext()}var PI=/^([0-9a-f]{32})$/i,OI=/^[0-9a-f]{16}$/i;function AI(t){return PI.test(t)&&t!==K_}function MI(t){return OI.test(t)&&t!==G_}function Q_(t){return AI(t.traceId)&&MI(t.spanId)}function NI(t){return new No(t)}var zd=Yi.getInstance(),X_=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=zd.active());var s=!!r?.root;if(s)return new No;var o=n&&Y_(n);return LI(o)&&Q_(o)?new No(o):new No},t.prototype.startActiveSpan=function(e,r,n,s){var o,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,a=n,i=s);var c=a??zd.active(),l=this.startSpan(e,o,c),u=Ud(c,l);return zd.with(u,i,void 0,l)}},t})();function LI(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var qI=new X_,jI=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):qI},t})(),UI=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new X_},t})(),zI=new UI,ev=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new jI(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:zI},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})(),Qi;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Qi||(Qi={})),Yi.getInstance(),br.instance();var DI=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return dI},t})(),ZI=new DI,Dd="metrics",VI=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return Oo(Dd,e,br.instance())},t.prototype.getMeterProvider=function(){return qn(Dd)||ZI},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Ao(Dd,br.instance())},t})();VI.getInstance();var FI=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})(),Zd=W_("OpenTelemetry Baggage Key");function tv(t){return t.getValue(Zd)||void 0}function HI(){return tv(Yi.getInstance().active())}function BI(t,e){return t.setValue(Zd,e)}function JI(t){return t.deleteValue(Zd)}var Vd="propagation",WI=new FI,GI=(function(){function t(){this.createBaggage=eI,this.getBaggage=tv,this.getActiveBaggage=HI,this.setBaggage=BI,this.deleteBaggage=JI}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return Oo(Vd,e,br.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=wI),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=yI),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){Ao(Vd,br.instance())},t.prototype._getGlobalPropagator=function(){return qn(Vd)||WI},t})();GI.getInstance();var Fd="trace",KI=(function(){function t(){this._proxyTracerProvider=new ev,this.wrapSpanContext=NI,this.isSpanContextValid=Q_,this.deleteSpan=II,this.getSpan=jd,this.getActiveSpan=xI,this.getSpanContext=Y_,this.setSpan=Ud,this.setSpanContext=RI}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=Oo(Fd,this._proxyTracerProvider,br.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return qn(Fd)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){Ao(Fd,br.instance()),this._proxyTracerProvider=new ev},t})(),YI=KI.getInstance(),QI=Object.defineProperty,XI=(t,e)=>{for(var r in e)QI(t,r,{get:e[r],enumerable:!0})},rv="AI_NoOutputSpecifiedError",nv=`vercel.ai.error.${rv}`,e7=Symbol.for(nv),sv,ov=class extends Se{constructor({message:t="No output specified."}={}){super({name:rv,message:t}),this[sv]=!0}static isInstance(t){return Se.hasMarker(t,nv)}};sv=e7;function t7(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let n=`${e} The tool "${r}" is not supported by this model`;return t.details&&(n+=` - ${t.details}`),n}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var r7="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",av=!1,iv=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}av||(av=!0,console.info(r7));for(const r of t)console.warn(t7(r))}},cv="AI_InvalidArgumentError",lv=`vercel.ai.error.${cv}`,n7=Symbol.for(lv),uv,Sr=class extends Se{constructor({parameter:e,value:r,message:n}){super({name:cv,message:`Invalid argument for parameter ${e}: ${n}`}),this[uv]=!0,this.parameter=e,this.value=r}static isInstance(e){return Se.hasMarker(e,lv)}};uv=n7;var dv="AI_InvalidToolInputError",pv=`vercel.ai.error.${dv}`,s7=Symbol.for(pv),hv,fv=class extends Se{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${ls(r)}`}){super({name:dv,message:n,cause:r}),this[hv]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return Se.hasMarker(t,pv)}};hv=s7;var mv="AI_NoObjectGeneratedError",gv=`vercel.ai.error.${mv}`,o7=Symbol.for(gv),_v,vv=class extends Se{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s,finishReason:o}){super({name:mv,message:t,cause:e}),this[_v]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(t){return Se.hasMarker(t,gv)}};_v=o7;var yv="AI_NoOutputGeneratedError",wv=`vercel.ai.error.${yv}`,a7=Symbol.for(wv),bv,i7=class extends Se{constructor({message:t="No output generated.",cause:e}={}){super({name:yv,message:t,cause:e}),this[bv]=!0}static isInstance(t){return Se.hasMarker(t,wv)}};bv=a7;var Sv="AI_NoSuchToolError",kv=`vercel.ai.error.${Sv}`,c7=Symbol.for(kv),Cv,Hd=class extends Se{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:Sv,message:r}),this[Cv]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return Se.hasMarker(t,kv)}};Cv=c7;var Tv="AI_ToolCallRepairError",$v=`vercel.ai.error.${Tv}`,l7=Symbol.for($v),Ev,u7=class extends Se{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${ls(t)}`}){super({name:Tv,message:r,cause:t}),this[Ev]=!0,this.originalError=e}static isInstance(t){return Se.hasMarker(t,$v)}};Ev=l7;var d7=class extends Se{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},xv="AI_InvalidMessageRoleError",Iv=`vercel.ai.error.${xv}`,p7=Symbol.for(Iv),Rv,h7=class extends Se{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:xv,message:e}),this[Rv]=!0,this.role=t}static isInstance(t){return Se.hasMarker(t,Iv)}};Rv=p7;var Pv="AI_DownloadError",Ov=`vercel.ai.error.${Pv}`,f7=Symbol.for(Ov),Av,Bd=class extends Se{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Pv,message:s,cause:n}),this[Av]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return Se.hasMarker(t,Ov)}};Av=f7;var Mv="AI_RetryError",Nv=`vercel.ai.error.${Mv}`,m7=Symbol.for(Nv),Lv,qv=class extends Se{constructor({message:t,reason:e,errors:r}){super({name:Mv,message:t}),this[Lv]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Se.hasMarker(t,Nv)}};Lv=m7;function Xi(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new d7({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return g7().languageModel(t)}function g7(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:j8}var _7=[{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]}],v7=t=>{const e=typeof t=="string"?Id(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function y7(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?v7(t):t}function w7({data:t,signatures:e}){const r=y7(t),n=typeof r=="string"?Id(r.substring(0,Math.min(r.length,24))):r;for(const s of e)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,a)=>o===null||n[a]===o))return s.mediaType}var jv="5.0.106",b7=async({url:t})=>{var e;const r=t.toString();try{const n=await fetch(r,{headers:on({},`ai-sdk/${jv}`,xo())});if(!n.ok)throw new Bd({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw Bd.isInstance(n)?n:new Bd({url:r,cause:n})}},S7=(t=b7)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function k7(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Uv=ee([d(),Qa(Uint8Array),Qa(ArrayBuffer),tl(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function zv(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=k7(t.toString());if(e==null||r==null)throw new Se({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function C7(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Gi(new Uint8Array(t)):Gi(t)}async function Dv({prompt:t,supportedUrls:e,download:r=S7()}){const n=await $7(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(s=>T7({message:s,downloadedAssets:n}))]}function T7({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>E7(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:a}=zv(n.data);return{type:"file",data:o,filename:n.filename,mediaType:a??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:t.providerOptions};default:{const n=r;throw new h7({role:n})}}}async function $7(t,e,r){const n=t.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const i=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let c=o.type==="image"?o.image:o.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:i,data:c}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&rx({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await e(n);return Object.fromEntries(s.map((o,a)=>o==null?null:[n[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function E7(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n;const s=t.type;switch(s){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:a}=zv(n);let i=a??t.mediaType,c=o;if(c instanceof URL){const l=e[c.toString()];l&&(c=l.data,i??(i=l.mediaType))}switch(s){case"image":return(c instanceof Uint8Array||typeof c=="string")&&(i=(r=w7({data:c,signatures:_7}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:c,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:c,providerOptions:t.providerOptions}}}}function Jd({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:a,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new Sr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new Sr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new Sr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Sr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Sr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new Sr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new Sr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Sr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:i,seed:a}}function x7(t){return t!=null&&Object.keys(t).length>0}function Zv({tools:t,toolChoice:e,activeTools:r}){return x7(t)?{tools:(r!=null?Object.entries(t).filter(([s])=>r.includes(s)):Object.entries(t)).map(([s,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:Wi(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var Lo=um(()=>ee([Yc(),d(),M(),ne(),ie(d(),Lo),I(Lo)])),kr=ie(d(),ie(d(),Lo)),Vv=C({type:O("text"),text:d(),providerOptions:kr.optional()}),I7=C({type:O("image"),image:ee([Uv,Qa(URL)]),mediaType:d().optional(),providerOptions:kr.optional()}),Fv=C({type:O("file"),data:ee([Uv,Qa(URL)]),filename:d().optional(),mediaType:d(),providerOptions:kr.optional()}),R7=C({type:O("reasoning"),text:d(),providerOptions:kr.optional()}),P7=C({type:O("tool-call"),toolCallId:d(),toolName:d(),input:he(),providerOptions:kr.optional(),providerExecuted:ne().optional()}),O7=Xe("type",[C({type:O("text"),value:d()}),C({type:O("json"),value:Lo}),C({type:O("error-text"),value:d()}),C({type:O("error-json"),value:Lo}),C({type:O("content"),value:I(ee([C({type:O("text"),text:d()}),C({type:O("media"),data:d(),mediaType:d()})]))})]),Hv=C({type:O("tool-result"),toolCallId:d(),toolName:d(),output:O7,providerOptions:kr.optional()}),A7=C({role:O("system"),content:d(),providerOptions:kr.optional()}),M7=C({role:O("user"),content:ee([d(),I(ee([Vv,I7,Fv]))]),providerOptions:kr.optional()}),N7=C({role:O("assistant"),content:ee([d(),I(ee([Vv,Fv,R7,P7,Hv]))]),providerOptions:kr.optional()}),L7=C({role:O("tool"),content:I(Hv),providerOptions:kr.optional()}),q7=ee([A7,M7,N7,L7]);async function Bv(t){if(t.prompt==null&&t.messages==null)throw new us({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new us({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new us({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new us({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new us({prompt:t,message:"messages must not be empty"});const r=await ir({value:e,schema:I(q7)});if(!r.success)throw new us({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Jv(t){return Ad.isInstance(t)||M_.isInstance(t)?new Se({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function gs({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function Wv({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((o,[a,i])=>(o[`ai.settings.${a}`]=i,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[a,i])=>(o[`ai.telemetry.metadata.${a}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[a,i])=>(i!==void 0&&(o[`ai.request.headers.${a}`]=i),o),{})}}var j7={startSpan(){return ec},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(ec);if(typeof r=="function")return r(ec);if(typeof n=="function")return n(ec)}},ec={spanContext(){return U7},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}},U7={traceId:"",spanId:"",traceFlags:0};function Gv({isEnabled:t=!1,tracer:e}={}){return t?e||YI.getTracer("ai"):j7}function _s({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async o=>{try{const a=await n(o);return s&&o.end(),a}catch(a){try{Wd(o,a)}finally{o.end()}throw a}})}function Wd(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:Qi.ERROR,message:e.message})):t.setStatus({code:Qi.ERROR})}function Bt({telemetry:t,attributes:e}){return t?.isEnabled!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(t?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(t?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function Kv(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?C7(r.data):r.data}:r)})))}function Yv(t,e){return{inputTokens:qo(t.inputTokens,e.inputTokens),outputTokens:qo(t.outputTokens,e.outputTokens),totalTokens:qo(t.totalTokens,e.totalTokens),reasoningTokens:qo(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:qo(t.cachedInputTokens,e.cachedInputTokens)}}function qo(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function Gd(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function z7({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let n;const s=r["retry-after-ms"];if(s){const a=parseFloat(s);Number.isNaN(a)||(n=a)}const o=r["retry-after"];if(o&&n===void 0){const a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var D7=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>Qv(s,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function Qv(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:s},o=[]){try{return await t()}catch(a){if(On(a)||e===0)throw a;const i=Sd(a),c=[...o,a],l=c.length;if(l>e)throw new qv({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:c});if(a instanceof Error&&wt.isInstance(a)&&a.isRetryable===!0&&l<=e)return await QE(z7({error:a,exponentialBackoffDelay:r}),{abortSignal:s}),Qv(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:s},c);throw l===1?a:new qv({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:c})}}function Xv({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new Sr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new Sr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:D7({maxRetries:r,abortSignal:e})}}function ey(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var ty=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Gi(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Id(this.base64Data)),this.uint8ArrayData}},Z7=class extends ty{constructor(t){super(t),this.type="file"}};async function ry({toolCall:t,tools:e,repairToolCall:r,system:n,messages:s}){try{if(e==null)throw new Hd({toolName:t.toolName});try{return await ny({toolCall:t,tools:e})}catch(o){if(r==null||!(Hd.isInstance(o)||fv.isInstance(o)))throw o;let a=null;try{a=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:c}=e[i];return Wi(c).jsonSchema},system:n,messages:s,error:o})}catch(i){throw new u7({cause:i,originalError:o})}if(a==null)throw o;return await ny({toolCall:a,tools:e})}}catch(o){const a=await An({text:t.input}),i=a.success?a.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:o,providerMetadata:t.providerMetadata}}}async function ny({toolCall:t,tools:e}){const r=t.toolName,n=e[r];if(n==null)throw new Hd({toolName:t.toolName,availableTools:Object.keys(e)});const s=Wi(n.inputSchema),o=t.input.trim()===""?await ir({value:{},schema:s}):await An({text:t.input,schema:s});if(o.success===!1)throw new fv({toolName:r,toolInput:t.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var sy=class{constructor({content:t,finishReason:e,usage:r,warnings:n,request:s,response:o,providerMetadata:a}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=a}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function Kd(t){return({steps:e})=>e.length===t}async function oy({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function Yd({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:ls(t)}:r==="json"?{type:"error-json",value:ay(t)}:e?.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:ay(t)}}function ay(t){return t===void 0?null:t}function Qd({content:t,tools:e}){const r=[],n=t.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Yd({tool:e?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Yd({tool:e?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=t.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Yd({tool:e?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"}),...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}}));return s.length>0&&r.push({role:"tool",content:s}),r}var V7=$o({prefix:"aitxt",size:24});async function iy({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Kd(1),experimental_output:u,experimental_telemetry:h,providerOptions:f,experimental_activeTools:p,activeTools:m=p,experimental_prepareStep:v,prepareStep:_=v,experimental_repairToolCall:w,experimental_download:g,experimental_context:y,_internal:{generateId:b=V7,currentDate:S=()=>new Date}={},onStepFinish:k,...T}){const x=Xi(t),P=Gd(l),{maxRetries:q,retry:N}=Xv({maxRetries:a,abortSignal:i}),z=Jd(T),D=on(c??{},`ai/${jv}`),F=Wv({model:x,telemetry:h,headers:D,settings:{...z,maxRetries:q}}),oe=await Bv({system:n,prompt:s,messages:o}),fe=Gv(h);try{return await _s({name:"ai.generateText",attributes:Bt({telemetry:h,attributes:{...gs({operationId:"ai.generateText",telemetry:h}),...F,"ai.model.provider":x.provider,"ai.model.id":x.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:s,messages:o})}}}),tracer:fe,fn:async de=>{var se,_e,H,A,V,j,E;const R=Jd(T);let $,B=[],G=[];const ve=[],pe=[];do{const W=[...oe.messages,...ve],K=await _?.({model:x,steps:pe,stepNumber:pe.length,messages:W}),X=Xi((se=K?.model)!=null?se:x),ue=await Dv({prompt:{system:(_e=K?.system)!=null?_e:oe.system,messages:(H=K?.messages)!=null?H:W},supportedUrls:await X.supportedUrls,download:g}),{toolChoice:me,tools:Je}=Zv({tools:e,toolChoice:(A=K?.toolChoice)!=null?A:r,activeTools:(V=K?.activeTools)!=null?V:m});$=await N(()=>{var Ie;return _s({name:"ai.generateText.doGenerate",attributes:Bt({telemetry:h,attributes:{...gs({operationId:"ai.generateText.doGenerate",telemetry:h}),...F,"ai.model.provider":X.provider,"ai.model.id":X.modelId,"ai.prompt.messages":{input:()=>Kv(ue)},"ai.prompt.tools":{input:()=>Je?.map(Pt=>JSON.stringify(Pt))},"ai.prompt.toolChoice":{input:()=>me!=null?JSON.stringify(me):void 0},"gen_ai.system":X.provider,"gen_ai.request.model":X.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(Ie=T.temperature)!=null?Ie:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:fe,fn:async Pt=>{var zr,Ot,pt,Wt,un,dn,ks,mc;const st=await X.doGenerate({...R,tools:Je,toolChoice:me,responseFormat:u?.responseFormat,prompt:ue,providerOptions:f,abortSignal:i,headers:D}),Dr={id:(Ot=(zr=st.response)==null?void 0:zr.id)!=null?Ot:b(),timestamp:(Wt=(pt=st.response)==null?void 0:pt.timestamp)!=null?Wt:S(),modelId:(dn=(un=st.response)==null?void 0:un.modelId)!=null?dn:X.modelId,headers:(ks=st.response)==null?void 0:ks.headers,body:(mc=st.response)==null?void 0:mc.body};return Pt.setAttributes(Bt({telemetry:h,attributes:{"ai.response.finishReason":st.finishReason,"ai.response.text":{output:()=>ey(st.content)},"ai.response.toolCalls":{output:()=>{const Zr=cy(st.content);return Zr==null?void 0:JSON.stringify(Zr)}},"ai.response.id":Dr.id,"ai.response.model":Dr.modelId,"ai.response.timestamp":Dr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(st.providerMetadata),"ai.usage.promptTokens":st.usage.inputTokens,"ai.usage.completionTokens":st.usage.outputTokens,"gen_ai.response.finish_reasons":[st.finishReason],"gen_ai.response.id":Dr.id,"gen_ai.response.model":Dr.modelId,"gen_ai.usage.input_tokens":st.usage.inputTokens,"gen_ai.usage.output_tokens":st.usage.outputTokens}})),{...st,response:Dr}}})});const Ge=await Promise.all($.content.filter(Ie=>Ie.type==="tool-call").map(Ie=>ry({toolCall:Ie,tools:e,repairToolCall:w,system:n,messages:W})));for(const Ie of Ge){if(Ie.invalid)continue;const Pt=e[Ie.toolName];Pt?.onInputAvailable!=null&&await Pt.onInputAvailable({input:Ie.input,toolCallId:Ie.toolCallId,messages:W,abortSignal:i,experimental_context:y})}const te=Ge.filter(Ie=>Ie.invalid&&Ie.dynamic);G=[];for(const Ie of te)G.push({type:"tool-error",toolCallId:Ie.toolCallId,toolName:Ie.toolName,input:Ie.input,error:Sd(Ie.error),dynamic:!0});B=Ge.filter(Ie=>!Ie.providerExecuted),e!=null&&G.push(...await F7({toolCalls:B.filter(Ie=>!Ie.invalid),tools:e,tracer:fe,telemetry:h,messages:W,abortSignal:i,experimental_context:y}));const ke=B7({content:$.content,toolCalls:Ge,toolOutputs:G});ve.push(...Qd({content:ke,tools:e}));const Ct=new sy({content:ke,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(j=$.request)!=null?j:{},response:{...$.response,messages:structuredClone(ve)}});iv((E=$.warnings)!=null?E:[]),pe.push(Ct),await k?.(Ct)}while(B.length>0&&G.length===B.length&&!await oy({stopConditions:P,steps:pe}));de.setAttributes(Bt({telemetry:h,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>ey($.content)},"ai.response.toolCalls":{output:()=>{const W=cy($.content);return W==null?void 0:JSON.stringify(W)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const L=pe[pe.length-1];let Z;return L.finishReason==="stop"&&(Z=await u?.parseOutput({text:L.text},{response:L.response,usage:L.usage,finishReason:L.finishReason})),new H7({steps:pe,resolvedOutput:Z})}})}catch(de){throw Jv(de)}}async function F7({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:o,experimental_context:a}){return(await Promise.all(t.map(async({toolCallId:c,toolName:l,input:u})=>{const h=e[l];if(h?.execute!=null)return _s({name:"ai.toolCall",attributes:Bt({telemetry:n,attributes:{...gs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async f=>{try{const p=p_({execute:h.execute.bind(h),input:u,options:{toolCallId:c,messages:s,abortSignal:o,experimental_context:a}});let m;for await(const v of p)v.type==="final"&&(m=v.output);try{f.setAttributes(Bt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(m)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:u,output:m,dynamic:h.type==="dynamic"}}catch(p){return Wd(f,p),{type:"tool-error",toolCallId:c,toolName:l,input:u,error:p,dynamic:h.type==="dynamic"}}}})}))).filter(c=>c!=null)}var H7=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Yv(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new ov;return this.resolvedOutput}};function cy(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function B7({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new ty(n)};case"tool-call":return e.find(s=>s.toolCallId===n.toolCallId);case"tool-result":{const s=e.find(o=>o.toolCallId===n.toolCallId);if(s==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,error:n.result,providerExecuted:!0,dynamic:s.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,output:n.result,providerExecuted:!0,dynamic:s.dynamic}}}}),...r]}function tc(t,e){const r=new Headers(t??{});for(const[n,s]of Object.entries(e))r.has(n)||r.set(n,s);return r}function J7({status:t,statusText:e,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:tc(r,{"content-type":"text/plain; charset=utf-8"})})}function ly({response:t,status:e,statusText:r,headers:n,stream:s}){t.writeHead(e??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:i,value:c}=await o.read();if(i)break;t.write(c)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function W7({response:t,status:e,statusText:r,headers:n,textStream:s}){ly({response:t,status:e,statusText:r,headers:Object.fromEntries(tc(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var uy=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
|
|
569
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new S_({message:a,statusCode:s,cause:o})}},x2="GatewayInvalidRequestError",hT=`vercel.ai.gateway.error.${x2}`,I2=Symbol.for(hT),R2,P2,mT=class extends(P2=At,R2=I2,P2){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[R2]=!0,this.name=x2,this.type="invalid_request_error"}static isInstance(t){return At.hasMarker(t)&&I2 in t}},O2="GatewayRateLimitError",gT=`vercel.ai.gateway.error.${O2}`,A2=Symbol.for(gT),M2,N2,yT=class extends(N2=At,M2=A2,N2){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[M2]=!0,this.name=O2,this.type="rate_limit_exceeded"}static isInstance(t){return At.hasMarker(t)&&A2 in t}},L2="GatewayModelNotFoundError",_T=`vercel.ai.gateway.error.${L2}`,j2=Symbol.for(_T),vT=es(()=>kn(T({modelId:m()}))),q2,z2,D2=class extends(z2=At,q2=j2,z2){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[q2]=!0,this.name=L2,this.type="model_not_found",this.modelId=r}static isInstance(t){return At.hasMarker(t)&&j2 in t}},U2="GatewayInternalServerError",wT=`vercel.ai.gateway.error.${U2}`,Z2=Symbol.for(wT),F2,V2,H2=class extends(V2=At,F2=Z2,V2){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[F2]=!0,this.name=U2,this.type="internal_server_error"}static isInstance(t){return At.hasMarker(t)&&Z2 in t}},B2="GatewayResponseError",bT=`vercel.ai.gateway.error.${B2}`,J2=Symbol.for(bT),W2,G2,kT=class extends(G2=At,W2=J2,G2){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:s}={}){super({message:t,statusCode:e,cause:s}),this[W2]=!0,this.name=B2,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return At.hasMarker(t)&&J2 in t}};async function K2({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await er({value:t,schema:ST});if(!o.success)return new kT({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:o.error,cause:n});const a=o.value,i=a.error.type,c=a.error.message;switch(i){case"authentication_error":return xu.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new mT({message:c,statusCode:e,cause:n});case"rate_limit_exceeded":return new yT({message:c,statusCode:e,cause:n});case"model_not_found":{const l=await er({value:a.error.param,schema:vT});return new D2({message:c,statusCode:e,modelId:l.success?l.value.modelId:void 0,cause:n})}case"internal_server_error":return new H2({message:c,statusCode:e,cause:n});default:return new H2({message:c,statusCode:e,cause:n})}}var ST=es(()=>kn(T({error:T({message:m(),type:m().nullish(),param:Pe().nullish(),code:ie([m(),N()]).nullish()})})));function Yr(t,e){var r;return At.isInstance(t)?t:gt.isInstance(t)?K2({response:CT(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):K2({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function CT(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var Y2="ai-gateway-auth-method";async function ns(t){const e=await er({value:t[Y2],schema:TT});return e.success?e.value:void 0}var TT=es(()=>kn(ie([L("api-key"),L("oidc")]))),Q2=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await o2({url:`${this.config.baseURL}/config`,headers:await dr(this.config.headers()),successfulResponseHandler:rs($T),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Yr(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await o2({url:`${t.origin}/v1/credits`,headers:await dr(this.config.headers()),successfulResponseHandler:rs(ET),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Yr(t)}}},$T=es(()=>kn(T({models:M(T({id:m(),name:m(),description:m().nullish(),pricing:T({input:m(),output:m(),input_cache_read:m().nullish(),input_cache_write:m().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:L("v2"),provider:m(),modelId:m()}),modelType:xe(["language","embedding","image"]).nullish()}))}))),ET=es(()=>kn(T({balance:m(),total_used:m()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),xT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await dr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:i}=await ts({url:this.getUrl(),headers:Xn(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await dr(this.config.o11yHeaders)),body:e,successfulResponseHandler:rs(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:e},response:{headers:o,body:i},warnings:r}}catch(o){throw await Yr(o,await ns(s))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await dr(this.config.headers());try{const{value:o,responseHeaders:a}=await ts({url:this.getUrl(),headers:Xn(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await dr(this.config.o11yHeaders)),body:e,successfulResponseHandler:u2(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,c){if(i.success){const l=i.value;if(l.type==="raw"&&!t.includeRawChunks)return;l.type==="response-metadata"&&l.timestamp&&typeof l.timestamp=="string"&&(l.timestamp=new Date(l.timestamp)),c.enqueue(l)}else c.error(i.error)}})),request:{body:e},response:{headers:a}}}catch(o){throw await Yr(o,await ns(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},IT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;const o=await dr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:c}=await ts({url:this.getUrl(),headers:Xn(o,e??{},this.getModelConfigHeaders(),await dr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...n?{providerOptions:n}:{}},successfulResponseHandler:rs(RT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(s=i.usage)!=null?s:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:c}}}catch(a){throw await Yr(a,await ns(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},RT=es(()=>kn(T({embeddings:M(M(N())),usage:T({tokens:N()}).nullish(),providerMetadata:be(m(),be(m(),Pe())).optional()}))),PT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c;const l=await dr(this.config.headers());try{const{responseHeaders:u,value:p,rawValue:h}=await ts({url:this.getUrl(),headers:Xn(l,a??{},this.getModelConfigHeaders(),await dr(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...s&&{seed:s},...o&&{providerOptions:o}},successfulResponseHandler:rs(AT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:p.images,warnings:(c=p.warnings)!=null?c:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw Yr(u,await ns(l))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},OT=T({images:M(Pe()).optional()}).catchall(Pe()),AT=T({images:M(m()),warnings:M(T({type:L("other"),message:m()})).optional(),providerMetadata:be(m(),OT).optional()});async function MT(){var t;return(t=b2.getContext().headers)==null?void 0:t["x-vercel-id"]}var NT="2.0.18",LT="0.0.1";function jT(t={}){var e,r;let n=null,s=null;const o=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let a=0;const i=(r=y2(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",c=async()=>{const f=await zT(t);if(f)return Kr({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":LT,[Y2]:f.authMethod,...t.headers},`ai-sdk/gateway/${NT}`);throw xu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{const f=mi({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=mi({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=mi({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await MT();return{...f&&{"ai-o11y-deployment-id":f},...v&&{"ai-o11y-environment":v},...y&&{"ai-o11y-region":y},...w&&{"ai-o11y-request-id":w}}}},u=f=>new xT(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),p=async()=>{var f,v,y;const w=(y=(v=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:v.call(f).getTime())!=null?y:Date.now();return(!n||w-a>o)&&(a=w,n=new Q2({baseURL:i,headers:c,fetch:t.fetch}).getAvailableModels().then(g=>(s=g,g)).catch(async g=>{throw await Yr(g,await ns(await c()))})),s?Promise.resolve(s):n},h=async()=>new Q2({baseURL:i,headers:c,fetch:t.fetch}).getCredits().catch(async f=>{throw await Yr(f,await ns(await c()))}),d=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(f)};return d.getAvailableModels=p,d.getCredits=h,d.imageModel=f=>new PT(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),d.languageModel=u,d.textEmbeddingModel=f=>new IT(f,{provider:"gateway",baseURL:i,headers:c,fetch:t.fetch,o11yHeaders:l()}),d}var qT=jT();async function zT(t){const e=mi({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await b2.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var DT=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Sn="1.9.0",X2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function UT(t){var e=new Set([t]),r=new Set,n=t.match(X2);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function o(i){return r.add(i),!1}function a(i){return e.add(i),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(X2);if(!l)return o(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||s.major!==u.major?o(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?a(c):o(c):s.minor<=u.minor?a(c):o(c)}}var ZT=UT(Sn),FT=Sn.split(".")[0],mo=Symbol.for("opentelemetry.js.api."+FT),go=DT;function yo(t,e,r,n){var s;n===void 0&&(n=!1);var o=go[mo]=(s=go[mo])!==null&&s!==void 0?s:{version:Sn};if(!n&&o[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(o.version!==Sn){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+Sn);return r.error(a.stack||a.message),!1}return o[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Sn+"."),!0}function Cn(t){var e,r,n=(e=go[mo])===null||e===void 0?void 0:e.version;if(!(!n||!ZT(n)))return(r=go[mo])===null||r===void 0?void 0:r[t]}function _o(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Sn+".");var r=go[mo];r&&delete r[t]}var VT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},HT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},BT=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return vo("verbose",this._namespace,e)},t})();function vo(t,e,r){var n=Cn("diag");if(n)return r.unshift(e),n[t].apply(n,HT([],VT(r),!1))}var Mt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Mt||(Mt={}));function JT(t,e){t<Mt.NONE?t=Mt.NONE:t>Mt.ALL&&(t=Mt.ALL),e=e||{};function r(n,s){var o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",Mt.ERROR),warn:r("warn",Mt.WARN),info:r("info",Mt.INFO),debug:r("debug",Mt.DEBUG),verbose:r("verbose",Mt.VERBOSE)}}var WT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},GT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},KT="diag",pr=(function(){function t(){function e(s){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var i=Cn("diag");if(i)return i[s].apply(i,GT([],WT(o),!1))}}var r=this,n=function(s,o){var a,i,c;if(o===void 0&&(o={logLevel:Mt.INFO}),s===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof o=="number"&&(o={logLevel:o});var u=Cn("diag"),p=JT((i=o.logLevel)!==null&&i!==void 0?i:Mt.INFO,s);if(u&&!o.suppressOverrideMessage){var h=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return yo("diag",p,r,!0)};r.setLogger=n,r.disable=function(){_o(KT,r)},r.createComponentLogger=function(s){return new BT(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),YT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},QT=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},XT=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=YT(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new t(this._entries);try{for(var a=QT(n),i=a.next();!i.done;i=a.next()){var c=i.value;o._entries.delete(c)}}catch(l){e={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return o},t.prototype.clear=function(){return new t},t})();pr.instance();function e8(t){return t===void 0&&(t={}),new XT(new Map(Object.entries(t)))}function eg(t){return Symbol.for(t)}var t8=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),r8=new t8,Tn=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),n8=(function(){function t(){}return t.prototype.createGauge=function(e,r){return f8},t.prototype.createHistogram=function(e,r){return h8},t.prototype.createCounter=function(e,r){return p8},t.prototype.createUpDownCounter=function(e,r){return m8},t.prototype.createObservableGauge=function(e,r){return y8},t.prototype.createObservableCounter=function(e,r){return g8},t.prototype.createObservableUpDownCounter=function(e,r){return _8},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),vi=(function(){function t(){}return t})(),s8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(vi),o8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(vi),a8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(vi),i8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(vi),Iu=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),c8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Iu),l8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Iu),u8=(function(t){Tn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(Iu),d8=new n8,p8=new s8,f8=new a8,h8=new i8,m8=new o8,g8=new c8,y8=new l8,_8=new u8,v8={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},w8={set:function(t,e,r){t!=null&&(t[e]=r)}},b8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},k8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},S8=(function(){function t(){}return t.prototype.active=function(){return r8},t.prototype.with=function(e,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,k8([n],b8(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),C8=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},T8=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},Ru="context",$8=new S8,wi=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return yo(Ru,e,pr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(s=this._getContextManager()).with.apply(s,T8([e,r,n],C8(o),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Cn(Ru)||$8},t.prototype.disable=function(){this._getContextManager().disable(),_o(Ru,pr.instance())},t})(),Pu;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Pu||(Pu={}));var tg="0000000000000000",rg="00000000000000000000000000000000",E8={traceId:rg,spanId:tg,traceFlags:Pu.NONE},wo=(function(){function t(e){e===void 0&&(e=E8),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})(),Ou=eg("OpenTelemetry Context Key SPAN");function Au(t){return t.getValue(Ou)||void 0}function x8(){return Au(wi.getInstance().active())}function Mu(t,e){return t.setValue(Ou,e)}function I8(t){return t.deleteValue(Ou)}function R8(t,e){return Mu(t,new wo(e))}function ng(t){var e;return(e=Au(t))===null||e===void 0?void 0:e.spanContext()}var P8=/^([0-9a-f]{32})$/i,O8=/^[0-9a-f]{16}$/i;function A8(t){return P8.test(t)&&t!==rg}function M8(t){return O8.test(t)&&t!==tg}function sg(t){return A8(t.traceId)&&M8(t.spanId)}function N8(t){return new wo(t)}var Nu=wi.getInstance(),og=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Nu.active());var s=!!r?.root;if(s)return new wo;var o=n&&ng(n);return L8(o)&&sg(o)?new wo(o):new wo},t.prototype.startActiveSpan=function(e,r,n,s){var o,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,a=n,i=s);var c=a??Nu.active(),l=this.startSpan(e,o,c),u=Mu(c,l);return Nu.with(u,i,void 0,l)}},t})();function L8(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var j8=new og,q8=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):j8},t})(),z8=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new og},t})(),D8=new z8,ag=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new q8(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:D8},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})(),bi;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(bi||(bi={})),wi.getInstance(),pr.instance();var U8=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return d8},t})(),Z8=new U8,Lu="metrics",F8=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return yo(Lu,e,pr.instance())},t.prototype.getMeterProvider=function(){return Cn(Lu)||Z8},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){_o(Lu,pr.instance())},t})();F8.getInstance();var V8=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})(),ju=eg("OpenTelemetry Baggage Key");function ig(t){return t.getValue(ju)||void 0}function H8(){return ig(wi.getInstance().active())}function B8(t,e){return t.setValue(ju,e)}function J8(t){return t.deleteValue(ju)}var qu="propagation",W8=new V8,G8=(function(){function t(){this.createBaggage=e8,this.getBaggage=ig,this.getActiveBaggage=H8,this.setBaggage=B8,this.deleteBaggage=J8}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return yo(qu,e,pr.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=w8),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=v8),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){_o(qu,pr.instance())},t.prototype._getGlobalPropagator=function(){return Cn(qu)||W8},t})();G8.getInstance();var zu="trace",K8=(function(){function t(){this._proxyTracerProvider=new ag,this.wrapSpanContext=N8,this.isSpanContextValid=sg,this.deleteSpan=I8,this.getSpan=Au,this.getActiveSpan=x8,this.getSpanContext=ng,this.setSpan=Mu,this.setSpanContext=R8}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=yo(zu,this._proxyTracerProvider,pr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Cn(zu)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){_o(zu,pr.instance()),this._proxyTracerProvider=new ag},t})(),Y8=K8.getInstance(),Q8=Object.defineProperty,X8=(t,e)=>{for(var r in e)Q8(t,r,{get:e[r],enumerable:!0})},cg="AI_NoOutputSpecifiedError",lg=`vercel.ai.error.${cg}`,e$=Symbol.for(lg),ug,dg=class extends we{constructor({message:t="No output specified."}={}){super({name:cg,message:t}),this[ug]=!0}static isInstance(t){return we.hasMarker(t,lg)}};ug=e$;function t$(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let n=`${e} The tool "${r}" is not supported by this model`;return t.details&&(n+=` - ${t.details}`),n}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var r$="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",pg=!1,fg=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}pg||(pg=!0,console.info(r$));for(const r of t)console.warn(t$(r))}},hg="AI_InvalidArgumentError",mg=`vercel.ai.error.${hg}`,n$=Symbol.for(mg),gg,fr=class extends we{constructor({parameter:e,value:r,message:n}){super({name:hg,message:`Invalid argument for parameter ${e}: ${n}`}),this[gg]=!0,this.parameter=e,this.value=r}static isInstance(e){return we.hasMarker(e,mg)}};gg=n$;var yg="AI_InvalidToolInputError",_g=`vercel.ai.error.${yg}`,s$=Symbol.for(_g),vg,wg=class extends we{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Yn(r)}`}){super({name:yg,message:n,cause:r}),this[vg]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return we.hasMarker(t,_g)}};vg=s$;var bg="AI_NoObjectGeneratedError",kg=`vercel.ai.error.${bg}`,o$=Symbol.for(kg),Sg,Cg=class extends we{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s,finishReason:o}){super({name:bg,message:t,cause:e}),this[Sg]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(t){return we.hasMarker(t,kg)}};Sg=o$;var Tg="AI_NoOutputGeneratedError",$g=`vercel.ai.error.${Tg}`,a$=Symbol.for($g),Eg,i$=class extends we{constructor({message:t="No output generated.",cause:e}={}){super({name:Tg,message:t,cause:e}),this[Eg]=!0}static isInstance(t){return we.hasMarker(t,$g)}};Eg=a$;var xg="AI_NoSuchToolError",Ig=`vercel.ai.error.${xg}`,c$=Symbol.for(Ig),Rg,Du=class extends we{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:xg,message:r}),this[Rg]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return we.hasMarker(t,Ig)}};Rg=c$;var Pg="AI_ToolCallRepairError",Og=`vercel.ai.error.${Pg}`,l$=Symbol.for(Og),Ag,u$=class extends we{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Yn(t)}`}){super({name:Pg,message:r,cause:t}),this[Ag]=!0,this.originalError=e}static isInstance(t){return we.hasMarker(t,Og)}};Ag=l$;var d$=class extends we{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Mg="AI_InvalidMessageRoleError",Ng=`vercel.ai.error.${Mg}`,p$=Symbol.for(Ng),Lg,f$=class extends we{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Mg,message:e}),this[Lg]=!0,this.role=t}static isInstance(t){return we.hasMarker(t,Ng)}};Lg=p$;var jg="AI_DownloadError",qg=`vercel.ai.error.${jg}`,h$=Symbol.for(qg),zg,Uu=class extends we{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:jg,message:s,cause:n}),this[zg]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return we.hasMarker(t,qg)}};zg=h$;var Dg="AI_RetryError",Ug=`vercel.ai.error.${Dg}`,m$=Symbol.for(Ug),Zg,Fg=class extends we{constructor({message:t,reason:e,errors:r}){super({name:Dg,message:t}),this[Zg]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return we.hasMarker(t,Ug)}};Zg=m$;function ki(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new d$({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return g$().languageModel(t)}function g$(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:qT}var y$=[{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]}],_$=t=>{const e=typeof t=="string"?Cu(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function v$(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?_$(t):t}function w$({data:t,signatures:e}){const r=v$(t),n=typeof r=="string"?Cu(r.substring(0,Math.min(r.length,24))):r;for(const s of e)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,a)=>o===null||n[a]===o))return s.mediaType}var Vg="5.0.106",b$=async({url:t})=>{var e;const r=t.toString();try{const n=await fetch(r,{headers:Kr({},`ai-sdk/${Vg}`,fo())});if(!n.ok)throw new Uu({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw Uu.isInstance(n)?n:new Uu({url:r,cause:n})}},k$=(t=b$)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function S$(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Hg=ie([m(),La(Uint8Array),La(ArrayBuffer),oh(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Bg(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=S$(t.toString());if(e==null||r==null)throw new we({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function C$(t){return typeof t=="string"?t:t instanceof ArrayBuffer?_i(new Uint8Array(t)):_i(t)}async function Jg({prompt:t,supportedUrls:e,download:r=k$()}){const n=await $$(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(s=>T$({message:s,downloadedAssets:n}))]}function T$({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>E$(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:a}=Bg(n.data);return{type:"file",data:o,filename:n.filename,mediaType:a??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:t.providerOptions};default:{const n=r;throw new f$({role:n})}}}async function $$(t,e,r){const n=t.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const i=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let c=o.type==="image"?o.image:o.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:i,data:c}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&rC({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await e(n);return Object.fromEntries(s.map((o,a)=>o==null?null:[n[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function E$(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n;const s=t.type;switch(s){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:a}=Bg(n);let i=a??t.mediaType,c=o;if(c instanceof URL){const l=e[c.toString()];l&&(c=l.data,i??(i=l.mediaType))}switch(s){case"image":return(c instanceof Uint8Array||typeof c=="string")&&(i=(r=w$({data:c,signatures:y$}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:c,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:c,providerOptions:t.providerOptions}}}}function Zu({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:a,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new fr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new fr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new fr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new fr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new fr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new fr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new fr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new fr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:i,seed:a}}function x$(t){return t!=null&&Object.keys(t).length>0}function Wg({tools:t,toolChoice:e,activeTools:r}){return x$(t)?{tools:(r!=null?Object.entries(t).filter(([s])=>r.includes(s)):Object.entries(t)).map(([s,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:yi(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var bo=sh(()=>ie([wc(),m(),N(),me(),be(m(),bo),M(bo)])),hr=be(m(),be(m(),bo)),Gg=T({type:L("text"),text:m(),providerOptions:hr.optional()}),I$=T({type:L("image"),image:ie([Hg,La(URL)]),mediaType:m().optional(),providerOptions:hr.optional()}),Kg=T({type:L("file"),data:ie([Hg,La(URL)]),filename:m().optional(),mediaType:m(),providerOptions:hr.optional()}),R$=T({type:L("reasoning"),text:m(),providerOptions:hr.optional()}),P$=T({type:L("tool-call"),toolCallId:m(),toolName:m(),input:Pe(),providerOptions:hr.optional(),providerExecuted:me().optional()}),O$=Xe("type",[T({type:L("text"),value:m()}),T({type:L("json"),value:bo}),T({type:L("error-text"),value:m()}),T({type:L("error-json"),value:bo}),T({type:L("content"),value:M(ie([T({type:L("text"),text:m()}),T({type:L("media"),data:m(),mediaType:m()})]))})]),Yg=T({type:L("tool-result"),toolCallId:m(),toolName:m(),output:O$,providerOptions:hr.optional()}),A$=T({role:L("system"),content:m(),providerOptions:hr.optional()}),M$=T({role:L("user"),content:ie([m(),M(ie([Gg,I$,Kg]))]),providerOptions:hr.optional()}),N$=T({role:L("assistant"),content:ie([m(),M(ie([Gg,Kg,R$,P$,Yg]))]),providerOptions:hr.optional()}),L$=T({role:L("tool"),content:M(Yg),providerOptions:hr.optional()}),j$=ie([A$,M$,N$,L$]);async function Qg(t){if(t.prompt==null&&t.messages==null)throw new Qn({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Qn({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Qn({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Qn({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Qn({prompt:t,message:"messages must not be empty"});const r=await er({value:e,schema:M(j$)});if(!r.success)throw new Qn({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Xg(t){return xu.isInstance(t)||D2.isInstance(t)?new we({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function ss({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function ey({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((o,[a,i])=>(o[`ai.settings.${a}`]=i,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[a,i])=>(o[`ai.telemetry.metadata.${a}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[a,i])=>(i!==void 0&&(o[`ai.request.headers.${a}`]=i),o),{})}}var q$={startSpan(){return Si},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Si);if(typeof r=="function")return r(Si);if(typeof n=="function")return n(Si)}},Si={spanContext(){return z$},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}},z$={traceId:"",spanId:"",traceFlags:0};function ty({isEnabled:t=!1,tracer:e}={}){return t?e||Y8.getTracer("ai"):q$}function os({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async o=>{try{const a=await n(o);return s&&o.end(),a}catch(a){try{Fu(o,a)}finally{o.end()}throw a}})}function Fu(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:bi.ERROR,message:e.message})):t.setStatus({code:bi.ERROR})}function Dt({telemetry:t,attributes:e}){return t?.isEnabled!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(t?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(t?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function ry(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?C$(r.data):r.data}:r)})))}function ny(t,e){return{inputTokens:ko(t.inputTokens,e.inputTokens),outputTokens:ko(t.outputTokens,e.outputTokens),totalTokens:ko(t.totalTokens,e.totalTokens),reasoningTokens:ko(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:ko(t.cachedInputTokens,e.cachedInputTokens)}}function ko(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function Vu(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function D$({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let n;const s=r["retry-after-ms"];if(s){const a=parseFloat(s);Number.isNaN(a)||(n=a)}const o=r["retry-after"];if(o&&n===void 0){const a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var U$=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>sy(s,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function sy(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:s},o=[]){try{return await t()}catch(a){if(vn(a)||e===0)throw a;const i=yu(a),c=[...o,a],l=c.length;if(l>e)throw new Fg({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:c});if(a instanceof Error&>.isInstance(a)&&a.isRetryable===!0&&l<=e)return await Q5(D$({error:a,exponentialBackoffDelay:r}),{abortSignal:s}),sy(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:s},c);throw l===1?a:new Fg({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:c})}}function oy({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new fr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new fr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:U$({maxRetries:r,abortSignal:e})}}function ay(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var iy=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=_i(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Cu(this.base64Data)),this.uint8ArrayData}},Z$=class extends iy{constructor(t){super(t),this.type="file"}};async function cy({toolCall:t,tools:e,repairToolCall:r,system:n,messages:s}){try{if(e==null)throw new Du({toolName:t.toolName});try{return await ly({toolCall:t,tools:e})}catch(o){if(r==null||!(Du.isInstance(o)||wg.isInstance(o)))throw o;let a=null;try{a=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:c}=e[i];return yi(c).jsonSchema},system:n,messages:s,error:o})}catch(i){throw new u$({cause:i,originalError:o})}if(a==null)throw o;return await ly({toolCall:a,tools:e})}}catch(o){const a=await wn({text:t.input}),i=a.success?a.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:o,providerMetadata:t.providerMetadata}}}async function ly({toolCall:t,tools:e}){const r=t.toolName,n=e[r];if(n==null)throw new Du({toolName:t.toolName,availableTools:Object.keys(e)});const s=yi(n.inputSchema),o=t.input.trim()===""?await er({value:{},schema:s}):await wn({text:t.input,schema:s});if(o.success===!1)throw new wg({toolName:r,toolInput:t.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var uy=class{constructor({content:t,finishReason:e,usage:r,warnings:n,request:s,response:o,providerMetadata:a}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=a}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function Hu(t){return({steps:e})=>e.length===t}async function dy({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function Bu({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Yn(t)}:r==="json"?{type:"error-json",value:py(t)}:e?.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:py(t)}}function py(t){return t===void 0?null:t}function Ju({content:t,tools:e}){const r=[],n=t.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Bu({tool:e?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Bu({tool:e?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=t.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Bu({tool:e?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"}),...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}}));return s.length>0&&r.push({role:"tool",content:s}),r}var F$=uo({prefix:"aitxt",size:24});async function fy({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Hu(1),experimental_output:u,experimental_telemetry:p,providerOptions:h,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:v,prepareStep:y=v,experimental_repairToolCall:w,experimental_download:g,experimental_context:_,_internal:{generateId:b=F$,currentDate:k=()=>new Date}={},onStepFinish:S,...C}){const x=ki(t),R=Vu(l),{maxRetries:j,retry:O}=oy({maxRetries:a,abortSignal:i}),D=Zu(C),U=Kr(c??{},`ai/${Vg}`),V=ey({model:x,telemetry:p,headers:U,settings:{...D,maxRetries:j}}),ne=await Qg({system:n,prompt:s,messages:o}),fe=ty(p);try{return await os({name:"ai.generateText",attributes:Dt({telemetry:p,attributes:{...ss({operationId:"ai.generateText",telemetry:p}),...V,"ai.model.provider":x.provider,"ai.model.id":x.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:s,messages:o})}}}),tracer:fe,fn:async de=>{var te,ye,H,P,F,q,E;const I=Zu(C);let $,B=[],G=[];const _e=[],pe=[];do{const W=[...ne.messages,..._e],K=await y?.({model:x,steps:pe,stepNumber:pe.length,messages:W}),Q=ki((te=K?.model)!=null?te:x),ue=await Jg({prompt:{system:(ye=K?.system)!=null?ye:ne.system,messages:(H=K?.messages)!=null?H:W},supportedUrls:await Q.supportedUrls,download:g}),{toolChoice:he,tools:Ve}=Wg({tools:e,toolChoice:(P=K?.toolChoice)!=null?P:r,activeTools:(F=K?.activeTools)!=null?F:f});$=await O(()=>{var Ee;return os({name:"ai.generateText.doGenerate",attributes:Dt({telemetry:p,attributes:{...ss({operationId:"ai.generateText.doGenerate",telemetry:p}),...V,"ai.model.provider":Q.provider,"ai.model.id":Q.modelId,"ai.prompt.messages":{input:()=>ry(ue)},"ai.prompt.tools":{input:()=>Ve?.map($t=>JSON.stringify($t))},"ai.prompt.toolChoice":{input:()=>he!=null?JSON.stringify(he):void 0},"gen_ai.system":Q.provider,"gen_ai.request.model":Q.modelId,"gen_ai.request.frequency_penalty":C.frequencyPenalty,"gen_ai.request.max_tokens":C.maxOutputTokens,"gen_ai.request.presence_penalty":C.presencePenalty,"gen_ai.request.stop_sequences":C.stopSequences,"gen_ai.request.temperature":(Ee=C.temperature)!=null?Ee:void 0,"gen_ai.request.top_k":C.topK,"gen_ai.request.top_p":C.topP}}),tracer:fe,fn:async $t=>{var Or,Et,ct,Zt,en,tn,ds,qi;const rt=await Q.doGenerate({...I,tools:Ve,toolChoice:he,responseFormat:u?.responseFormat,prompt:ue,providerOptions:h,abortSignal:i,headers:U}),Ar={id:(Et=(Or=rt.response)==null?void 0:Or.id)!=null?Et:b(),timestamp:(Zt=(ct=rt.response)==null?void 0:ct.timestamp)!=null?Zt:k(),modelId:(tn=(en=rt.response)==null?void 0:en.modelId)!=null?tn:Q.modelId,headers:(ds=rt.response)==null?void 0:ds.headers,body:(qi=rt.response)==null?void 0:qi.body};return $t.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":rt.finishReason,"ai.response.text":{output:()=>ay(rt.content)},"ai.response.toolCalls":{output:()=>{const Mr=hy(rt.content);return Mr==null?void 0:JSON.stringify(Mr)}},"ai.response.id":Ar.id,"ai.response.model":Ar.modelId,"ai.response.timestamp":Ar.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(rt.providerMetadata),"ai.usage.promptTokens":rt.usage.inputTokens,"ai.usage.completionTokens":rt.usage.outputTokens,"gen_ai.response.finish_reasons":[rt.finishReason],"gen_ai.response.id":Ar.id,"gen_ai.response.model":Ar.modelId,"gen_ai.usage.input_tokens":rt.usage.inputTokens,"gen_ai.usage.output_tokens":rt.usage.outputTokens}})),{...rt,response:Ar}}})});const Be=await Promise.all($.content.filter(Ee=>Ee.type==="tool-call").map(Ee=>cy({toolCall:Ee,tools:e,repairToolCall:w,system:n,messages:W})));for(const Ee of Be){if(Ee.invalid)continue;const $t=e[Ee.toolName];$t?.onInputAvailable!=null&&await $t.onInputAvailable({input:Ee.input,toolCallId:Ee.toolCallId,messages:W,abortSignal:i,experimental_context:_})}const X=Be.filter(Ee=>Ee.invalid&&Ee.dynamic);G=[];for(const Ee of X)G.push({type:"tool-error",toolCallId:Ee.toolCallId,toolName:Ee.toolName,input:Ee.input,error:yu(Ee.error),dynamic:!0});B=Be.filter(Ee=>!Ee.providerExecuted),e!=null&&G.push(...await V$({toolCalls:B.filter(Ee=>!Ee.invalid),tools:e,tracer:fe,telemetry:p,messages:W,abortSignal:i,experimental_context:_}));const ke=B$({content:$.content,toolCalls:Be,toolOutputs:G});_e.push(...Ju({content:ke,tools:e}));const wt=new uy({content:ke,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(q=$.request)!=null?q:{},response:{...$.response,messages:structuredClone(_e)}});fg((E=$.warnings)!=null?E:[]),pe.push(wt),await S?.(wt)}while(B.length>0&&G.length===B.length&&!await dy({stopConditions:R,steps:pe}));de.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>ay($.content)},"ai.response.toolCalls":{output:()=>{const W=hy($.content);return W==null?void 0:JSON.stringify(W)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const A=pe[pe.length-1];let Z;return A.finishReason==="stop"&&(Z=await u?.parseOutput({text:A.text},{response:A.response,usage:A.usage,finishReason:A.finishReason})),new H$({steps:pe,resolvedOutput:Z})}})}catch(de){throw Xg(de)}}async function V$({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:o,experimental_context:a}){return(await Promise.all(t.map(async({toolCallId:c,toolName:l,input:u})=>{const p=e[l];if(p?.execute!=null)return os({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...ss({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=_2({execute:p.execute.bind(p),input:u,options:{toolCallId:c,messages:s,abortSignal:o,experimental_context:a}});let f;for await(const v of d)v.type==="final"&&(f=v.output);try{h.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:u,output:f,dynamic:p.type==="dynamic"}}catch(d){return Fu(h,d),{type:"tool-error",toolCallId:c,toolName:l,input:u,error:d,dynamic:p.type==="dynamic"}}}})}))).filter(c=>c!=null)}var H$=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>ny(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new dg;return this.resolvedOutput}};function hy(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function B$({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new iy(n)};case"tool-call":return e.find(s=>s.toolCallId===n.toolCallId);case"tool-result":{const s=e.find(o=>o.toolCallId===n.toolCallId);if(s==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,error:n.result,providerExecuted:!0,dynamic:s.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,output:n.result,providerExecuted:!0,dynamic:s.dynamic}}}}),...r]}function Ci(t,e){const r=new Headers(t??{});for(const[n,s]of Object.entries(e))r.has(n)||r.set(n,s);return r}function J$({status:t,statusText:e,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:Ci(r,{"content-type":"text/plain; charset=utf-8"})})}function my({response:t,status:e,statusText:r,headers:n,stream:s}){t.writeHead(e??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:i,value:c}=await o.read();if(i)break;t.write(c)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function W$({response:t,status:e,statusText:r,headers:n,textStream:s}){my({response:t,status:e,statusText:r,headers:Object.fromEntries(Ci(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var gy=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
|
|
570
570
|
|
|
571
571
|
`)},flush(t){t.enqueue(`data: [DONE]
|
|
572
572
|
|
|
573
|
-
`)}})}},dy={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function G7({status:t,statusText:e,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new uy);if(s){const[a,i]=o.tee();o=a,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:tc(r,dy)})}function K7({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return r?.role==="assistant"?r.id:typeof e=="function"?e():e}function Y7(t){return t.type.startsWith("data-")}function py(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(s===void 0)continue;const o=n in t?t[n]:void 0,a=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&i?r[n]=py(o,s):r[n]=s}return r}function Q7(t){const e=["ROOT"];let r=-1,n=null;function s(c,l,u){switch(c){case'"':{r=l,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=l,n=l,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=l,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=l,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function o(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=l,e.pop();break}}}function a(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}}}for(let c=0;c<t.length;c++){const l=t[c];switch(e[e.length-1]){case"ROOT":s(l,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(l,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,c);break}case"INSIDE_STRING":{switch(l){case'"':{e.pop(),r=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{r=c,e.pop();break}default:{r=c,s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=c;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const h=t.substring(n,c+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c)):r=c;break}}}let i=t.slice(0,r+1);for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(n,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function hy(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await An({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await An({text:Q7(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Xd(t){return t.type.startsWith("tool-")}function fy(t){return t.type.split("-").slice(1).join("-")}function X7({lastMessage:t,messageId:e}){return{message:t?.role==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function eR({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:a}){return t.pipeThrough(new TransformStream({async transform(i,c){await n(async({state:l,write:u})=>{var h,f,p,m;function v(b){const k=l.message.parts.filter(Xd).find(T=>T.toolCallId===b);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function _(b){const k=l.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===b);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function w(b){var S;const k=l.message.parts.find(P=>Xd(P)&&P.toolCallId===b.toolCallId),T=b,x=k;k!=null?(k.state=b.state,x.input=T.input,x.output=T.output,x.errorText=T.errorText,x.rawInput=T.rawInput,x.preliminary=T.preliminary,x.providerExecuted=(S=T.providerExecuted)!=null?S:k.providerExecuted,T.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=T.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function g(b){var S,k;const T=l.message.parts.find(q=>q.type==="dynamic-tool"&&q.toolCallId===b.toolCallId),x=b,P=T;T!=null?(T.state=b.state,P.toolName=b.toolName,P.input=x.input,P.output=x.output,P.errorText=x.errorText,P.rawInput=(S=x.rawInput)!=null?S:P.rawInput,P.preliminary=x.preliminary,P.providerExecuted=(k=x.providerExecuted)!=null?k:T.providerExecuted,x.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=x.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function y(b){if(b!=null){const S=l.message.metadata!=null?py(l.message.metadata,b):b;e!=null&&await Cd({value:S,schema:e}),l.message.metadata=S}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeTextParts[i.id]=b,l.message.parts.push(b),u();break}case"text-delta":{const b=l.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,u();break}case"text-end":{const b=l.activeTextParts[i.id];b.state="done",b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,delete l.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeReasoningParts[i.id]=b,l.message.parts.push(b),u();break}case"reasoning-delta":{const b=l.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,u();break}case"reasoning-end":{const b=l.activeReasoningParts[i.id];b.providerMetadata=(m=i.providerMetadata)!=null?m:b.providerMetadata,b.state="done",delete l.activeReasoningParts[i.id],u();break}case"file":{l.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=l.message.parts.filter(Xd);l.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=l.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:S}=await hy(b.text);b.dynamic?g({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}):w({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}),u();break}case"tool-input-available":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=_(i.toolCallId);g({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:fy(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=_(i.toolCallId);g({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:fy(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{i.messageId!=null&&(l.message.id=i.messageId),await y(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(l.finishReason=i.finishReason),await y(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await y(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{s?.(new Error(i.errorText));break}default:if(Y7(i)){r?.[i.type]!=null&&await Cd({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const S=b.id!=null?l.message.parts.find(k=>b.type===k.type&&b.id===k.id):void 0;S!=null?S.data=b.data:l.message.parts.push(b),a?.(b),u()}}c.enqueue(i)})}}))}function tR({messageId:t,originalMessages:e=[],onFinish:r,onError:n,stream:s}){let o=e?.[e.length-1];o?.role!=="assistant"?o=void 0:t=o.id;let a=!1;const i=s.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const m=f;m.messageId==null&&t!=null&&(m.messageId=t)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(r==null)return i;const c=X7({lastMessage:o?structuredClone(o):void 0,messageId:t??""}),l=async f=>{await f({state:c,write:()=>{}})};let u=!1;const h=async()=>{if(u||!r)return;u=!0;const f=c.message.id===o?.id;await r({isAborted:a,isContinuation:f,responseMessage:c.message,messages:[...f?e.slice(0,-1):e,c.message],finishReason:c.finishReason})};return eR({stream:i,runUpdateMessageJob:l,onError:n}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await h()},async flush(){await h()}}))}function rR({response:t,status:e,statusText:r,headers:n,stream:s,consumeSseStream:o}){let a=s.pipeThrough(new uy);if(o){const[i,c]=a.tee();a=i,o({stream:c})}ly({response:t,status:e,statusText:r,headers:Object.fromEntries(tc(n,dy).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function rc(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var a;n=!0;try{o&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:a}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},e}async function nR({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){e?.(n)}finally{r.releaseLock()}}function my(){let t,e;return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}function sR(){let t=[],e=null,r=!1,n=my();const s=()=>{r=!0,n.resolve(),t.forEach(a=>a.cancel()),t=[],e?.close()},o=async()=>{if(r&&t.length===0){e?.close();return}if(t.length===0)return n=my(),await n.promise,o();try{const{value:a,done:i}=await t[0].read();i?(t.shift(),t.length>0?await o():r&&e?.close()):e?.enqueue(a)}catch(a){e?.error(a),t.shift(),s()}};return{stream:new ReadableStream({start(a){e=a},pull:o,async cancel(){for(const a of t)await a.cancel();t=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),t.length===0&&e?.close()},terminate:s}}function oR(){var t,e;return(e=(t=globalThis?.performance)==null?void 0:t.now())!=null?e:Date.now()}function aR({tools:t,generatorStream:e,tracer:r,telemetry:n,system:s,messages:o,abortSignal:a,repairToolCall:i,experimental_context:c}){let l=null;const u=new ReadableStream({start(w){l=w}}),h=new Set,f=new Map;let p=!1,m;function v(){p&&h.size===0&&(m!=null&&l.enqueue(m),l.close())}const _=new TransformStream({async transform(w,g){const y=w.type;switch(y){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":{g.enqueue(w);break}case"file":{g.enqueue({type:"file",file:new Z7({data:w.data,mediaType:w.mediaType})});break}case"finish":{m={type:"finish",finishReason:w.finishReason,usage:w.usage,providerMetadata:w.providerMetadata};break}case"tool-call":{try{const b=await ry({toolCall:w,tools:t,repairToolCall:i,system:s,messages:o});if(g.enqueue(b),b.invalid){l.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Sd(b.error),dynamic:!0});break}const S=t[b.toolName];if(f.set(b.toolCallId,b.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}),S.execute!=null&&b.providerExecuted!==!0){const k=Eo();h.add(k),_s({name:"ai.toolCall",attributes:Bt({telemetry:n,attributes:{...gs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async T=>{let x;try{const P=p_({execute:S.execute.bind(S),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}});for await(const q of P)l.enqueue({...b,type:"tool-result",output:q.output,...q.type==="preliminary"&&{preliminary:!0}}),q.type==="final"&&(x=q.output)}catch(P){Wd(T,P),l.enqueue({...b,type:"tool-error",error:P}),h.delete(k),v();return}h.delete(k),v();try{T.setAttributes(Bt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(b){l.enqueue({type:"error",error:b})}break}case"tool-result":{const b=w.toolName;w.isError?l.enqueue({type:"tool-error",toolCallId:w.toolCallId,toolName:b,input:f.get(w.toolCallId),providerExecuted:w.providerExecuted,error:w.result}):g.enqueue({type:"tool-result",toolCallId:w.toolCallId,toolName:b,input:f.get(w.toolCallId),output:w.result,providerExecuted:w.providerExecuted});break}default:{const b=y;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){p=!0,v()}});return new ReadableStream({async start(w){return Promise.all([e.pipeThrough(_).pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){}})),u.pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){w.close()}}))])}})}var iR=$o({prefix:"aitxt",size:24});function ep({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Kd(1),experimental_output:u,experimental_telemetry:h,prepareStep:f,providerOptions:p,experimental_activeTools:m,activeTools:v=m,experimental_repairToolCall:_,experimental_transform:w,experimental_download:g,includeRawChunks:y=!1,onChunk:b,onError:S=({error:F})=>{console.error(F)},onFinish:k,onAbort:T,onStepFinish:x,experimental_context:P,_internal:{now:q=oR,generateId:N=iR,currentDate:z=()=>new Date}={},...D}){return new lR({model:Xi(t),telemetry:h,headers:c,settings:D,maxRetries:a,abortSignal:i,system:n,prompt:s,messages:o,tools:e,toolChoice:r,transforms:Gd(w),activeTools:v,repairToolCall:_,stopConditions:Gd(l),output:u,providerOptions:p,prepareStep:f,includeRawChunks:y,onChunk:b,onError:S,onFinish:k,onAbort:T,onStepFinish:x,now:q,currentDate:z,generateId:N,experimental_context:P,download:g})}function cR(t){if(!t)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let e,r="",n="",s="";function o({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:e,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&o({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(e==null)e=a.id;else if(a.id!==e){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const c=await t.parsePartial({text:r});if(c!=null){const l=JSON.stringify(c.partial);l!==s&&(o({controller:i,partialOutput:c.partial}),s=l)}}})}var lR=class{constructor({model:t,telemetry:e,headers:r,settings:n,maxRetries:s,abortSignal:o,system:a,prompt:i,messages:c,tools:l,toolChoice:u,transforms:h,activeTools:f,repairToolCall:p,stopConditions:m,output:v,providerOptions:_,prepareStep:w,includeRawChunks:g,now:y,currentDate:b,generateId:S,onChunk:k,onError:T,onFinish:x,onAbort:P,onStepFinish:q,experimental_context:N,download:z}){this._totalUsage=new Hi,this._finishReason=new Hi,this._steps=new Hi,this.output=v,this.includeRawChunks=g,this.tools=l;let D,F=[];const oe=[];let fe,de,se={},_e=[];const H=[];let A,V={},j={};const E=new TransformStream({async transform(K,X){var ue,me,Je,Ge;X.enqueue(K);const{part:te}=K;if((te.type==="text-delta"||te.type==="reasoning-delta"||te.type==="source"||te.type==="tool-call"||te.type==="tool-result"||te.type==="tool-input-start"||te.type==="tool-input-delta"||te.type==="raw")&&await k?.({chunk:te}),te.type==="error"&&await T({error:Jv(te.error)}),te.type==="text-start"&&(V[te.id]={type:"text",text:"",providerMetadata:te.providerMetadata},F.push(V[te.id])),te.type==="text-delta"){const ke=V[te.id];if(ke==null){X.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}ke.text+=te.text,ke.providerMetadata=(ue=te.providerMetadata)!=null?ue:ke.providerMetadata}if(te.type==="text-end"){const ke=V[te.id];if(ke==null){X.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(me=te.providerMetadata)!=null?me:ke.providerMetadata,delete V[te.id]}if(te.type==="reasoning-start"&&(j[te.id]={type:"reasoning",text:"",providerMetadata:te.providerMetadata},F.push(j[te.id])),te.type==="reasoning-delta"){const ke=j[te.id];if(ke==null){X.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}ke.text+=te.text,ke.providerMetadata=(Je=te.providerMetadata)!=null?Je:ke.providerMetadata}if(te.type==="reasoning-end"){const ke=j[te.id];if(ke==null){X.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(Ge=te.providerMetadata)!=null?Ge:ke.providerMetadata,delete j[te.id]}if(te.type==="file"&&F.push({type:"file",file:te.file}),te.type==="source"&&F.push(te),te.type==="tool-call"&&F.push(te),te.type==="tool-result"&&!te.preliminary&&F.push(te),te.type==="tool-error"&&F.push(te),te.type==="start-step"&&(se=te.request,_e=te.warnings),te.type==="finish-step"){const ke=Qd({content:F,tools:l}),Ct=new sy({content:F,finishReason:te.finishReason,usage:te.usage,warnings:_e,request:se,response:{...te.response,messages:[...oe,...ke]},providerMetadata:te.providerMetadata});await q?.(Ct),iv(_e),H.push(Ct),F=[],j={},V={},oe.push(...ke),D.resolve()}te.type==="finish"&&(de=te.totalUsage,fe=te.finishReason)},async flush(K){try{if(H.length===0){const Je=new i7({message:"No output generated. Check the stream for errors."});W._finishReason.reject(Je),W._totalUsage.reject(Je),W._steps.reject(Je);return}const X=fe??"unknown",ue=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};W._finishReason.resolve(X),W._totalUsage.resolve(ue),W._steps.resolve(H);const me=H[H.length-1];await x?.({finishReason:X,totalUsage:ue,usage:me.usage,content:me.content,text:me.text,reasoningText:me.reasoningText,reasoning:me.reasoning,files:me.files,sources:me.sources,toolCalls:me.toolCalls,staticToolCalls:me.staticToolCalls,dynamicToolCalls:me.dynamicToolCalls,toolResults:me.toolResults,staticToolResults:me.staticToolResults,dynamicToolResults:me.dynamicToolResults,request:me.request,response:me.response,warnings:me.warnings,providerMetadata:me.providerMetadata,steps:H}),A.setAttributes(Bt({telemetry:e,attributes:{"ai.response.finishReason":X,"ai.response.text":{output:()=>me.text},"ai.response.toolCalls":{output:()=>{var Je;return(Je=me.toolCalls)!=null&&Je.length?JSON.stringify(me.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(me.providerMetadata),"ai.usage.inputTokens":ue.inputTokens,"ai.usage.outputTokens":ue.outputTokens,"ai.usage.totalTokens":ue.totalTokens,"ai.usage.reasoningTokens":ue.reasoningTokens,"ai.usage.cachedInputTokens":ue.cachedInputTokens}}))}catch(X){K.error(X)}finally{A.end()}}}),R=sR();this.addStream=R.addStream,this.closeStream=R.close;const $=R.stream.getReader();let B=new ReadableStream({async start(K){K.enqueue({type:"start"})},async pull(K){function X(){P?.({steps:H}),K.enqueue({type:"abort"}),K.close()}try{const{done:ue,value:me}=await $.read();if(ue){K.close();return}if(o?.aborted){X();return}K.enqueue(me)}catch(ue){On(ue)&&o?.aborted?X():K.error(ue)}},cancel(K){return R.stream.cancel(K)}});for(const K of h)B=B.pipeThrough(K({tools:l,stopStream(){R.terminate()}}));this.baseStream=B.pipeThrough(cR(v)).pipeThrough(E);const{maxRetries:G,retry:ve}=Xv({maxRetries:s,abortSignal:o}),pe=Gv(e),L=Jd(n),Z=Wv({model:t,telemetry:e,headers:r,settings:{...L,maxRetries:G}}),W=this;_s({name:"ai.streamText",attributes:Bt({telemetry:e,attributes:{...gs({operationId:"ai.streamText",telemetry:e}),...Z,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:c})}}}),tracer:pe,endWhenDone:!1,fn:async K=>{A=K;async function X({currentStep:ue,responseMessages:me,usage:Je}){var Ge,te,ke,Ct,Ie;const Pt=W.includeRawChunks;D=new Hi;const zr=await Bv({system:a,prompt:i,messages:c}),Ot=[...zr.messages,...me],pt=await w?.({model:t,steps:H,stepNumber:H.length,messages:Ot}),Wt=Xi((Ge=pt?.model)!=null?Ge:t),un=await Dv({prompt:{system:(te=pt?.system)!=null?te:zr.system,messages:(ke=pt?.messages)!=null?ke:Ot},supportedUrls:await Wt.supportedUrls,download:z}),{toolChoice:dn,tools:ks}=Zv({tools:l,toolChoice:(Ct=pt?.toolChoice)!=null?Ct:u,activeTools:(Ie=pt?.activeTools)!=null?Ie:f}),{result:{stream:mc,response:st,request:Dr},doStreamSpan:Zr,startTimestampMs:uw}=await ve(()=>_s({name:"ai.streamText.doStream",attributes:Bt({telemetry:e,attributes:{...gs({operationId:"ai.streamText.doStream",telemetry:e}),...Z,"ai.model.provider":Wt.provider,"ai.model.id":Wt.modelId,"ai.prompt.messages":{input:()=>Kv(un)},"ai.prompt.tools":{input:()=>ks?.map(ye=>JSON.stringify(ye))},"ai.prompt.toolChoice":{input:()=>dn!=null?JSON.stringify(dn):void 0},"gen_ai.system":Wt.provider,"gen_ai.request.model":Wt.modelId,"gen_ai.request.frequency_penalty":L.frequencyPenalty,"gen_ai.request.max_tokens":L.maxOutputTokens,"gen_ai.request.presence_penalty":L.presencePenalty,"gen_ai.request.stop_sequences":L.stopSequences,"gen_ai.request.temperature":L.temperature,"gen_ai.request.top_k":L.topK,"gen_ai.request.top_p":L.topP}}),tracer:pe,endWhenDone:!1,fn:async ye=>({startTimestampMs:y(),doStreamSpan:ye,result:await Wt.doStream({...L,tools:ks,toolChoice:dn,responseFormat:v?.responseFormat,prompt:un,providerOptions:_,abortSignal:o,headers:r,includeRawChunks:Pt})})})),yM=aR({tools:l,generatorStream:mc,tracer:pe,telemetry:e,system:a,messages:Ot,repairToolCall:p,abortSignal:o,experimental_context:N}),wM=Dr??{},gc=[],gp=[];let _p;const vp={};let Cs="unknown",hr={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},yp,dw=!0,$r={id:S(),timestamp:b(),modelId:t.modelId},pw="";W.addStream(yM.pipeThrough(new TransformStream({async transform(ye,ht){var Vo,Fo,_c,Vr;if(ye.type==="stream-start"){_p=ye.warnings;return}if(dw){const Tt=y()-uw;dw=!1,Zr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Tt}),Zr.setAttributes({"ai.response.msToFirstChunk":Tt}),ht.enqueue({type:"start-step",request:wM,warnings:_p??[]})}const hw=ye.type;switch(hw){case"text-start":case"text-end":{ht.enqueue(ye);break}case"text-delta":{ye.delta.length>0&&(ht.enqueue({type:"text-delta",id:ye.id,text:ye.delta,providerMetadata:ye.providerMetadata}),pw+=ye.delta);break}case"reasoning-start":case"reasoning-end":{ht.enqueue(ye);break}case"reasoning-delta":{ht.enqueue({type:"reasoning-delta",id:ye.id,text:ye.delta,providerMetadata:ye.providerMetadata});break}case"tool-call":{ht.enqueue(ye),gc.push(ye);break}case"tool-result":{ht.enqueue(ye),ye.preliminary||gp.push(ye);break}case"tool-error":{ht.enqueue(ye),gp.push(ye);break}case"response-metadata":{$r={id:(Vo=ye.id)!=null?Vo:$r.id,timestamp:(Fo=ye.timestamp)!=null?Fo:$r.timestamp,modelId:(_c=ye.modelId)!=null?_c:$r.modelId};break}case"finish":{hr=ye.usage,Cs=ye.finishReason,yp=ye.providerMetadata;const Tt=y()-uw;Zr.addEvent("ai.stream.finish"),Zr.setAttributes({"ai.response.msToFinish":Tt,"ai.response.avgOutputTokensPerSecond":1e3*((Vr=hr.outputTokens)!=null?Vr:0)/Tt});break}case"file":{ht.enqueue(ye);break}case"source":{ht.enqueue(ye);break}case"tool-input-start":{vp[ye.id]=ye.toolName;const Tt=l?.[ye.toolName];Tt?.onInputStart!=null&&await Tt.onInputStart({toolCallId:ye.id,messages:Ot,abortSignal:o,experimental_context:N}),ht.enqueue({...ye,dynamic:Tt?.type==="dynamic"});break}case"tool-input-end":{delete vp[ye.id],ht.enqueue(ye);break}case"tool-input-delta":{const Tt=vp[ye.id],wp=l?.[Tt];wp?.onInputDelta!=null&&await wp.onInputDelta({inputTextDelta:ye.delta,toolCallId:ye.id,messages:Ot,abortSignal:o,experimental_context:N}),ht.enqueue(ye);break}case"error":{ht.enqueue(ye),Cs="error";break}case"raw":{Pt&&ht.enqueue(ye);break}default:{const Tt=hw;throw new Error(`Unknown chunk type: ${Tt}`)}}},async flush(ye){const ht=gc.length>0?JSON.stringify(gc):void 0;try{Zr.setAttributes(Bt({telemetry:e,attributes:{"ai.response.finishReason":Cs,"ai.response.text":{output:()=>pw},"ai.response.toolCalls":{output:()=>ht},"ai.response.id":$r.id,"ai.response.model":$r.modelId,"ai.response.timestamp":$r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(yp),"ai.usage.inputTokens":hr.inputTokens,"ai.usage.outputTokens":hr.outputTokens,"ai.usage.totalTokens":hr.totalTokens,"ai.usage.reasoningTokens":hr.reasoningTokens,"ai.usage.cachedInputTokens":hr.cachedInputTokens,"gen_ai.response.finish_reasons":[Cs],"gen_ai.response.id":$r.id,"gen_ai.response.model":$r.modelId,"gen_ai.usage.input_tokens":hr.inputTokens,"gen_ai.usage.output_tokens":hr.outputTokens}}))}catch{}finally{Zr.end()}ye.enqueue({type:"finish-step",finishReason:Cs,usage:hr,providerMetadata:yp,response:{...$r,headers:st?.headers}});const Vo=Yv(Je,hr);await D.promise;const Fo=gc.filter(Vr=>Vr.providerExecuted!==!0),_c=gp.filter(Vr=>Vr.providerExecuted!==!0);if(Fo.length>0&&_c.length===Fo.length&&!await oy({stopConditions:m,steps:H})){me.push(...Qd({content:H[H.length-1].content,tools:l}));try{await X({currentStep:ue+1,responseMessages:me,usage:Vo})}catch(Vr){ye.enqueue({type:"error",error:Vr}),W.closeStream()}}else ye.enqueue({type:"finish",finishReason:Cs,totalUsage:Vo}),W.closeStream()}})))}await X({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(K=>{W.addStream(new ReadableStream({start(X){X.enqueue({type:"error",error:K}),X.close()}})),W.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return rc(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return rc(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await nR({stream:this.fullStream,onError:t?.onError})}catch(r){(e=t?.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new ov;return rc(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:i=!0,onError:c=ls}={}){const l=e!=null?K7({originalMessages:t,responseMessageId:e}):void 0,u={},h=p=>{var m,v;const _=u[p];return((v=(m=this.tools)==null?void 0:m[_])==null?void 0:v.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,m)=>{const v=n?.({part:p}),_=p.type;switch(_){case"text-start":{m.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{m.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{s&&m.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{m.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{o&&p.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),o&&p.sourceType==="document"&&m.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":{u[p.id]=p.toolName;const w=h(p.id);m.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{u[p.toolCallId]=p.toolName;const w=h(p.toolCallId);p.invalid?m.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}:{},...w!=null?{dynamic:w}:{},errorText:c(p.error)}):m.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}:{},...w!=null?{dynamic:w}:{}});break}case"tool-result":{const w=h(p.toolCallId);m.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=h(p.toolCallId);m.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:c(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"error":{m.enqueue({type:"error",errorText:c(p.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{a&&m.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...l!=null?{messageId:l}:{}});break}case"finish":{i&&m.enqueue({type:"finish",finishReason:p.finishReason,...v!=null?{messageMetadata:v}:{}});break}case"abort":{m.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const w=_;throw new Error(`Unknown chunk type: ${w}`)}}v!=null&&_!=="start"&&_!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:v})}}));return rc(tR({stream:f,messageId:l??e?.(),originalMessages:t,onFinish:r,onError:c}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l,...u}={}){rR({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l}),...u})}pipeTextStreamToResponse(t,e){W7({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c,...l}={}){return G7({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c}),...l})}toTextStreamResponse(t){return J7({textStream:this.textStream,...t})}};$o({prefix:"aiobj",size:24}),$o({prefix:"aiobj",size:24});var uR={};XI(uR,{object:()=>pR,text:()=>dR});var dR=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),pR=({schema:t})=>{const e=Wi(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const n=await hy(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await An({text:r});if(!s.success)throw new vv({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await ir({value:s.value,schema:e});if(!o.success)throw new vv({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},hR="AI_MCPClientError",gy=`vercel.ai.error.${hR}`,fR=Symbol.for(gy),_y,vy,Ve=class extends(vy=Se,_y=fR,vy){constructor({name:t="MCPClientError",message:e,cause:r,data:n,code:s}){super({name:t,message:e,cause:r}),this[_y]=!0,this.data=n,this.code=s}static isInstance(t){return Se.hasMarker(t,gy)}},vs="2025-06-18",mR=[vs,"2025-03-26","2024-11-05"],gR=Oe({name:d(),version:d()}),nc=Oe({_meta:Q(C({}).loose())}),qr=nc,yy=C({method:d(),params:Q(nc)}),wy=C({applyDefaults:Q(ne())}).loose(),_R=Oe({experimental:Q(C({}).loose()),logging:Q(C({}).loose()),prompts:Q(Oe({listChanged:Q(ne())})),resources:Q(Oe({subscribe:Q(ne()),listChanged:Q(ne())})),tools:Q(Oe({listChanged:Q(ne())})),elicitation:Q(wy)});C({elicitation:Q(wy)}).loose();var vR=qr.extend({protocolVersion:d(),capabilities:_R,serverInfo:gR,instructions:Q(d())}),tp=qr.extend({nextCursor:Q(d())}),yR=C({name:d(),description:Q(d()),inputSchema:C({type:O("object"),properties:Q(C({}).loose())}).loose()}).loose(),wR=tp.extend({tools:I(yR)}),by=C({type:O("text"),text:d()}).loose(),Sy=C({type:O("image"),data:rm(),mimeType:d()}).loose(),bR=C({uri:d(),name:d(),title:Q(d()),description:Q(d()),mimeType:Q(d()),size:Q(M())}).loose(),SR=tp.extend({resources:I(bR)}),ky=C({uri:d(),name:Q(d()),title:Q(d()),mimeType:Q(d())}).loose(),Cy=ky.extend({text:d()}),Ty=ky.extend({blob:rm()}),$y=C({type:O("resource"),resource:ee([Cy,Ty])}).loose(),kR=qr.extend({content:I(ee([by,Sy,$y])),isError:ne().default(!1).optional()}).or(qr.extend({toolResult:he()})),CR=C({uriTemplate:d(),name:d(),title:Q(d()),description:Q(d()),mimeType:Q(d())}).loose(),TR=qr.extend({resourceTemplates:I(CR)}),$R=qr.extend({contents:I(ee([Cy,Ty]))}),ER=C({name:d(),description:Q(d()),required:Q(ne())}).loose(),xR=C({name:d(),title:Q(d()),description:Q(d()),arguments:Q(I(ER))}).loose(),IR=tp.extend({prompts:I(xR)}),RR=C({role:ee([O("user"),O("assistant")]),content:ee([by,Sy,$y])}).loose(),PR=qr.extend({description:Q(d()),messages:I(RR)}),OR=nc.extend({message:d(),requestedSchema:he()}),Ey=yy.extend({method:O("elicitation/create"),params:OR}),AR=qr.extend({action:ee([O("accept"),O("decline"),O("cancel")]),content:Q(ie(d(),he()))}),sc="2.0",MR=C({jsonrpc:O(sc),id:ee([d(),M().int()])}).merge(yy).strict(),NR=C({jsonrpc:O(sc),id:ee([d(),M().int()]),result:qr}).strict(),LR=C({jsonrpc:O(sc),id:ee([d(),M().int()]),error:C({code:M().int(),message:d(),data:Q(he())})}).strict(),qR=C({jsonrpc:O(sc)}).merge(C({method:d(),params:Q(nc)})).strict(),jo=ee([MR,qR,NR,LR]),xy=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Iy=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:M().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Rt=d().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:nl.custom,message:"URL must be parseable",fatal:!0}),jc}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),jR=C({resource:d().url(),authorization_servers:I(Rt).optional(),jwks_uri:d().url().optional(),scopes_supported:I(d()).optional(),bearer_methods_supported:I(d()).optional(),resource_signing_alg_values_supported:I(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:ne().optional(),authorization_details_types_supported:I(d()).optional(),dpop_signing_alg_values_supported:I(d()).optional(),dpop_bound_access_tokens_required:ne().optional()}).passthrough(),Ry=C({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,registration_endpoint:Rt.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),grant_types_supported:I(d()).optional(),code_challenge_methods_supported:I(d()),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional()}).passthrough(),UR=C({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,userinfo_endpoint:Rt.optional(),jwks_uri:Rt,registration_endpoint:Rt.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),grant_types_supported:I(d()).optional(),subject_types_supported:I(d()),id_token_signing_alg_values_supported:I(d()),claims_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional()}).passthrough(),zR=UR.merge(Ry.pick({code_challenge_methods_supported:!0})),DR=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),ZR=C({redirect_uris:I(Rt),token_endpoint_auth_method:d().optional(),grant_types:I(d()).optional(),response_types:I(d()).optional(),client_name:d().optional(),client_uri:Rt.optional(),logo_uri:Rt.optional(),scope:d().optional(),contacts:I(d()).optional(),tos_uri:Rt.optional(),policy_uri:d().optional(),jwks_uri:Rt.optional(),jwks:mt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),VR=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),FR=ZR.merge(DR),HR="AI_MCPClientOAuthError",Py=`vercel.ai.error.${HR}`,BR=Symbol.for(Py),Oy,Ay,Uo=class extends(Ay=Se,Oy=BR,Ay){constructor({name:t="MCPClientOAuthError",message:e,cause:r}){super({name:t,message:e,cause:r}),this[Oy]=!0}static isInstance(t){return Se.hasMarker(t,Py)}},ys=class extends Uo{};ys.errorCode="server_error";var oc=class extends Uo{};oc.errorCode="invalid_client";var ac=class extends Uo{};ac.errorCode="invalid_grant";var ic=class extends Uo{};ic.errorCode="unauthorized_client";var JR={[ys.errorCode]:ys,[oc.errorCode]:oc,[ac.errorCode]:ac,[ic.errorCode]:ic};function WR(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function GR({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var cc=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function lc(t){var e;const r=(e=t.headers.get("www-authenticate"))!=null?e:t.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,a=r.match(o);if(a)try{return new URL(a[1])}catch{return}}function KR(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function rp(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?rp(t,void 0,r):void 0;throw n}}async function My(t,e,r=fetch){return await rp(t,{"MCP-Protocol-Version":e},r)}function YR(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function QR(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!=null?s:vs;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const u=KR(e,a.pathname);c=new URL(u,(o=n?.metadataServerUrl)!=null?o:a),c.search=a.search}let l=await My(c,i,r);if(!n?.metadataUrl&&YR(l,a.pathname)){const u=new URL(`/.well-known/${e}`,a);l=await My(u,i,r)}return l}async function XR(t,e,r=fetch){const n=await QR(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return jR.parse(await n.json())}function eP(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function tP(t,{fetchFn:e=fetch,protocolVersion:r=vs}={}){var n;const s={"MCP-Protocol-Version":r},o=eP(t);for(const{url:a,type:i}of o){const c=await rp(a,s,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return Ry.parse(await c.json());{const l=zR.parse(await c.json());if(!((n=l.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return l}}}}async function rP(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){const i="code",c="S256";let l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",t);const u=await Dl(),h=u.code_verifier,f=u.code_challenge;return l.searchParams.set("response_type",i),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",f),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(n)),o&&l.searchParams.set("state",o),s&&l.searchParams.set("scope",s),s?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:h}}function Ny(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Ly(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":nP(s,o,r);return;case"client_secret_post":sP(s,o,n);return;case"none":oP(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function nP(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function sP(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function oP(t,e){e.set("client_id",t)}async function np(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=VR.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=JR[s]||ys;return new i({message:o||"",cause:a})}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ys({message:s})}}async function aP(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:c}){var l;const u="authorization_code",h=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(f,p,t,e);else{const v=(l=e?.token_endpoint_auth_methods_supported)!=null?l:[],_=Ny(r,v);Ly(_,r,f,p)}a&&p.set("resource",a.href);const m=await(c??fetch)(h,{method:"POST",headers:f,body:p});if(!m.ok)throw await np(m);return Iy.parse(await m.json())}async function iP(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const c="refresh_token";let l;if(e){if(l=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(u,h,t,e);else{const p=(i=e?.token_endpoint_auth_methods_supported)!=null?i:[],m=Ny(r,p);Ly(m,r,u,h)}s&&h.set("resource",s.href);const f=await(a??fetch)(l,{method:"POST",headers:u,body:h});if(!f.ok)throw await np(f);return Iy.parse({refresh_token:n,...await f.json()})}async function cP(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await np(o);return FR.parse(await o.json())}async function uc(t,e){var r,n;try{return await sp(t,e)}catch(s){if(s instanceof oc||s instanceof ic)return await((r=t.invalidateCredentials)==null?void 0:r.call(t,"all")),await sp(t,e);if(s instanceof ac)return await((n=t.invalidateCredentials)==null?void 0:n.call(t,"tokens")),await sp(t,e);throw s}}async function lP(t,e,r){const n=WR(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!GR({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(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await XR(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=e);const c=await lP(e,t,a),l=await tP(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await cP(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),_=await aP(i,{metadata:l,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}const h=await t.tokens();if(h?.refresh_token)try{const v=await iP(i,{metadata:l,clientInformation:u,refreshToken:h.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Uo)||v instanceof ys))throw v}const f=t.state?await t.state():void 0,{authorizationUrl:p,codeVerifier:m}=await rP(i,{metadata:l,clientInformation:u,state:f,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(p),"REDIRECT"}var uP=class{constructor({url:t,headers:e,authProvider:r}){this.connected=!1,this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":vs};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return on(e,`ai-sdk/${xy}`,xo())}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,a,i,c;try{const l=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:l,signal:(s=this.abortController)==null?void 0:s.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=lc(u);try{if(await uc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new cc;return(o=this.onerror)==null||o.call(this,v),e(v)}}catch(m){return(a=this.onerror)==null||a.call(this,m),e(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 Ve({message:m});return(i=this.onerror)==null||i.call(this,v),e(v)}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new En).getReader(),p=async()=>{var m,v,_;try{for(;;){const{done:w,value:g}=await f.read();if(w){if(this.connected)throw this.connected=!1,new Ve({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:y,data:b}=g;if(y==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new Ve({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,t()}else if(y==="message")try{const S=jo.parse(JSON.parse(b));(m=this.onmessage)==null||m.call(this,S)}catch(S){const k=new Ve({message:"MCP SSE Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,k)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(_=this.onerror)==null||_.call(this,w),e(w)}};this.sseConnection={close:()=>f.cancel()},p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(c=this.onerror)==null||c.call(this,l),e(l)}};r()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){if(!this.endpoint||!this.connected)throw new Ve({message:"MCP SSE Transport Error: Not connected"});const e=this.endpoint,r=async(n=!1)=>{var s,o,a,i,c;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(t),signal:(s=this.abortController)==null?void 0:s.signal},h=await fetch(e,u);if(h.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=lc(h);try{if(await uc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new cc;(o=this.onerror)==null||o.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return r(!0)}if(!h.ok){const f=await h.text().catch(()=>null),p=new Ve({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${h.status}): ${f}`});(i=this.onerror)==null||i.call(this,p);return}}catch(l){(c=this.onerror)==null||c.call(this,l);return}};await r()}},dP=class{constructor({url:t,headers:e,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":vs};if(this.sessionId&&(e["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return on(e,`ai-sdk/${xy}`,xo())}async start(){if(this.abortController)throw new Ve({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var t,e,r;(t=this.inboundSseConnection)==null||t.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){const e=async(r=!1)=>{var n,s,o,a,i,c,l;try{const h={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(t),signal:(n=this.abortController)==null?void 0:n.signal},f=await fetch(this.url,h),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=lc(f);try{if(await uc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new cc}catch(_){throw(s=this.onerror)==null||s.call(this,_),_}return e(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const _=await f.text().catch(()=>null);let w=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${_}`;f.status===404&&(w+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new Ve({message:w});throw(o=this.onerror)==null||o.call(this,g),g}const m=f.headers.get("content-type")||"";if(m.includes("application/json")){const _=await f.json(),w=Array.isArray(_)?_.map(g=>jo.parse(g)):[jo.parse(_)];for(const g of w)(a=this.onmessage)==null||a.call(this,g);return}if(m.includes("text/event-stream")){if(!f.body){const y=new Ve({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,y),y}const w=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new En).getReader();(async()=>{var y,b,S;try{for(;;){const{done:k,value:T}=await w.read();if(k)return;const{event:x,data:P}=T;if(x==="message")try{const q=jo.parse(JSON.parse(P));(y=this.onmessage)==null||y.call(this,q)}catch(q){const N=new Ve({message:"MCP HTTP Transport Error: Failed to parse message",cause:q});(b=this.onerror)==null||b.call(this,N)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(S=this.onerror)==null||S.call(this,k)}})();return}const v=new Ve({message:`MCP HTTP Transport Error: Unexpected content type: ${m}`});throw(c=this.onerror)==null||c.call(this,v),v}catch(u){throw(l=this.onerror)==null||l.call(this,u),u}};await e()}getNextReconnectionDelay(t){const{initialReconnectionDelay:e,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(e*Math.pow(r,t),n)}scheduleInboundSseReconnection(){var t;const{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){(t=this.onerror)==null||t.call(this,new Ve({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(t=!1,e){var r,n,s,o,a,i;try{const c=await this.commonHeaders({Accept:"text/event-stream"});e&&(c["last-event-id"]=e);const l=await fetch(this.url.href,{method:"GET",headers:c,signal:(r=this.abortController)==null?void 0:r.signal}),u=l.headers.get("mcp-session-id");if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!t){this.resourceMetadataUrl=lc(l);try{if(await uc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new cc;(n=this.onerror)==null||n.call(this,v);return}}catch(m){(s=this.onerror)==null||s.call(this,m);return}return this.openInboundSse(!0,e)}if(l.status===405)return;if(!l.ok||!l.body){const m=new Ve({message:`MCP HTTP Transport Error: GET SSE failed: ${l.status} ${l.statusText}`});(o=this.onerror)==null||o.call(this,m);return}const f=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new En).getReader(),p=async()=>{var m,v,_,w;try{for(;;){const{done:g,value:y}=await f.read();if(g)return;const{event:b,data:S,id:k}=y;if(k&&(this.lastInboundEventId=k),b==="message")try{const T=jo.parse(JSON.parse(S));(m=this.onmessage)==null||m.call(this,T)}catch(T){const x=new Ve({message:"MCP HTTP Transport Error: Failed to parse message",cause:T});(v=this.onerror)==null||v.call(this,x)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(_=this.onerror)==null||_.call(this,g),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(a=this.onerror)==null||a.call(this,c),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function pP(t){switch(t.type){case"sse":return new uP(t);case"http":return new dP(t);default:throw new Ve({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function hP(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var fP="1.0.0";async function mP(t){const e=new gP(t);return await e.init(),e}var gP=class{constructor({transport:t,name:e="ai-sdk-mcp-client",version:r=fP,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},hP(t)?this.transport=t:this.transport=pP(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new Ve({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:e,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:vs,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:vR});if(t===void 0)throw new Ve({message:"Server sent invalid initialize result"});if(!mR.includes(t.protocolVersion))throw new Ve({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ve({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ve({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ve({message:"Server does not support prompts"});break;default:throw new Ve({message:`Unsupported method: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new Ve({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const o=r?.signal;o?.throwIfAborted();const a=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:a},c=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,l=>{if(o?.aborted)return s(new Ve({message:"Request was aborted",cause:o.reason}));if(l instanceof Error)return s(l);try{const u=e.parse(l.result);n(u)}catch(u){const h=new Ve({message:"Failed to parse server response",cause:u});s(h)}}),this.transport.send(i).catch(l=>{c(),s(l)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:wR,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:kR,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:t,options:e}={}){try{return this.request({request:{method:"resources/list",params:t},resultSchema:SR,options:e})}catch(r){throw r}}async readResourceInternal({uri:t,options:e}){try{return this.request({request:{method:"resources/read",params:{uri:t}},resultSchema:$R,options:e})}catch(r){throw r}}async listResourceTemplatesInternal({options:t}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:TR,options:t})}catch(e){throw e}}async listPromptsInternal({params:t,options:e}={}){try{return this.request({request:{method:"prompts/list",params:t},resultSchema:IR,options:e})}catch(r){throw r}}async getPromptInternal({name:t,args:e,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:t,arguments:e}},resultSchema:PR,options:r})}catch(n){throw n}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:a}of n.tools){if(t!=="automatic"&&!(s in t))continue;const i=this,c=async(u,h)=>{var f;return(f=h?.abortSignal)==null||f.throwIfAborted(),i.callTool({name:s,args:u,options:h})},l=t==="automatic"?n_({description:o,inputSchema:Io({...a,properties:(e=a.properties)!=null?e:{},additionalProperties:!1}),execute:c}):{description:o,inputSchema:t[s].inputSchema,execute:c};r[s]=l}return r}catch(n){throw n}}listResources({params:t,options:e}={}){return this.listResourcesInternal({params:t,options:e})}readResource({uri:t,options:e}){return this.readResourceInternal({uri:t,options:e})}listResourceTemplates({options:t}={}){return this.listResourceTemplatesInternal({options:t})}listPrompts({params:t,options:e}={}){return this.listPromptsInternal({params:t,options:e})}getPrompt({name:t,arguments:e,options:r}){return this.getPromptInternal({name:t,args:e,options:r})}onElicitationRequest(t,e){if(t!==Ey)throw new Ve({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=e}async onRequestMessage(t){try{if(t.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Unsupported request method: ${t.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const e=Ey.safeParse({method:t.method,params:t.params});if(!e.success){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32602,message:`Invalid elicitation request: ${e.error.message}`,data:e.error.issues}});return}try{const r=await this.elicitationRequestHandler(e.data),n=AR.parse(r);await this.transport.send({jsonrpc:"2.0",id:t.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new Ve({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new Ve({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new Ve({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}},qy="vercel.ai.error",_P=Symbol.for(qy),jy,Uy,et=class yw extends(Uy=Error,jy=_P,Uy){constructor({name:e,message:r,cause:n}){super(r),this[jy]=!0,this.name=e,this.cause=n}static isInstance(e){return yw.hasMarker(e,qy)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},zy="AI_APICallError",Dy=`vercel.ai.error.${zy}`,vP=Symbol.for(Dy),Zy,Vy,Jt=class extends(Vy=et,Zy=vP,Vy){constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:zy,message:t,cause:a}),this[Zy]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=c}static isInstance(t){return et.hasMarker(t,Dy)}},Fy="AI_EmptyResponseBodyError",Hy=`vercel.ai.error.${Fy}`,yP=Symbol.for(Hy),By,Jy,wP=class extends(Jy=et,By=yP,Jy){constructor({message:t="Empty response body"}={}){super({name:Fy,message:t}),this[By]=!0}static isInstance(t){return et.hasMarker(t,Hy)}};function Wy(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Gy="AI_InvalidArgumentError",Ky=`vercel.ai.error.${Gy}`,bP=Symbol.for(Ky),Yy,Qy,Xy=class extends(Qy=et,Yy=bP,Qy){constructor({message:t,cause:e,argument:r}){super({name:Gy,message:t,cause:e}),this[Yy]=!0,this.argument=r}static isInstance(t){return et.hasMarker(t,Ky)}},e1="AI_InvalidPromptError",t1=`vercel.ai.error.${e1}`,SP=Symbol.for(t1),r1,n1,kP=class extends(n1=et,r1=SP,n1){constructor({prompt:t,message:e,cause:r}){super({name:e1,message:`Invalid prompt: ${e}`,cause:r}),this[r1]=!0,this.prompt=t}static isInstance(t){return et.hasMarker(t,t1)}},s1="AI_InvalidResponseDataError",o1=`vercel.ai.error.${s1}`,CP=Symbol.for(o1),a1,i1,op=class extends(i1=et,a1=CP,i1){constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:s1,message:e}),this[a1]=!0,this.data=t}static isInstance(t){return et.hasMarker(t,o1)}},c1="AI_JSONParseError",l1=`vercel.ai.error.${c1}`,TP=Symbol.for(l1),u1,d1,dc=class extends(d1=et,u1=TP,d1){constructor({text:t,cause:e}){super({name:c1,message:`JSON parsing failed: Text: ${t}.
|
|
574
|
-
Error message: ${
|
|
575
|
-
Error message: ${Wy(r)}`,cause:r}),this[S1]=!0,this.value=e}static isInstance(e){return et.hasMarker(e,b1)}static wrap({value:e,cause:r}){return Tp.isInstance(r)&&r.value===e?r:new Tp({value:e,cause:r})}},C1="AI_UnsupportedFunctionalityError",T1=`vercel.ai.error.${C1}`,RP=Symbol.for(T1),$1,E1,jr=class extends(E1=et,$1=RP,E1){constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:C1,message:e}),this[$1]=!0,this.functionality=t}static isInstance(t){return et.hasMarker(t,T1)}};function Cr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function Do(t){return Object.fromEntries([...t.headers])}var PP=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new Xy({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},ur=PP();function ap(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var OP=["fetch failed","failed to fetch"];function AP({error:t,url:e,requestBodyValues:r}){if(ap(t))return t;if(t instanceof TypeError&&OP.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Jt({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function MP(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function NP(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function x1(t,...e){const r=new Headers(NP(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var LP="3.0.20";function qP({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new pc({message:`${n} API key must be a string.`});if(typeof process>"u")throw new pc({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new pc({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new pc({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function jP({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function UP(t){var e;const[r,n=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?e:n}var zP=/"__proto__"\s*:/,DP=/"constructor"\s*:/;function I1(t){const e=JSON.parse(t);return e===null||typeof e!="object"||zP.test(t)===!1&&DP.test(t)===!1?e:ZP(e)}function ZP(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function ip(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return I1(t)}try{return I1(t)}finally{Error.stackTraceLimit=e}}var hc=Symbol.for("vercel.ai.validator");function VP(t){return{[hc]:!0,validate:t}}function FP(t){return typeof t=="object"&&t!==null&&hc in t&&t[hc]===!0&&"validate"in t}function St(t){let e;return()=>(e==null&&(e=t()),e)}function HP(t){return FP(t)?t:typeof t=="function"?t():BP(t)}function BP(t){return VP(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new zo({value:e,cause:r.issues})}})}async function cn({value:t,schema:e}){const r=await cp({value:t,schema:e});if(!r.success)throw zo.wrap({value:t,cause:r.error});return r.value}async function cp({value:t,schema:e}){const r=HP(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:zo.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:zo.wrap({value:t,cause:n}),rawValue:t}}}async function JP({text:t,schema:e}){try{const r=ip(t);return e==null?r:cn({value:r,schema:e})}catch(r){throw dc.isInstance(r)||zo.isInstance(r)?r:new dc({text:t,cause:r})}}async function R1({text:t,schema:e}){try{const r=ip(t);return e==null?{success:!0,value:r,rawValue:r}:await cp({value:r,schema:e})}catch(r){return{success:!1,error:dc.isInstance(r)?r:new dc({text:t,cause:r}),rawValue:void 0}}}function P1(t){try{return ip(t),!0}catch{return!1}}function WP({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new En).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await R1({text:r,schema:e}))}}))}async function ln({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await cp({value:e[t],schema:r});if(!n.success)throw new Xy({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var GP=()=>globalThis.fetch,Ur=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>O1({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),KP=async({url:t,headers:e,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>O1({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),O1=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=GP()})=>{try{const i=await a(t,{method:"POST",headers:x1(e,`ai-sdk/provider-utils/${LP}`,MP()),body:r.content,signal:o}),c=Do(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw ap(u)||Jt.isInstance(u)?u:new Jt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(ap(l)||Jt.isInstance(l))?l:new Jt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw AP({error:i,url:t,requestBodyValues:r.values})}};function zM(t){return t}function ws({id:t,name:e,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c,...l})=>({type:"provider-defined",id:t,name:e,args:l,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c})}var YP=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=Do(n);if(a.trim()==="")return{responseHeaders:i,value:new Jt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await JP({text:a,schema:t});return{responseHeaders:i,value:new Jt({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new Jt({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},lp=t=>async({response:e})=>{const r=Do(e);if(e.body==null)throw new wP({});return{responseHeaders:r,value:WP({stream:e.body,schema:t})}},bs=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await R1({text:s,schema:t}),a=Do(e);if(!o.success)throw new Jt({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},QP=()=>async({response:t,url:e,requestBodyValues:r})=>{const n=Do(t);if(!t.body)throw new Jt({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0});try{const s=await t.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new Jt({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0,cause:s})}};function fc(t){if(t.type==="object"){t.additionalProperties=!1;const e=t.properties;if(e!=null)for(const r in e)e[r]=fc(e[r])}return t.type==="array"&&t.items!=null&&(Array.isArray(t.items)?t.items=t.items.map(e=>fc(e)):t.items=fc(t.items)),t}var XP=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},eO=Symbol("Let zodToJsonSchema decide on which parser to use"),A1={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"},tO=t=>typeof t=="string"?{...A1,name:t}:{...A1,...t};function zt(){return{}}function rO(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==U.ZodAny&&(o.items=Fe(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function nO(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function sO(){return{type:"boolean"}}function M1(t,e){return Fe(t.type._def,e)}var oO=(t,e)=>Fe(t.innerType._def,e);function N1(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>N1(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return aO(t)}}var aO=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function iO(t,e){return{...Fe(t.innerType._def,e),default:t.defaultValue()}}function cO(t,e){return e.effectStrategy==="input"?Fe(t.schema._def,e):zt()}function lO(t){return{type:"string",enum:Array.from(t.values)}}var uO=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function dO(t,e){const r=[Fe(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Fe(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(uO(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function pO(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var up=void 0,dr={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:()=>(up===void 0&&(up=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),up),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 L1(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":pr(r,"email",n.message,e);break;case"format:idn-email":pr(r,"idn-email",n.message,e);break;case"pattern:zod":kt(r,dr.email,n.message,e);break}break;case"url":pr(r,"uri",n.message,e);break;case"uuid":pr(r,"uuid",n.message,e);break;case"regex":kt(r,n.regex,n.message,e);break;case"cuid":kt(r,dr.cuid,n.message,e);break;case"cuid2":kt(r,dr.cuid2,n.message,e);break;case"startsWith":kt(r,RegExp(`^${dp(n.value,e)}`),n.message,e);break;case"endsWith":kt(r,RegExp(`${dp(n.value,e)}$`),n.message,e);break;case"datetime":pr(r,"date-time",n.message,e);break;case"date":pr(r,"date",n.message,e);break;case"time":pr(r,"time",n.message,e);break;case"duration":pr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{kt(r,RegExp(dp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&pr(r,"ipv4",n.message,e),n.version!=="v4"&&pr(r,"ipv6",n.message,e);break}case"base64url":kt(r,dr.base64url,n.message,e);break;case"jwt":kt(r,dr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&kt(r,dr.ipv4Cidr,n.message,e),n.version!=="v4"&&kt(r,dr.ipv6Cidr,n.message,e);break}case"emoji":kt(r,dr.emoji(),n.message,e);break;case"ulid":{kt(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{kt(r,dr.base64,n.message,e);break}}break}case"nanoid":kt(r,dr.nanoid,n.message,e)}return r}function dp(t,e){return e.patternStrategy==="escape"?fO(t):t}var hO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function fO(t){let e="";for(let r=0;r<t.length;r++)hO.has(t[r])||(e+="\\"),e+=t[r];return e}function pr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function kt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:q1(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=q1(e,n)}function q1(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
|
|
573
|
+
`)}})}},yy={"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:t,statusText:e,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new gy);if(s){const[a,i]=o.tee();o=a,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:Ci(r,yy)})}function K$({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return r?.role==="assistant"?r.id:typeof e=="function"?e():e}function Y$(t){return t.type.startsWith("data-")}function _y(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(s===void 0)continue;const o=n in t?t[n]:void 0,a=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&i?r[n]=_y(o,s):r[n]=s}return r}function Q$(t){const e=["ROOT"];let r=-1,n=null;function s(c,l,u){switch(c){case'"':{r=l,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=l,n=l,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=l,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=l,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function o(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=l,e.pop();break}}}function a(c,l){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}}}for(let c=0;c<t.length;c++){const l=t[c];switch(e[e.length-1]){case"ROOT":s(l,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(l,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,c);break}case"INSIDE_STRING":{switch(l){case'"':{e.pop(),r=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{r=c,e.pop();break}default:{r=c,s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(l,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=c;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,c+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,c)):r=c;break}}}let i=t.slice(0,r+1);for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(n,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function vy(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await wn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await wn({text:Q$(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Wu(t){return t.type.startsWith("tool-")}function wy(t){return t.type.split("-").slice(1).join("-")}function X$({lastMessage:t,messageId:e}){return{message:t?.role==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function eE({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:a}){return t.pipeThrough(new TransformStream({async transform(i,c){await n(async({state:l,write:u})=>{var p,h,d,f;function v(b){const S=l.message.parts.filter(Wu).find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(b){const S=l.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function w(b){var k;const S=l.message.parts.find(R=>Wu(R)&&R.toolCallId===b.toolCallId),C=b,x=S;S!=null?(S.state=b.state,x.input=C.input,x.output=C.output,x.errorText=C.errorText,x.rawInput=C.rawInput,x.preliminary=C.preliminary,x.providerExecuted=(k=C.providerExecuted)!=null?k:S.providerExecuted,C.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=C.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function g(b){var k,S;const C=l.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===b.toolCallId),x=b,R=C;C!=null?(C.state=b.state,R.toolName=b.toolName,R.input=x.input,R.output=x.output,R.errorText=x.errorText,R.rawInput=(k=x.rawInput)!=null?k:R.rawInput,R.preliminary=x.preliminary,R.providerExecuted=(S=x.providerExecuted)!=null?S:C.providerExecuted,x.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=x.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function _(b){if(b!=null){const k=l.message.metadata!=null?_y(l.message.metadata,b):b;e!=null&&await vu({value:k,schema:e}),l.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeTextParts[i.id]=b,l.message.parts.push(b),u();break}case"text-delta":{const b=l.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,u();break}case"text-end":{const b=l.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete l.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};l.activeReasoningParts[i.id]=b,l.message.parts.push(b),u();break}case"reasoning-delta":{const b=l.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=l.activeReasoningParts[i.id];b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,b.state="done",delete l.activeReasoningParts[i.id],u();break}case"file":{l.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=l.message.parts.filter(Wu);l.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=l.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await vy(b.text);b.dynamic?g({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):w({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=y(i.toolCallId);g({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:wy(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=y(i.toolCallId);g({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=v(i.toolCallId);w({toolCallId:i.toolCallId,toolName:wy(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{i.messageId!=null&&(l.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(l.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{s?.(new Error(i.errorText));break}default:if(Y$(i)){r?.[i.type]!=null&&await vu({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?l.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:l.message.parts.push(b),a?.(b),u()}}c.enqueue(i)})}}))}function tE({messageId:t,originalMessages:e=[],onFinish:r,onError:n,stream:s}){let o=e?.[e.length-1];o?.role!=="assistant"?o=void 0:t=o.id;let a=!1;const i=s.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const f=h;f.messageId==null&&t!=null&&(f.messageId=t)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const c=X$({lastMessage:o?structuredClone(o):void 0,messageId:t??""}),l=async h=>{await h({state:c,write:()=>{}})};let u=!1;const p=async()=>{if(u||!r)return;u=!0;const h=c.message.id===o?.id;await r({isAborted:a,isContinuation:h,responseMessage:c.message,messages:[...h?e.slice(0,-1):e,c.message],finishReason:c.finishReason})};return eE({stream:i,runUpdateMessageJob:l,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function rE({response:t,status:e,statusText:r,headers:n,stream:s,consumeSseStream:o}){let a=s.pipeThrough(new gy);if(o){const[i,c]=a.tee();a=i,o({stream:c})}my({response:t,status:e,statusText:r,headers:Object.fromEntries(Ci(n,yy).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ti(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var a;n=!0;try{o&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:a}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},e}async function nE({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){e?.(n)}finally{r.releaseLock()}}function by(){let t,e;return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}function sE(){let t=[],e=null,r=!1,n=by();const s=()=>{r=!0,n.resolve(),t.forEach(a=>a.cancel()),t=[],e?.close()},o=async()=>{if(r&&t.length===0){e?.close();return}if(t.length===0)return n=by(),await n.promise,o();try{const{value:a,done:i}=await t[0].read();i?(t.shift(),t.length>0?await o():r&&e?.close()):e?.enqueue(a)}catch(a){e?.error(a),t.shift(),s()}};return{stream:new ReadableStream({start(a){e=a},pull:o,async cancel(){for(const a of t)await a.cancel();t=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),t.length===0&&e?.close()},terminate:s}}function oE(){var t,e;return(e=(t=globalThis?.performance)==null?void 0:t.now())!=null?e:Date.now()}function aE({tools:t,generatorStream:e,tracer:r,telemetry:n,system:s,messages:o,abortSignal:a,repairToolCall:i,experimental_context:c}){let l=null;const u=new ReadableStream({start(w){l=w}}),p=new Set,h=new Map;let d=!1,f;function v(){d&&p.size===0&&(f!=null&&l.enqueue(f),l.close())}const y=new TransformStream({async transform(w,g){const _=w.type;switch(_){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{g.enqueue(w);break}case"file":{g.enqueue({type:"file",file:new Z$({data:w.data,mediaType:w.mediaType})});break}case"finish":{f={type:"finish",finishReason:w.finishReason,usage:w.usage,providerMetadata:w.providerMetadata};break}case"tool-call":{try{const b=await cy({toolCall:w,tools:t,repairToolCall:i,system:s,messages:o});if(g.enqueue(b),b.invalid){l.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:yu(b.error),dynamic:!0});break}const k=t[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}),k.execute!=null&&b.providerExecuted!==!0){const S=po();p.add(S),os({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...ss({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async C=>{let x;try{const R=_2({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:c}});for await(const j of R)l.enqueue({...b,type:"tool-result",output:j.output,...j.type==="preliminary"&&{preliminary:!0}}),j.type==="final"&&(x=j.output)}catch(R){Fu(C,R),l.enqueue({...b,type:"tool-error",error:R}),p.delete(S),v();return}p.delete(S),v();try{C.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(b){l.enqueue({type:"error",error:b})}break}case"tool-result":{const b=w.toolName;w.isError?l.enqueue({type:"tool-error",toolCallId:w.toolCallId,toolName:b,input:h.get(w.toolCallId),providerExecuted:w.providerExecuted,error:w.result}):g.enqueue({type:"tool-result",toolCallId:w.toolCallId,toolName:b,input:h.get(w.toolCallId),output:w.result,providerExecuted:w.providerExecuted});break}default:{const b=_;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,v()}});return new ReadableStream({async start(w){return Promise.all([e.pipeThrough(y).pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){}})),u.pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){w.close()}}))])}})}var iE=uo({prefix:"aitxt",size:24});function Gu({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:c,stopWhen:l=Hu(1),experimental_output:u,experimental_telemetry:p,prepareStep:h,providerOptions:d,experimental_activeTools:f,activeTools:v=f,experimental_repairToolCall:y,experimental_transform:w,experimental_download:g,includeRawChunks:_=!1,onChunk:b,onError:k=({error:V})=>{console.error(V)},onFinish:S,onAbort:C,onStepFinish:x,experimental_context:R,_internal:{now:j=oE,generateId:O=iE,currentDate:D=()=>new Date}={},...U}){return new lE({model:ki(t),telemetry:p,headers:c,settings:U,maxRetries:a,abortSignal:i,system:n,prompt:s,messages:o,tools:e,toolChoice:r,transforms:Vu(w),activeTools:v,repairToolCall:y,stopConditions:Vu(l),output:u,providerOptions:d,prepareStep:h,includeRawChunks:_,onChunk:b,onError:k,onFinish:S,onAbort:C,onStepFinish:x,now:j,currentDate:D,generateId:O,experimental_context:R,download:g})}function cE(t){if(!t)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let e,r="",n="",s="";function o({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:e,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&o({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(e==null)e=a.id;else if(a.id!==e){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const c=await t.parsePartial({text:r});if(c!=null){const l=JSON.stringify(c.partial);l!==s&&(o({controller:i,partialOutput:c.partial}),s=l)}}})}var lE=class{constructor({model:t,telemetry:e,headers:r,settings:n,maxRetries:s,abortSignal:o,system:a,prompt:i,messages:c,tools:l,toolChoice:u,transforms:p,activeTools:h,repairToolCall:d,stopConditions:f,output:v,providerOptions:y,prepareStep:w,includeRawChunks:g,now:_,currentDate:b,generateId:k,onChunk:S,onError:C,onFinish:x,onAbort:R,onStepFinish:j,experimental_context:O,download:D}){this._totalUsage=new hi,this._finishReason=new hi,this._steps=new hi,this.output=v,this.includeRawChunks=g,this.tools=l;let U,V=[];const ne=[];let fe,de,te={},ye=[];const H=[];let P,F={},q={};const E=new TransformStream({async transform(K,Q){var ue,he,Ve,Be;Q.enqueue(K);const{part:X}=K;if((X.type==="text-delta"||X.type==="reasoning-delta"||X.type==="source"||X.type==="tool-call"||X.type==="tool-result"||X.type==="tool-input-start"||X.type==="tool-input-delta"||X.type==="raw")&&await S?.({chunk:X}),X.type==="error"&&await C({error:Xg(X.error)}),X.type==="text-start"&&(F[X.id]={type:"text",text:"",providerMetadata:X.providerMetadata},V.push(F[X.id])),X.type==="text-delta"){const ke=F[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}ke.text+=X.text,ke.providerMetadata=(ue=X.providerMetadata)!=null?ue:ke.providerMetadata}if(X.type==="text-end"){const ke=F[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(he=X.providerMetadata)!=null?he:ke.providerMetadata,delete F[X.id]}if(X.type==="reasoning-start"&&(q[X.id]={type:"reasoning",text:"",providerMetadata:X.providerMetadata},V.push(q[X.id])),X.type==="reasoning-delta"){const ke=q[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}ke.text+=X.text,ke.providerMetadata=(Ve=X.providerMetadata)!=null?Ve:ke.providerMetadata}if(X.type==="reasoning-end"){const ke=q[X.id];if(ke==null){Q.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}ke.providerMetadata=(Be=X.providerMetadata)!=null?Be:ke.providerMetadata,delete q[X.id]}if(X.type==="file"&&V.push({type:"file",file:X.file}),X.type==="source"&&V.push(X),X.type==="tool-call"&&V.push(X),X.type==="tool-result"&&!X.preliminary&&V.push(X),X.type==="tool-error"&&V.push(X),X.type==="start-step"&&(te=X.request,ye=X.warnings),X.type==="finish-step"){const ke=Ju({content:V,tools:l}),wt=new uy({content:V,finishReason:X.finishReason,usage:X.usage,warnings:ye,request:te,response:{...X.response,messages:[...ne,...ke]},providerMetadata:X.providerMetadata});await j?.(wt),fg(ye),H.push(wt),V=[],q={},F={},ne.push(...ke),U.resolve()}X.type==="finish"&&(de=X.totalUsage,fe=X.finishReason)},async flush(K){try{if(H.length===0){const Ve=new i$({message:"No output generated. Check the stream for errors."});W._finishReason.reject(Ve),W._totalUsage.reject(Ve),W._steps.reject(Ve);return}const Q=fe??"unknown",ue=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};W._finishReason.resolve(Q),W._totalUsage.resolve(ue),W._steps.resolve(H);const he=H[H.length-1];await x?.({finishReason:Q,totalUsage:ue,usage:he.usage,content:he.content,text:he.text,reasoningText:he.reasoningText,reasoning:he.reasoning,files:he.files,sources:he.sources,toolCalls:he.toolCalls,staticToolCalls:he.staticToolCalls,dynamicToolCalls:he.dynamicToolCalls,toolResults:he.toolResults,staticToolResults:he.staticToolResults,dynamicToolResults:he.dynamicToolResults,request:he.request,response:he.response,warnings:he.warnings,providerMetadata:he.providerMetadata,steps:H}),P.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":Q,"ai.response.text":{output:()=>he.text},"ai.response.toolCalls":{output:()=>{var Ve;return(Ve=he.toolCalls)!=null&&Ve.length?JSON.stringify(he.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(he.providerMetadata),"ai.usage.inputTokens":ue.inputTokens,"ai.usage.outputTokens":ue.outputTokens,"ai.usage.totalTokens":ue.totalTokens,"ai.usage.reasoningTokens":ue.reasoningTokens,"ai.usage.cachedInputTokens":ue.cachedInputTokens}}))}catch(Q){K.error(Q)}finally{P.end()}}}),I=sE();this.addStream=I.addStream,this.closeStream=I.close;const $=I.stream.getReader();let B=new ReadableStream({async start(K){K.enqueue({type:"start"})},async pull(K){function Q(){R?.({steps:H}),K.enqueue({type:"abort"}),K.close()}try{const{done:ue,value:he}=await $.read();if(ue){K.close();return}if(o?.aborted){Q();return}K.enqueue(he)}catch(ue){vn(ue)&&o?.aborted?Q():K.error(ue)}},cancel(K){return I.stream.cancel(K)}});for(const K of p)B=B.pipeThrough(K({tools:l,stopStream(){I.terminate()}}));this.baseStream=B.pipeThrough(cE(v)).pipeThrough(E);const{maxRetries:G,retry:_e}=oy({maxRetries:s,abortSignal:o}),pe=ty(e),A=Zu(n),Z=ey({model:t,telemetry:e,headers:r,settings:{...A,maxRetries:G}}),W=this;os({name:"ai.streamText",attributes:Dt({telemetry:e,attributes:{...ss({operationId:"ai.streamText",telemetry:e}),...Z,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:c})}}}),tracer:pe,endWhenDone:!1,fn:async K=>{P=K;async function Q({currentStep:ue,responseMessages:he,usage:Ve}){var Be,X,ke,wt,Ee;const $t=W.includeRawChunks;U=new hi;const Or=await Qg({system:a,prompt:i,messages:c}),Et=[...Or.messages,...he],ct=await w?.({model:t,steps:H,stepNumber:H.length,messages:Et}),Zt=ki((Be=ct?.model)!=null?Be:t),en=await Jg({prompt:{system:(X=ct?.system)!=null?X:Or.system,messages:(ke=ct?.messages)!=null?ke:Et},supportedUrls:await Zt.supportedUrls,download:D}),{toolChoice:tn,tools:ds}=Wg({tools:l,toolChoice:(wt=ct?.toolChoice)!=null?wt:u,activeTools:(Ee=ct?.activeTools)!=null?Ee:h}),{result:{stream:qi,response:rt,request:Ar},doStreamSpan:Mr,startTimestampMs:g_}=await _e(()=>os({name:"ai.streamText.doStream",attributes:Dt({telemetry:e,attributes:{...ss({operationId:"ai.streamText.doStream",telemetry:e}),...Z,"ai.model.provider":Zt.provider,"ai.model.id":Zt.modelId,"ai.prompt.messages":{input:()=>ry(en)},"ai.prompt.tools":{input:()=>ds?.map(ve=>JSON.stringify(ve))},"ai.prompt.toolChoice":{input:()=>tn!=null?JSON.stringify(tn):void 0},"gen_ai.system":Zt.provider,"gen_ai.request.model":Zt.modelId,"gen_ai.request.frequency_penalty":A.frequencyPenalty,"gen_ai.request.max_tokens":A.maxOutputTokens,"gen_ai.request.presence_penalty":A.presencePenalty,"gen_ai.request.stop_sequences":A.stopSequences,"gen_ai.request.temperature":A.temperature,"gen_ai.request.top_k":A.topK,"gen_ai.request.top_p":A.topP}}),tracer:pe,endWhenDone:!1,fn:async ve=>({startTimestampMs:_(),doStreamSpan:ve,result:await Zt.doStream({...A,tools:ds,toolChoice:tn,responseFormat:v?.responseFormat,prompt:en,providerOptions:y,abortSignal:o,headers:r,includeRawChunks:$t})})})),vR=aE({tools:l,generatorStream:qi,tracer:pe,telemetry:e,system:a,messages:Et,repairToolCall:d,abortSignal:o,experimental_context:O}),wR=Ar??{},zi=[],dd=[];let pd;const fd={};let ps="unknown",ar={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},hd,y_=!0,yr={id:k(),timestamp:b(),modelId:t.modelId},__="";W.addStream(vR.pipeThrough(new TransformStream({async transform(ve,lt){var xo,Io,Di,Nr;if(ve.type==="stream-start"){pd=ve.warnings;return}if(y_){const bt=_()-g_;y_=!1,Mr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":bt}),Mr.setAttributes({"ai.response.msToFirstChunk":bt}),lt.enqueue({type:"start-step",request:wR,warnings:pd??[]})}const v_=ve.type;switch(v_){case"text-start":case"text-end":{lt.enqueue(ve);break}case"text-delta":{ve.delta.length>0&&(lt.enqueue({type:"text-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata}),__+=ve.delta);break}case"reasoning-start":case"reasoning-end":{lt.enqueue(ve);break}case"reasoning-delta":{lt.enqueue({type:"reasoning-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata});break}case"tool-call":{lt.enqueue(ve),zi.push(ve);break}case"tool-result":{lt.enqueue(ve),ve.preliminary||dd.push(ve);break}case"tool-error":{lt.enqueue(ve),dd.push(ve);break}case"response-metadata":{yr={id:(xo=ve.id)!=null?xo:yr.id,timestamp:(Io=ve.timestamp)!=null?Io:yr.timestamp,modelId:(Di=ve.modelId)!=null?Di:yr.modelId};break}case"finish":{ar=ve.usage,ps=ve.finishReason,hd=ve.providerMetadata;const bt=_()-g_;Mr.addEvent("ai.stream.finish"),Mr.setAttributes({"ai.response.msToFinish":bt,"ai.response.avgOutputTokensPerSecond":1e3*((Nr=ar.outputTokens)!=null?Nr:0)/bt});break}case"file":{lt.enqueue(ve);break}case"source":{lt.enqueue(ve);break}case"tool-input-start":{fd[ve.id]=ve.toolName;const bt=l?.[ve.toolName];bt?.onInputStart!=null&&await bt.onInputStart({toolCallId:ve.id,messages:Et,abortSignal:o,experimental_context:O}),lt.enqueue({...ve,dynamic:bt?.type==="dynamic"});break}case"tool-input-end":{delete fd[ve.id],lt.enqueue(ve);break}case"tool-input-delta":{const bt=fd[ve.id],md=l?.[bt];md?.onInputDelta!=null&&await md.onInputDelta({inputTextDelta:ve.delta,toolCallId:ve.id,messages:Et,abortSignal:o,experimental_context:O}),lt.enqueue(ve);break}case"error":{lt.enqueue(ve),ps="error";break}case"raw":{$t&<.enqueue(ve);break}default:{const bt=v_;throw new Error(`Unknown chunk type: ${bt}`)}}},async flush(ve){const lt=zi.length>0?JSON.stringify(zi):void 0;try{Mr.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":ps,"ai.response.text":{output:()=>__},"ai.response.toolCalls":{output:()=>lt},"ai.response.id":yr.id,"ai.response.model":yr.modelId,"ai.response.timestamp":yr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(hd),"ai.usage.inputTokens":ar.inputTokens,"ai.usage.outputTokens":ar.outputTokens,"ai.usage.totalTokens":ar.totalTokens,"ai.usage.reasoningTokens":ar.reasoningTokens,"ai.usage.cachedInputTokens":ar.cachedInputTokens,"gen_ai.response.finish_reasons":[ps],"gen_ai.response.id":yr.id,"gen_ai.response.model":yr.modelId,"gen_ai.usage.input_tokens":ar.inputTokens,"gen_ai.usage.output_tokens":ar.outputTokens}}))}catch{}finally{Mr.end()}ve.enqueue({type:"finish-step",finishReason:ps,usage:ar,providerMetadata:hd,response:{...yr,headers:rt?.headers}});const xo=ny(Ve,ar);await U.promise;const Io=zi.filter(Nr=>Nr.providerExecuted!==!0),Di=dd.filter(Nr=>Nr.providerExecuted!==!0);if(Io.length>0&&Di.length===Io.length&&!await dy({stopConditions:f,steps:H})){he.push(...Ju({content:H[H.length-1].content,tools:l}));try{await Q({currentStep:ue+1,responseMessages:he,usage:xo})}catch(Nr){ve.enqueue({type:"error",error:Nr}),W.closeStream()}}else ve.enqueue({type:"finish",finishReason:ps,totalUsage:xo}),W.closeStream()}})))}await Q({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(K=>{W.addStream(new ReadableStream({start(Q){Q.enqueue({type:"error",error:K}),Q.close()}})),W.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return Ti(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return Ti(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await nE({stream:this.fullStream,onError:t?.onError})}catch(r){(e=t?.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new dg;return Ti(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:i=!0,onError:c=Yn}={}){const l=e!=null?K$({originalMessages:t,responseMessageId:e}):void 0,u={},p=d=>{var f,v;const y=u[d];return((v=(f=this.tools)==null?void 0:f[y])==null?void 0:v.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const v=n?.({part:d}),y=d.type;switch(y){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{s&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{o&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),o&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const w=p(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const w=p(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...w!=null?{dynamic:w}:{},errorText:c(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...w!=null?{dynamic:w}:{}});break}case"tool-result":{const w=p(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=p(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:c(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"error":{f.enqueue({type:"error",errorText:c(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...l!=null?{messageId:l}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:d.finishReason,...v!=null?{messageMetadata:v}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const w=y;throw new Error(`Unknown chunk type: ${w}`)}}v!=null&&y!=="start"&&y!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:v})}}));return Ti(tE({stream:h,messageId:l??e?.(),originalMessages:t,onFinish:r,onError:c}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l,...u}={}){rE({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:c,onError:l}),...u})}pipeTextStreamToResponse(t,e){W$({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c,...l}={}){return G$({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:c}),...l})}toTextStreamResponse(t){return J$({textStream:this.textStream,...t})}};uo({prefix:"aiobj",size:24}),uo({prefix:"aiobj",size:24});var uE={};X8(uE,{object:()=>pE,text:()=>dE});var dE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),pE=({schema:t})=>{const e=yi(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const n=await vy(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await wn({text:r});if(!s.success)throw new Cg({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await er({value:s.value,schema:e});if(!o.success)throw new Cg({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},fE="AI_MCPClientError",ky=`vercel.ai.error.${fE}`,hE=Symbol.for(ky),Sy,Cy,De=class extends(Cy=we,Sy=hE,Cy){constructor({name:t="MCPClientError",message:e,cause:r,data:n,code:s}){super({name:t,message:e,cause:r}),this[Sy]=!0,this.data=n,this.code=s}static isInstance(t){return we.hasMarker(t,ky)}},as="2025-06-18",mE=[as,"2025-03-26","2024-11-05"],gE=Ke({name:m(),version:m()}),$i=Ke({_meta:le(T({}).loose())}),Ir=$i,Ty=T({method:m(),params:le($i)}),$y=T({applyDefaults:le(me())}).loose(),yE=Ke({experimental:le(T({}).loose()),logging:le(T({}).loose()),prompts:le(Ke({listChanged:le(me())})),resources:le(Ke({subscribe:le(me()),listChanged:le(me())})),tools:le(Ke({listChanged:le(me())})),elicitation:le($y)});T({elicitation:le($y)}).loose();var _E=Ir.extend({protocolVersion:m(),capabilities:yE,serverInfo:gE,instructions:le(m())}),Ku=Ir.extend({nextCursor:le(m())}),vE=T({name:m(),description:le(m()),inputSchema:T({type:L("object"),properties:le(T({}).loose())}).loose()}).loose(),wE=Ku.extend({tools:M(vE)}),Ey=T({type:L("text"),text:m()}).loose(),xy=T({type:L("image"),data:Kf(),mimeType:m()}).loose(),bE=T({uri:m(),name:m(),title:le(m()),description:le(m()),mimeType:le(m()),size:le(N())}).loose(),kE=Ku.extend({resources:M(bE)}),Iy=T({uri:m(),name:le(m()),title:le(m()),mimeType:le(m())}).loose(),Ry=Iy.extend({text:m()}),Py=Iy.extend({blob:Kf()}),Oy=T({type:L("resource"),resource:ie([Ry,Py])}).loose(),SE=Ir.extend({content:M(ie([Ey,xy,Oy])),isError:me().default(!1).optional()}).or(Ir.extend({toolResult:Pe()})),CE=T({uriTemplate:m(),name:m(),title:le(m()),description:le(m()),mimeType:le(m())}).loose(),TE=Ir.extend({resourceTemplates:M(CE)}),$E=Ir.extend({contents:M(ie([Ry,Py]))}),EE=T({name:m(),description:le(m()),required:le(me())}).loose(),xE=T({name:m(),title:le(m()),description:le(m()),arguments:le(M(EE))}).loose(),IE=Ku.extend({prompts:M(xE)}),RE=T({role:ie([L("user"),L("assistant")]),content:ie([Ey,xy,Oy])}).loose(),PE=Ir.extend({description:le(m()),messages:M(RE)}),OE=$i.extend({message:m(),requestedSchema:Pe()}),Ay=Ty.extend({method:L("elicitation/create"),params:OE}),AE=Ir.extend({action:ie([L("accept"),L("decline"),L("cancel")]),content:le(be(m(),Pe()))}),Ei="2.0",ME=T({jsonrpc:L(Ei),id:ie([m(),N().int()])}).merge(Ty).strict(),NE=T({jsonrpc:L(Ei),id:ie([m(),N().int()]),result:Ir}).strict(),LE=T({jsonrpc:L(Ei),id:ie([m(),N().int()]),error:T({code:N().int(),message:m(),data:le(Pe())})}).strict(),jE=T({jsonrpc:L(Ei)}).merge(T({method:m(),params:le($i)})).strict(),So=ie([ME,jE,NE,LE]),My=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Ny=T({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:N().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Tt=m().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:ih.custom,message:"URL must be parseable",fatal:!0}),sf}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),qE=T({resource:m().url(),authorization_servers:M(Tt).optional(),jwks_uri:m().url().optional(),scopes_supported:M(m()).optional(),bearer_methods_supported:M(m()).optional(),resource_signing_alg_values_supported:M(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:me().optional(),authorization_details_types_supported:M(m()).optional(),dpop_signing_alg_values_supported:M(m()).optional(),dpop_bound_access_tokens_required:me().optional()}).passthrough(),Ly=T({issuer:m(),authorization_endpoint:Tt,token_endpoint:Tt,registration_endpoint:Tt.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),grant_types_supported:M(m()).optional(),code_challenge_methods_supported:M(m()),token_endpoint_auth_methods_supported:M(m()).optional(),token_endpoint_auth_signing_alg_values_supported:M(m()).optional()}).passthrough(),zE=T({issuer:m(),authorization_endpoint:Tt,token_endpoint:Tt,userinfo_endpoint:Tt.optional(),jwks_uri:Tt,registration_endpoint:Tt.optional(),scopes_supported:M(m()).optional(),response_types_supported:M(m()),grant_types_supported:M(m()).optional(),subject_types_supported:M(m()),id_token_signing_alg_values_supported:M(m()),claims_supported:M(m()).optional(),token_endpoint_auth_methods_supported:M(m()).optional()}).passthrough(),DE=zE.merge(Ly.pick({code_challenge_methods_supported:!0})),UE=T({client_id:m(),client_secret:m().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),ZE=T({redirect_uris:M(Tt),token_endpoint_auth_method:m().optional(),grant_types:M(m()).optional(),response_types:M(m()).optional(),client_name:m().optional(),client_uri:Tt.optional(),logo_uri:Tt.optional(),scope:m().optional(),contacts:M(m()).optional(),tos_uri:Tt.optional(),policy_uri:m().optional(),jwks_uri:Tt.optional(),jwks:ht().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),FE=T({error:m(),error_description:m().optional(),error_uri:m().optional()}),VE=ZE.merge(UE),HE="AI_MCPClientOAuthError",jy=`vercel.ai.error.${HE}`,BE=Symbol.for(jy),qy,zy,Co=class extends(zy=we,qy=BE,zy){constructor({name:t="MCPClientOAuthError",message:e,cause:r}){super({name:t,message:e,cause:r}),this[qy]=!0}static isInstance(t){return we.hasMarker(t,jy)}},is=class extends Co{};is.errorCode="server_error";var xi=class extends Co{};xi.errorCode="invalid_client";var Ii=class extends Co{};Ii.errorCode="invalid_grant";var Ri=class extends Co{};Ri.errorCode="unauthorized_client";var JE={[is.errorCode]:is,[xi.errorCode]:xi,[Ii.errorCode]:Ii,[Ri.errorCode]:Ri};function WE(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function GE({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var Pi=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Oi(t){var e;const r=(e=t.headers.get("www-authenticate"))!=null?e:t.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,a=r.match(o);if(a)try{return new URL(a[1])}catch{return}}function KE(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Yu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Yu(t,void 0,r):void 0;throw n}}async function Dy(t,e,r=fetch){return await Yu(t,{"MCP-Protocol-Version":e},r)}function YE(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function QE(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!=null?s:as;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const u=KE(e,a.pathname);c=new URL(u,(o=n?.metadataServerUrl)!=null?o:a),c.search=a.search}let l=await Dy(c,i,r);if(!n?.metadataUrl&&YE(l,a.pathname)){const u=new URL(`/.well-known/${e}`,a);l=await Dy(u,i,r)}return l}async function XE(t,e,r=fetch){const n=await QE(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return qE.parse(await n.json())}function e7(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function t7(t,{fetchFn:e=fetch,protocolVersion:r=as}={}){var n;const s={"MCP-Protocol-Version":r},o=e7(t);for(const{url:a,type:i}of o){const c=await Yu(a,s,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return Ly.parse(await c.json());{const l=DE.parse(await c.json());if(!((n=l.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return l}}}}async function r7(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){const i="code",c="S256";let l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",t);const u=await p0(),p=u.code_verifier,h=u.code_challenge;return l.searchParams.set("response_type",i),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",h),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(n)),o&&l.searchParams.set("state",o),s&&l.searchParams.set("scope",s),s?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:p}}function Uy(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Zy(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":n7(s,o,r);return;case"client_secret_post":s7(s,o,n);return;case"none":o7(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function n7(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function s7(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function o7(t,e){e.set("client_id",t)}async function Qu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=FE.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=JE[s]||is;return new i({message:o||"",cause:a})}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new is({message:s})}}async function a7(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:c}){var l;const u="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,d,t,e);else{const v=(l=e?.token_endpoint_auth_methods_supported)!=null?l:[],y=Uy(r,v);Zy(y,r,h,d)}a&&d.set("resource",a.href);const f=await(c??fetch)(p,{method:"POST",headers:h,body:d});if(!f.ok)throw await Qu(f);return Ny.parse(await f.json())}async function i7(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const c="refresh_token";let l;if(e){if(l=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(u,p,t,e);else{const d=(i=e?.token_endpoint_auth_methods_supported)!=null?i:[],f=Uy(r,d);Zy(f,r,u,p)}s&&p.set("resource",s.href);const h=await(a??fetch)(l,{method:"POST",headers:u,body:p});if(!h.ok)throw await Qu(h);return Ny.parse({refresh_token:n,...await h.json()})}async function c7(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Qu(o);return VE.parse(await o.json())}async function Ai(t,e){var r,n;try{return await Xu(t,e)}catch(s){if(s instanceof xi||s instanceof Ri)return await((r=t.invalidateCredentials)==null?void 0:r.call(t,"all")),await Xu(t,e);if(s instanceof Ii)return await((n=t.invalidateCredentials)==null?void 0:n.call(t,"tokens")),await Xu(t,e);throw s}}async function l7(t,e,r){const n=WE(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!GE({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 Xu(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await XE(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=e);const c=await l7(e,t,a),l=await t7(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await c7(i,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),y=await a7(i,{metadata:l,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(y),"AUTHORIZED"}const p=await t.tokens();if(p?.refresh_token)try{const v=await i7(i,{metadata:l,clientInformation:u,refreshToken:p.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Co)||v instanceof is))throw v}const h=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:f}=await r7(i,{metadata:l,clientInformation:u,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(f),await t.redirectToAuthorization(d),"REDIRECT"}var u7=class{constructor({url:t,headers:e,authProvider:r}){this.connected=!1,this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":as};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Kr(e,`ai-sdk/${My}`,fo())}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,a,i,c;try{const l=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:l,signal:(s=this.abortController)==null?void 0:s.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Oi(u);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Pi;return(o=this.onerror)==null||o.call(this,v),e(v)}}catch(f){return(a=this.onerror)==null||a.call(this,f),e(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const v=new De({message:f});return(i=this.onerror)==null||i.call(this,v),e(v)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),d=async()=>{var f,v,y;try{for(;;){const{done:w,value:g}=await h.read();if(w){if(this.connected)throw this.connected=!1,new De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:_,data:b}=g;if(_==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new De({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,t()}else if(_==="message")try{const k=So.parse(JSON.parse(b));(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(v=this.onerror)==null||v.call(this,S)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(y=this.onerror)==null||y.call(this,w),e(w)}};this.sseConnection={close:()=>h.cancel()},d()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(c=this.onerror)==null||c.call(this,l),e(l)}};r()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){if(!this.endpoint||!this.connected)throw new De({message:"MCP SSE Transport Error: Not connected"});const e=this.endpoint,r=async(n=!1)=>{var s,o,a,i,c;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(t),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(e,u);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Oi(p);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new Pi;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),d=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(l){(c=this.onerror)==null||c.call(this,l);return}};await r()}},d7=class{constructor({url:t,headers:e,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":as};if(this.sessionId&&(e["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Kr(e,`ai-sdk/${My}`,fo())}async start(){if(this.abortController)throw new De({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var t,e,r;(t=this.inboundSseConnection)==null||t.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){const e=async(r=!1)=>{var n,s,o,a,i,c,l;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(t),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Oi(h);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Pi}catch(y){throw(s=this.onerror)==null||s.call(this,y),y}return e(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const y=await h.text().catch(()=>null);let w=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${y}`;h.status===404&&(w+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new De({message:w});throw(o=this.onerror)==null||o.call(this,g),g}const f=h.headers.get("content-type")||"";if(f.includes("application/json")){const y=await h.json(),w=Array.isArray(y)?y.map(g=>So.parse(g)):[So.parse(y)];for(const g of w)(a=this.onmessage)==null||a.call(this,g);return}if(f.includes("text/event-stream")){if(!h.body){const _=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,_),_}const w=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader();(async()=>{var _,b,k;try{for(;;){const{done:S,value:C}=await w.read();if(S)return;const{event:x,data:R}=C;if(x==="message")try{const j=So.parse(JSON.parse(R));(_=this.onmessage)==null||_.call(this,j)}catch(j){const O=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:j});(b=this.onerror)==null||b.call(this,O)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const v=new De({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`});throw(c=this.onerror)==null||c.call(this,v),v}catch(u){throw(l=this.onerror)==null||l.call(this,u),u}};await e()}getNextReconnectionDelay(t){const{initialReconnectionDelay:e,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(e*Math.pow(r,t),n)}scheduleInboundSseReconnection(){var t;const{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){(t=this.onerror)==null||t.call(this,new De({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(t=!1,e){var r,n,s,o,a,i;try{const c=await this.commonHeaders({Accept:"text/event-stream"});e&&(c["last-event-id"]=e);const l=await fetch(this.url.href,{method:"GET",headers:c,signal:(r=this.abortController)==null?void 0:r.signal}),u=l.headers.get("mcp-session-id");if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!t){this.resourceMetadataUrl=Oi(l);try{if(await Ai(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Pi;(n=this.onerror)==null||n.call(this,v);return}}catch(f){(s=this.onerror)==null||s.call(this,f);return}return this.openInboundSse(!0,e)}if(l.status===405)return;if(!l.ok||!l.body){const f=new De({message:`MCP HTTP Transport Error: GET SSE failed: ${l.status} ${l.statusText}`});(o=this.onerror)==null||o.call(this,f);return}const h=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),d=async()=>{var f,v,y,w;try{for(;;){const{done:g,value:_}=await h.read();if(g)return;const{event:b,data:k,id:S}=_;if(S&&(this.lastInboundEventId=S),b==="message")try{const C=So.parse(JSON.parse(k));(f=this.onmessage)==null||f.call(this,C)}catch(C){const x=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(v=this.onerror)==null||v.call(this,x)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(y=this.onerror)==null||y.call(this,g),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(a=this.onerror)==null||a.call(this,c),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function p7(t){switch(t.type){case"sse":return new u7(t);case"http":return new d7(t);default:throw new De({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function f7(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var h7="1.0.0";async function m7(t){const e=new g7(t);return await e.init(),e}var g7=class{constructor({transport:t,name:e="ai-sdk-mcp-client",version:r=h7,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},f7(t)?this.transport=t:this.transport=p7(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new De({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:e,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:as,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:_E});if(t===void 0)throw new De({message:"Server sent invalid initialize result"});if(!mE.includes(t.protocolVersion))throw new De({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new De({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new De({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new De({message:"Server does not support prompts"});break;default:throw new De({message:`Unsupported method: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new De({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const o=r?.signal;o?.throwIfAborted();const a=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:a},c=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,l=>{if(o?.aborted)return s(new De({message:"Request was aborted",cause:o.reason}));if(l instanceof Error)return s(l);try{const u=e.parse(l.result);n(u)}catch(u){const p=new De({message:"Failed to parse server response",cause:u});s(p)}}),this.transport.send(i).catch(l=>{c(),s(l)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:wE,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:SE,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:t,options:e}={}){try{return this.request({request:{method:"resources/list",params:t},resultSchema:kE,options:e})}catch(r){throw r}}async readResourceInternal({uri:t,options:e}){try{return this.request({request:{method:"resources/read",params:{uri:t}},resultSchema:$E,options:e})}catch(r){throw r}}async listResourceTemplatesInternal({options:t}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:TE,options:t})}catch(e){throw e}}async listPromptsInternal({params:t,options:e}={}){try{return this.request({request:{method:"prompts/list",params:t},resultSchema:IE,options:e})}catch(r){throw r}}async getPromptInternal({name:t,args:e,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:t,arguments:e}},resultSchema:PE,options:r})}catch(n){throw n}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:a}of n.tools){if(t!=="automatic"&&!(s in t))continue;const i=this,c=async(u,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:u,options:p})},l=t==="automatic"?l2({description:o,inputSchema:ho({...a,properties:(e=a.properties)!=null?e:{},additionalProperties:!1}),execute:c}):{description:o,inputSchema:t[s].inputSchema,execute:c};r[s]=l}return r}catch(n){throw n}}listResources({params:t,options:e}={}){return this.listResourcesInternal({params:t,options:e})}readResource({uri:t,options:e}){return this.readResourceInternal({uri:t,options:e})}listResourceTemplates({options:t}={}){return this.listResourceTemplatesInternal({options:t})}listPrompts({params:t,options:e}={}){return this.listPromptsInternal({params:t,options:e})}getPrompt({name:t,arguments:e,options:r}){return this.getPromptInternal({name:t,args:e,options:r})}onElicitationRequest(t,e){if(t!==Ay)throw new De({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=e}async onRequestMessage(t){try{if(t.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Unsupported request method: ${t.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const e=Ay.safeParse({method:t.method,params:t.params});if(!e.success){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32602,message:`Invalid elicitation request: ${e.error.message}`,data:e.error.issues}});return}try{const r=await this.elicitationRequestHandler(e.data),n=AE.parse(r);await this.transport.send({jsonrpc:"2.0",id:t.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new De({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new De({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}},Fy="vercel.ai.error",y7=Symbol.for(Fy),Vy,Hy,Ye=class C_ extends(Hy=Error,Vy=y7,Hy){constructor({name:e,message:r,cause:n}){super(r),this[Vy]=!0,this.name=e,this.cause=n}static isInstance(e){return C_.hasMarker(e,Fy)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}},By="AI_APICallError",Jy=`vercel.ai.error.${By}`,_7=Symbol.for(Jy),Wy,Gy,Ut=class extends(Gy=Ye,Wy=_7,Gy){constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:By,message:t,cause:a}),this[Wy]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=c}static isInstance(t){return Ye.hasMarker(t,Jy)}},Ky="AI_EmptyResponseBodyError",Yy=`vercel.ai.error.${Ky}`,v7=Symbol.for(Yy),Qy,Xy,w7=class extends(Xy=Ye,Qy=v7,Xy){constructor({message:t="Empty response body"}={}){super({name:Ky,message:t}),this[Qy]=!0}static isInstance(t){return Ye.hasMarker(t,Yy)}};function e1(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var t1="AI_InvalidArgumentError",r1=`vercel.ai.error.${t1}`,b7=Symbol.for(r1),n1,s1,o1=class extends(s1=Ye,n1=b7,s1){constructor({message:t,cause:e,argument:r}){super({name:t1,message:t,cause:e}),this[n1]=!0,this.argument=r}static isInstance(t){return Ye.hasMarker(t,r1)}},a1="AI_InvalidPromptError",i1=`vercel.ai.error.${a1}`,k7=Symbol.for(i1),c1,l1,S7=class extends(l1=Ye,c1=k7,l1){constructor({prompt:t,message:e,cause:r}){super({name:a1,message:`Invalid prompt: ${e}`,cause:r}),this[c1]=!0,this.prompt=t}static isInstance(t){return Ye.hasMarker(t,i1)}},u1="AI_InvalidResponseDataError",d1=`vercel.ai.error.${u1}`,C7=Symbol.for(d1),p1,f1,ed=class extends(f1=Ye,p1=C7,f1){constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:u1,message:e}),this[p1]=!0,this.data=t}static isInstance(t){return Ye.hasMarker(t,d1)}},h1="AI_JSONParseError",m1=`vercel.ai.error.${h1}`,T7=Symbol.for(m1),g1,y1,Mi=class extends(y1=Ye,g1=T7,y1){constructor({text:t,cause:e}){super({name:h1,message:`JSON parsing failed: Text: ${t}.
|
|
574
|
+
Error message: ${e1(e)}`,cause:e}),this[g1]=!0,this.text=t}static isInstance(t){return Ye.hasMarker(t,m1)}},_1="AI_LoadAPIKeyError",v1=`vercel.ai.error.${_1}`,$7=Symbol.for(v1),w1,b1,Ni=class extends(b1=Ye,w1=$7,b1){constructor({message:t}){super({name:_1,message:t}),this[w1]=!0}static isInstance(t){return Ye.hasMarker(t,v1)}},k1="AI_TooManyEmbeddingValuesForCallError",S1=`vercel.ai.error.${k1}`,E7=Symbol.for(S1),C1,T1,x7=class extends(T1=Ye,C1=E7,T1){constructor(t){super({name:k1,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[C1]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Ye.hasMarker(t,S1)}},$1="AI_TypeValidationError",E1=`vercel.ai.error.${$1}`,I7=Symbol.for(E1),x1,I1,To=class wd extends(I1=Ye,x1=I7,I1){constructor({value:e,cause:r}){super({name:$1,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
575
|
+
Error message: ${e1(r)}`,cause:r}),this[x1]=!0,this.value=e}static isInstance(e){return Ye.hasMarker(e,E1)}static wrap({value:e,cause:r}){return wd.isInstance(r)&&r.value===e?r:new wd({value:e,cause:r})}},R1="AI_UnsupportedFunctionalityError",P1=`vercel.ai.error.${R1}`,R7=Symbol.for(P1),O1,A1,Rr=class extends(A1=Ye,O1=R7,A1){constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:R1,message:e}),this[O1]=!0,this.functionality=t}static isInstance(t){return Ye.hasMarker(t,P1)}};function mr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function $o(t){return Object.fromEntries([...t.headers])}var P7=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new o1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},nr=P7();function td(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var O7=["fetch failed","failed to fetch"];function A7({error:t,url:e,requestBodyValues:r}){if(td(t))return t;if(t instanceof TypeError&&O7.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ut({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function M7(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function N7(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function M1(t,...e){const r=new Headers(N7(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var L7="3.0.20";function j7({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Ni({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Ni({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Ni({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Ni({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function q7({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function z7(t){var e;const[r,n=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?e:n}var D7=/"__proto__"\s*:/,U7=/"constructor"\s*:/;function N1(t){const e=JSON.parse(t);return e===null||typeof e!="object"||D7.test(t)===!1&&U7.test(t)===!1?e:Z7(e)}function Z7(t){let e=[t];for(;e.length;){const r=e;e=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function rd(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return N1(t)}try{return N1(t)}finally{Error.stackTraceLimit=e}}var Li=Symbol.for("vercel.ai.validator");function F7(t){return{[Li]:!0,validate:t}}function V7(t){return typeof t=="object"&&t!==null&&Li in t&&t[Li]===!0&&"validate"in t}function _t(t){let e;return()=>(e==null&&(e=t()),e)}function H7(t){return V7(t)?t:typeof t=="function"?t():B7(t)}function B7(t){return F7(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new To({value:e,cause:r.issues})}})}async function Qr({value:t,schema:e}){const r=await nd({value:t,schema:e});if(!r.success)throw To.wrap({value:t,cause:r.error});return r.value}async function nd({value:t,schema:e}){const r=H7(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:To.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:To.wrap({value:t,cause:n}),rawValue:t}}}async function J7({text:t,schema:e}){try{const r=rd(t);return e==null?r:Qr({value:r,schema:e})}catch(r){throw Mi.isInstance(r)||To.isInstance(r)?r:new Mi({text:t,cause:r})}}async function L1({text:t,schema:e}){try{const r=rd(t);return e==null?{success:!0,value:r,rawValue:r}:await nd({value:r,schema:e})}catch(r){return{success:!1,error:Mi.isInstance(r)?r:new Mi({text:t,cause:r}),rawValue:void 0}}}function j1(t){try{return rd(t),!0}catch{return!1}}function W7({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await L1({text:r,schema:e}))}}))}async function Xr({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await nd({value:e[t],schema:r});if(!n.success)throw new o1({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var G7=()=>globalThis.fetch,Pr=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>q1({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),K7=async({url:t,headers:e,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>q1({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),q1=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=G7()})=>{try{const i=await a(t,{method:"POST",headers:M1(e,`ai-sdk/provider-utils/${L7}`,M7()),body:r.content,signal:o}),c=$o(i);if(!i.ok){let l;try{l=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw td(u)||Ut.isInstance(u)?u:new Ut({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}throw l.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(l){throw l instanceof Error&&(td(l)||Ut.isInstance(l))?l:new Ut({message:"Failed to process successful response",cause:l,statusCode:i.status,url:t,responseHeaders:c,requestBodyValues:r.values})}}catch(i){throw A7({error:i,url:t,requestBodyValues:r.values})}};function DR(t){return t}function cs({id:t,name:e,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c,...l})=>({type:"provider-defined",id:t,name:e,args:l,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:c})}var Y7=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=$o(n);if(a.trim()==="")return{responseHeaders:i,value:new Ut({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const c=await J7({text:a,schema:t});return{responseHeaders:i,value:new Ut({message:e(c),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:c,isRetryable:r?.(n,c)})}}catch{return{responseHeaders:i,value:new Ut({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},sd=t=>async({response:e})=>{const r=$o(e);if(e.body==null)throw new w7({});return{responseHeaders:r,value:W7({stream:e.body,schema:t})}},ls=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await L1({text:s,schema:t}),a=$o(e);if(!o.success)throw new Ut({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},Q7=()=>async({response:t,url:e,requestBodyValues:r})=>{const n=$o(t);if(!t.body)throw new Ut({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0});try{const s=await t.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new Ut({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0,cause:s})}};function ji(t){if(t.type==="object"){t.additionalProperties=!1;const e=t.properties;if(e!=null)for(const r in e)e[r]=ji(e[r])}return t.type==="array"&&t.items!=null&&(Array.isArray(t.items)?t.items=t.items.map(e=>ji(e)):t.items=ji(t.items)),t}var X7=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},ex=Symbol("Let zodToJsonSchema decide on which parser to use"),z1={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"},tx=t=>typeof t=="string"?{...z1,name:t}:{...z1,...t};function Nt(){return{}}function rx(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=Ue(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function nx(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function sx(){return{type:"boolean"}}function D1(t,e){return Ue(t.type._def,e)}var ox=(t,e)=>Ue(t.innerType._def,e);function U1(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>U1(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ax(t)}}var ax=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function ix(t,e){return{...Ue(t.innerType._def,e),default:t.defaultValue()}}function cx(t,e){return e.effectStrategy==="input"?Ue(t.schema._def,e):Nt()}function lx(t){return{type:"string",enum:Array.from(t.values)}}var ux=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function dx(t,e){const r=[Ue(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ue(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(ux(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function px(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var od=void 0,sr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(od===void 0&&(od=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),od),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 Z1(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(e.emailStrategy){case"format:email":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":vt(r,sr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":vt(r,n.regex,n.message,e);break;case"cuid":vt(r,sr.cuid,n.message,e);break;case"cuid2":vt(r,sr.cuid2,n.message,e);break;case"startsWith":vt(r,RegExp(`^${ad(n.value,e)}`),n.message,e);break;case"endsWith":vt(r,RegExp(`${ad(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{vt(r,RegExp(ad(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":vt(r,sr.base64url,n.message,e);break;case"jwt":vt(r,sr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&vt(r,sr.ipv4Cidr,n.message,e),n.version!=="v4"&&vt(r,sr.ipv6Cidr,n.message,e);break}case"emoji":vt(r,sr.emoji(),n.message,e);break;case"ulid":{vt(r,sr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{vt(r,sr.base64,n.message,e);break}}break}case"nanoid":vt(r,sr.nanoid,n.message,e)}return r}function ad(t,e){return e.patternStrategy==="escape"?hx(t):t}var fx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hx(t){let e="";for(let r=0;r<t.length;r++)fx.has(t[r])||(e+="\\"),e+=t[r];return e}function or(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function vt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:F1(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=F1(e,n)}function F1(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,c=!1;for(let l=0;l<s.length;l++){if(a){o+=s[l],a=!1;continue}if(n.i){if(i){if(s[l].match(/[a-z]/)){c?(o+=s[l],o+=`${s[l-2]}-${s[l]}`.toUpperCase(),c=!1):s[l+1]==="-"&&((r=s[l+2])!=null&&r.match(/[a-z]/))?(o+=s[l],c=!0):o+=`${s[l]}${s[l].toUpperCase()}`;continue}}else if(s[l].match(/[a-z]/)){o+=`[${s[l]}${s[l].toUpperCase()}]`;continue}}if(n.m){if(s[l]==="^"){o+=`(^|(?<=[\r
|
|
576
576
|
]))`;continue}else if(s[l]==="$"){o+=`($|(?=[\r
|
|
577
577
|
]))`;continue}}if(n.s&&s[l]==="."){o+=i?`${s[l]}\r
|
|
578
578
|
`:`[${s[l]}\r
|
|
579
|
-
]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function j1(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=Fe(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===U.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=L1(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===U.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=M1(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function mO(t,e){if(e.mapStrategy==="record")return j1(t,e);const r=Fe(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||zt(),n=Fe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||zt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function gO(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function _O(){return{not:zt()}}function vO(){return{type:"null"}}var pp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yO(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in pp&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=pp[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return wO(t,e)}var wO=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Fe(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function bO(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[pp[t.innerType._def.typeName],"null"]};const r=Fe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function SO(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function kO(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=TO(i),l=Fe(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=CO(t,e);return o!==void 0&&(r.additionalProperties=o),r}function CO(t,e){if(t.catchall._def.typeName!=="ZodNever")return Fe(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function TO(t){try{return t.isOptional()}catch{return!0}}var $O=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Fe(t.innerType._def,e);const n=Fe(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:zt()},n]}:zt()},EO=(t,e)=>{if(e.pipeStrategy==="input")return Fe(t.in._def,e);if(e.pipeStrategy==="output")return Fe(t.out._def,e);const r=Fe(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Fe(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function xO(t,e){return Fe(t.type._def,e)}function IO(t,e){const n={type:"array",uniqueItems:!0,items:Fe(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function RO(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Fe(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Fe(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Fe(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function PO(){return{not:zt()}}function OO(){return zt()}var AO=(t,e)=>Fe(t.innerType._def,e),MO=(t,e,r)=>{switch(e){case U.ZodString:return L1(t,r);case U.ZodNumber:return SO(t);case U.ZodObject:return kO(t,r);case U.ZodBigInt:return nO(t);case U.ZodBoolean:return sO();case U.ZodDate:return N1(t,r);case U.ZodUndefined:return PO();case U.ZodNull:return vO();case U.ZodArray:return rO(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return yO(t,r);case U.ZodIntersection:return dO(t,r);case U.ZodTuple:return RO(t,r);case U.ZodRecord:return j1(t,r);case U.ZodLiteral:return pO(t);case U.ZodEnum:return lO(t);case U.ZodNativeEnum:return gO(t);case U.ZodNullable:return bO(t,r);case U.ZodOptional:return $O(t,r);case U.ZodMap:return mO(t,r);case U.ZodSet:return IO(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return xO(t,r);case U.ZodNaN:case U.ZodNever:return _O();case U.ZodEffects:return cO(t,r);case U.ZodAny:return zt();case U.ZodUnknown:return OO();case U.ZodDefault:return iO(t,r);case U.ZodBranded:return M1(t,r);case U.ZodReadonly:return AO(t,r);case U.ZodCatch:return oO(t,r);case U.ZodPipeline:return EO(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})()}};function Fe(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==eO)return c}if(s&&!r){const c=NO(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=MO(t,t.typeName,e),i=typeof a=="function"?Fe(a(),e):a;if(i&&LO(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var NO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:XP(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),zt()):e.$refStrategy==="seen"?zt():void 0}},LO=(t,e,r)=>(t.description&&(r.description=t.description),r),qO=t=>{const e=tO(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},jO=(t,e)=>{var r;const n=qO(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,h])=>{var f;return{...l,[u]:(f=Fe(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?f:zt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Fe(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:zt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},UO=jO;function zO(t,e){var r;const n=(r=void 0)!=null?r:!1;return U1(()=>UO(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function DO(t,e){var r;const n=(r=void 0)!=null?r:!1;return U1(()=>fc(Wc(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async s=>{const o=await Gc(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function ZO(t){return"_zod"in t}function Ue(t,e){return ZO(t)?DO(t):zO(t)}var VO=Symbol.for("vercel.ai.schema");function gt(t){let e;return()=>(e==null&&(e=t()),e)}function U1(t,{validate:e}={}){return{[VO]:!0,_type:void 0,[hc]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}var{btoa:FO,atob:HO}=globalThis;function BO(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=HO(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function JO(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return FO(e)}function Ss(t){return t instanceof Uint8Array?JO(t):t}function WO(t){return t?.replace(/\/$/,"")}var hp=C({error:C({message:d(),type:d().nullish(),param:mt().nullish(),code:ee([d(),M()]).nullish()})}),Tr=YP({errorSchema:hp,errorToMessage:t=>t.error.message});function z1(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),n=!(t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("chatgpt-4o")||t.startsWith("gpt-5-chat")),s=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:e,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:s}}function GO({prompt:t,systemMessageMode:e="system"}){const r=[],n=[];for(const{role:s,content:o}of t)switch(s){case"system":{switch(e){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=e;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((a,i)=>{var c,l,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const h=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${h};base64,${Ss(a.data)}`,detail:(l=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:l.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new jr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Ss(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Ss(a.data),format:"mp3"}};default:throw new jr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new jr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${Ss(a.data)}`}}}else throw new jr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const c of o)switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of o){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function fp({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r?new Date(r*1e3):void 0}}function D1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var KO=St(()=>Ue(C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({message:C({role:O("assistant").nullish(),content:d().nullish(),tool_calls:I(C({id:d().nullish(),type:O("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:I(C({type:O("url_citation"),url_citation:C({start_index:M(),end_index:M(),url:d(),title:d()})})).nullish()}),index:M(),logprobs:C({content:I(C({token:d(),logprob:M(),top_logprobs:I(C({token:d(),logprob:M()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:M().nullish(),completion_tokens:M().nullish(),total_tokens:M().nullish(),prompt_tokens_details:C({cached_tokens:M().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:M().nullish(),accepted_prediction_tokens:M().nullish(),rejected_prediction_tokens:M().nullish()}).nullish()}).nullish()}))),YO=St(()=>Ue(ee([C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({delta:C({role:we(["assistant"]).nullish(),content:d().nullish(),tool_calls:I(C({index:M(),id:d().nullish(),type:O("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:I(C({type:O("url_citation"),url_citation:C({start_index:M(),end_index:M(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:I(C({token:d(),logprob:M(),top_logprobs:I(C({token:d(),logprob:M()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:M()})),usage:C({prompt_tokens:M().nullish(),completion_tokens:M().nullish(),total_tokens:M().nullish(),prompt_tokens_details:C({cached_tokens:M().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:M().nullish(),accepted_prediction_tokens:M().nullish(),rejected_prediction_tokens:M().nullish()}).nullish()}).nullish()}),hp]))),QO=St(()=>Ue(C({logitBias:ie(dm(),M()).optional(),logprobs:ee([ne(),M()]).optional(),parallelToolCalls:ne().optional(),user:d().optional(),reasoningEffort:we(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:M().optional(),store:ne().optional(),metadata:ie(d().max(64),d().max(512)).optional(),prediction:ie(d(),mt()).optional(),structuredOutputs:ne().optional(),serviceTier:we(["auto","flex","priority","default"]).optional(),strictJsonSchema:ne().optional(),textVerbosity:we(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:we(["in_memory","24h"]).optional(),safetyIdentifier:d().optional()})));function XO({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:n}){t=t?.length?t:void 0;const s=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const o=[];for(const i of t)switch(i.type){case"function":o.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:s.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:s};const a=e.type;switch(a){case"auto":case"none":case"required":return{tools:o,toolChoice:a,toolWarnings:s};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:s};default:{const i=a;throw new jr({functionality:`tool choice type: ${i}`})}}}var eA=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,seed:l,tools:u,toolChoice:h,providerOptions:f}){var p,m,v,_;const w=[],g=(p=await ln({provider:"openai",providerOptions:f,schema:QO}))!=null?p:{},y=(m=g.structuredOutputs)!=null?m:!0,b=z1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!y&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:S,warnings:k}=GO({prompt:t,systemMessageMode:b.systemMessageMode});w.push(...k);const T=(v=g.strictJsonSchema)!=null?v:!1,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:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:c?.type==="json"?y&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:T,name:(_=c.name)!=null?_:"response",description:c.description}}:{type:"json_object"}:void 0,stop:i,seed:l,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:S};b.isReasoningModel?((g.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,w.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,w.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,w.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!b.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),g.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:P,toolChoice:q,toolWarnings:N}=XO({tools:u,toolChoice:h,structuredOutputs:y,strictJsonSchema:T});return{args:{...x,tools:P,tool_choice:q},warnings:[...w,...N]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,h,f,p,m;const{args:v,warnings:_}=await this.getArgs(t),{responseHeaders:w,value:g,rawValue:y}=await Ur({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:v,failedResponseHandler:Tr,successfulResponseHandler:bs(KO),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=g.choices[0],S=[],k=b.message.content;k!=null&&k.length>0&&S.push({type:"text",text:k});for(const q of(e=b.message.tool_calls)!=null?e:[])S.push({type:"tool-call",toolCallId:(r=q.id)!=null?r:ur(),toolName:q.function.name,input:q.function.arguments});for(const q of(n=b.message.annotations)!=null?n:[])S.push({type:"source",sourceType:"url",id:ur(),url:q.url_citation.url,title:q.url_citation.title});const T=(s=g.usage)==null?void 0:s.completion_tokens_details,x=(o=g.usage)==null?void 0:o.prompt_tokens_details,P={openai:{}};return T?.accepted_prediction_tokens!=null&&(P.openai.acceptedPredictionTokens=T?.accepted_prediction_tokens),T?.rejected_prediction_tokens!=null&&(P.openai.rejectedPredictionTokens=T?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(P.openai.logprobs=b.logprobs.content),{content:S,finishReason:D1(b.finish_reason),usage:{inputTokens:(c=(i=g.usage)==null?void 0:i.prompt_tokens)!=null?c:void 0,outputTokens:(u=(l=g.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(f=(h=g.usage)==null?void 0:h.total_tokens)!=null?f:void 0,reasoningTokens:(p=T?.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(m=x?.cached_tokens)!=null?m:void 0},request:{body:v},response:{...fp(g),headers:w,body:y},warnings:_,providerMetadata:P}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Ur({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:n,failedResponseHandler:Tr,successfulResponseHandler:lp(YO),abortSignal:t.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!1,u=!1;const h={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,p){var m,v,_,w,g,y,b,S,k,T,x,P,q,N,z,D,F,oe,fe,de,se,_e,H,A;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){i="error",p.enqueue({type:"error",error:f.error});return}const V=f.value;if("error"in V){i="error",p.enqueue({type:"error",error:V.error});return}if(!l){const R=fp(V);Object.values(R).some(Boolean)&&(l=!0,p.enqueue({type:"response-metadata",...fp(V)}))}V.usage!=null&&(c.inputTokens=(m=V.usage.prompt_tokens)!=null?m:void 0,c.outputTokens=(v=V.usage.completion_tokens)!=null?v:void 0,c.totalTokens=(_=V.usage.total_tokens)!=null?_:void 0,c.reasoningTokens=(g=(w=V.usage.completion_tokens_details)==null?void 0:w.reasoning_tokens)!=null?g:void 0,c.cachedInputTokens=(b=(y=V.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?b:void 0,((S=V.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(k=V.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens),((T=V.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(x=V.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens));const j=V.choices[0];if(j?.finish_reason!=null&&(i=D1(j.finish_reason)),((P=j?.logprobs)==null?void 0:P.content)!=null&&(h.openai.logprobs=j.logprobs.content),j?.delta==null)return;const E=j.delta;if(E.content!=null&&(u||(p.enqueue({type:"text-start",id:"0"}),u=!0),p.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const R of E.tool_calls){const $=R.index;if(a[$]==null){if(R.type!=="function")throw new op({data:R,message:"Expected 'function' type."});if(R.id==null)throw new op({data:R,message:"Expected 'id' to be a string."});if(((q=R.function)==null?void 0:q.name)==null)throw new op({data:R,message:"Expected 'function.name' to be a string."});p.enqueue({type:"tool-input-start",id:R.id,toolName:R.function.name}),a[$]={id:R.id,type:"function",function:{name:R.function.name,arguments:(N=R.function.arguments)!=null?N:""},hasFinished:!1};const G=a[$];((z=G.function)==null?void 0:z.name)!=null&&((D=G.function)==null?void 0:D.arguments)!=null&&(G.function.arguments.length>0&&p.enqueue({type:"tool-input-delta",id:G.id,delta:G.function.arguments}),P1(G.function.arguments)&&(p.enqueue({type:"tool-input-end",id:G.id}),p.enqueue({type:"tool-call",toolCallId:(F=G.id)!=null?F:ur(),toolName:G.function.name,input:G.function.arguments}),G.hasFinished=!0));continue}const B=a[$];B.hasFinished||(((oe=R.function)==null?void 0:oe.arguments)!=null&&(B.function.arguments+=(de=(fe=R.function)==null?void 0:fe.arguments)!=null?de:""),p.enqueue({type:"tool-input-delta",id:B.id,delta:(se=R.function.arguments)!=null?se:""}),((_e=B.function)==null?void 0:_e.name)!=null&&((H=B.function)==null?void 0:H.arguments)!=null&&P1(B.function.arguments)&&(p.enqueue({type:"tool-input-end",id:B.id}),p.enqueue({type:"tool-call",toolCallId:(A=B.id)!=null?A:ur(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(E.annotations!=null)for(const R of E.annotations)p.enqueue({type:"source",sourceType:"url",id:ur(),url:R.url_citation.url,title:R.url_citation.title})},flush(f){u&&f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:i,usage:c,...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:s}}}};function tA({prompt:t,user:e="user",assistant:r="assistant"}){let n="";t[0].role==="system"&&(n+=`${t[0].content}
|
|
579
|
+
]`;continue}o+=s[l],s[l]==="\\"?a=!0:i&&s[l]==="]"?i=!1:!i&&s[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function V1(t,e){var r,n,s,o,a,i;const c={type:"object",additionalProperties:(r=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...u}=Z1(t.keyType._def,e);return{...c,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...c,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:l,...u}=D1(t.keyType._def,e);return{...c,propertyNames:u}}}return c}function mx(t,e){if(e.mapStrategy==="record")return V1(t,e);const r=Ue(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Nt(),n=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Nt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function gx(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function yx(){return{not:Nt()}}function _x(){return{type:"null"}}var id={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vx(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in id&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=id[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return wx(t,e)}var wx=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ue(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function bx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[id[t.innerType._def.typeName],"null"]};const r=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kx(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Sx(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const c=Tx(i),l=Ue(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,c||n.push(a))}n.length&&(r.required=n);const o=Cx(t,e);return o!==void 0&&(r.additionalProperties=o),r}function Cx(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ue(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Tx(t){try{return t.isOptional()}catch{return!0}}var $x=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ue(t.innerType._def,e);const n=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Nt()},n]}:Nt()},Ex=(t,e)=>{if(e.pipeStrategy==="input")return Ue(t.in._def,e);if(e.pipeStrategy==="output")return Ue(t.out._def,e);const r=Ue(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ue(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function xx(t,e){return Ue(t.type._def,e)}function Ix(t,e){const n={type:"array",uniqueItems:!0,items:Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function Rx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ue(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Px(){return{not:Nt()}}function Ox(){return Nt()}var Ax=(t,e)=>Ue(t.innerType._def,e),Mx=(t,e,r)=>{switch(e){case z.ZodString:return Z1(t,r);case z.ZodNumber:return kx(t);case z.ZodObject:return Sx(t,r);case z.ZodBigInt:return nx(t);case z.ZodBoolean:return sx();case z.ZodDate:return U1(t,r);case z.ZodUndefined:return Px();case z.ZodNull:return _x();case z.ZodArray:return rx(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return vx(t,r);case z.ZodIntersection:return dx(t,r);case z.ZodTuple:return Rx(t,r);case z.ZodRecord:return V1(t,r);case z.ZodLiteral:return px(t);case z.ZodEnum:return lx(t);case z.ZodNativeEnum:return gx(t);case z.ZodNullable:return bx(t,r);case z.ZodOptional:return $x(t,r);case z.ZodMap:return mx(t,r);case z.ZodSet:return Ix(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return xx(t,r);case z.ZodNaN:case z.ZodNever:return yx();case z.ZodEffects:return cx(t,r);case z.ZodAny:return Nt();case z.ZodUnknown:return Ox();case z.ZodDefault:return ix(t,r);case z.ZodBranded:return D1(t,r);case z.ZodReadonly:return Ax(t,r);case z.ZodCatch:return ox(t,r);case z.ZodPipeline:return Ex(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ue(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const c=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(c!==ex)return c}if(s&&!r){const c=Nx(s,e);if(c!==void 0)return c}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=Mx(t,t.typeName,e),i=typeof a=="function"?Ue(a(),e):a;if(i&&Lx(t,e,i),e.postProcess){const c=e.postProcess(i,t,e);return o.jsonSchema=i,c}return o.jsonSchema=i,i}var Nx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:X7(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Nt()):e.$refStrategy==="seen"?Nt():void 0}},Lx=(t,e,r)=>(t.description&&(r.description=t.description),r),jx=t=>{const e=tx(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},qx=(t,e)=>{var r;const n=jx(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>{var h;return{...l,[u]:(h=Ue(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Nt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Ue(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Nt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const c=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return c.$schema="http://json-schema.org/draft-07/schema#",c},zx=qx;function Dx(t,e){var r;const n=(r=void 0)!=null?r:!1;return H1(()=>zx(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Ux(t,e){var r;const n=(r=void 0)!=null?r:!1;return H1(()=>ji(yc(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async s=>{const o=await _c(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Zx(t){return"_zod"in t}function Le(t,e){return Zx(t)?Ux(t):Dx(t)}var Fx=Symbol.for("vercel.ai.schema");function dt(t){let e;return()=>(e==null&&(e=t()),e)}function H1(t,{validate:e}={}){return{[Fx]:!0,_type:void 0,[Li]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}var{btoa:Vx,atob:Hx}=globalThis;function Bx(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Hx(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Jx(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Vx(e)}function us(t){return t instanceof Uint8Array?Jx(t):t}function Wx(t){return t?.replace(/\/$/,"")}var cd=T({error:T({message:m(),type:m().nullish(),param:ht().nullish(),code:ie([m(),N()]).nullish()})}),gr=Y7({errorSchema:cd,errorToMessage:t=>t.error.message});function B1(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),n=!(t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("chatgpt-4o")||t.startsWith("gpt-5-chat")),s=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:e,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:s}}function Gx({prompt:t,systemMessageMode:e="system"}){const r=[],n=[];for(const{role:s,content:o}of t)switch(s){case"system":{switch(e){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=e;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((a,i)=>{var c,l,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const p=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${p};base64,${us(a.data)}`,detail:(l=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:l.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Rr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:us(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:us(a.data),format:"mp3"}};default:throw new Rr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Rr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${us(a.data)}`}}}else throw new Rr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const c of o)switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of o){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function ld({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r?new Date(r*1e3):void 0}}function J1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Kx=_t(()=>Le(T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({message:T({role:L("assistant").nullish(),content:m().nullish(),tool_calls:M(T({id:m().nullish(),type:L("function"),function:T({name:m(),arguments:m()})})).nullish(),annotations:M(T({type:L("url_citation"),url_citation:T({start_index:N(),end_index:N(),url:m(),title:m()})})).nullish()}),index:N(),logprobs:T({content:M(T({token:m(),logprob:N(),top_logprobs:M(T({token:m(),logprob:N()}))})).nullish()}).nullish(),finish_reason:m().nullish()})),usage:T({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:T({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}))),Yx=_t(()=>Le(ie([T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({delta:T({role:xe(["assistant"]).nullish(),content:m().nullish(),tool_calls:M(T({index:N(),id:m().nullish(),type:L("function").nullish(),function:T({name:m().nullish(),arguments:m().nullish()})})).nullish(),annotations:M(T({type:L("url_citation"),url_citation:T({start_index:N(),end_index:N(),url:m(),title:m()})})).nullish()}).nullish(),logprobs:T({content:M(T({token:m(),logprob:N(),top_logprobs:M(T({token:m(),logprob:N()}))})).nullish()}).nullish(),finish_reason:m().nullish(),index:N()})),usage:T({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:T({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}),cd]))),Qx=_t(()=>Le(T({logitBias:be(ch(),N()).optional(),logprobs:ie([me(),N()]).optional(),parallelToolCalls:me().optional(),user:m().optional(),reasoningEffort:xe(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:N().optional(),store:me().optional(),metadata:be(m().max(64),m().max(512)).optional(),prediction:be(m(),ht()).optional(),structuredOutputs:me().optional(),serviceTier:xe(["auto","flex","priority","default"]).optional(),strictJsonSchema:me().optional(),textVerbosity:xe(["low","medium","high"]).optional(),promptCacheKey:m().optional(),promptCacheRetention:xe(["in_memory","24h"]).optional(),safetyIdentifier:m().optional()})));function Xx({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:n}){t=t?.length?t:void 0;const s=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const o=[];for(const i of t)switch(i.type){case"function":o.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:s.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:s};const a=e.type;switch(a){case"auto":case"none":case"required":return{tools:o,toolChoice:a,toolWarnings:s};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:s};default:{const i=a;throw new Rr({functionality:`tool choice type: ${i}`})}}}var eI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,seed:l,tools:u,toolChoice:p,providerOptions:h}){var d,f,v,y;const w=[],g=(d=await Xr({provider:"openai",providerOptions:h,schema:Qx}))!=null?d:{},_=(f=g.structuredOutputs)!=null?f:!0,b=B1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!_&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=Gx({prompt:t,systemMessageMode:b.systemMessageMode});w.push(...S);const C=(v=g.strictJsonSchema)!=null?v:!1,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:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:c?.type==="json"?_&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:C,name:(y=c.name)!=null?y:"response",description:c.description}}:{type:"json_object"}:void 0,stop:i,seed:l,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.isReasoningModel?((g.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,w.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,w.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,w.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!b.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),g.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:R,toolChoice:j,toolWarnings:O}=Xx({tools:u,toolChoice:p,structuredOutputs:_,strictJsonSchema:C});return{args:{...x,tools:R,tool_choice:j},warnings:[...w,...O]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f;const{args:v,warnings:y}=await this.getArgs(t),{responseHeaders:w,value:g,rawValue:_}=await Pr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:v,failedResponseHandler:gr,successfulResponseHandler:ls(Kx),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=g.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const j of(e=b.message.tool_calls)!=null?e:[])k.push({type:"tool-call",toolCallId:(r=j.id)!=null?r:nr(),toolName:j.function.name,input:j.function.arguments});for(const j of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:nr(),url:j.url_citation.url,title:j.url_citation.title});const C=(s=g.usage)==null?void 0:s.completion_tokens_details,x=(o=g.usage)==null?void 0:o.prompt_tokens_details,R={openai:{}};return C?.accepted_prediction_tokens!=null&&(R.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(R.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(R.openai.logprobs=b.logprobs.content),{content:k,finishReason:J1(b.finish_reason),usage:{inputTokens:(c=(i=g.usage)==null?void 0:i.prompt_tokens)!=null?c:void 0,outputTokens:(u=(l=g.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(h=(p=g.usage)==null?void 0:p.total_tokens)!=null?h:void 0,reasoningTokens:(d=C?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=x?.cached_tokens)!=null?f:void 0},request:{body:v},response:{...ld(g),headers:w,body:_},warnings:y,providerMetadata:R}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Pr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:sd(Yx),abortSignal:t.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!1,u=!1;const p={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var f,v,y,w,g,_,b,k,S,C,x,R,j,O,D,U,V,ne,fe,de,te,ye,H,P;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const F=h.value;if("error"in F){i="error",d.enqueue({type:"error",error:F.error});return}if(!l){const I=ld(F);Object.values(I).some(Boolean)&&(l=!0,d.enqueue({type:"response-metadata",...ld(F)}))}F.usage!=null&&(c.inputTokens=(f=F.usage.prompt_tokens)!=null?f:void 0,c.outputTokens=(v=F.usage.completion_tokens)!=null?v:void 0,c.totalTokens=(y=F.usage.total_tokens)!=null?y:void 0,c.reasoningTokens=(g=(w=F.usage.completion_tokens_details)==null?void 0:w.reasoning_tokens)!=null?g:void 0,c.cachedInputTokens=(b=(_=F.usage.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?b:void 0,((k=F.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(p.openai.acceptedPredictionTokens=(S=F.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((C=F.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens)!=null&&(p.openai.rejectedPredictionTokens=(x=F.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens));const q=F.choices[0];if(q?.finish_reason!=null&&(i=J1(q.finish_reason)),((R=q?.logprobs)==null?void 0:R.content)!=null&&(p.openai.logprobs=q.logprobs.content),q?.delta==null)return;const E=q.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const I of E.tool_calls){const $=I.index;if(a[$]==null){if(I.type!=="function")throw new ed({data:I,message:"Expected 'function' type."});if(I.id==null)throw new ed({data:I,message:"Expected 'id' to be a string."});if(((j=I.function)==null?void 0:j.name)==null)throw new ed({data:I,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),a[$]={id:I.id,type:"function",function:{name:I.function.name,arguments:(O=I.function.arguments)!=null?O:""},hasFinished:!1};const G=a[$];((D=G.function)==null?void 0:D.name)!=null&&((U=G.function)==null?void 0:U.arguments)!=null&&(G.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:G.id,delta:G.function.arguments}),j1(G.function.arguments)&&(d.enqueue({type:"tool-input-end",id:G.id}),d.enqueue({type:"tool-call",toolCallId:(V=G.id)!=null?V:nr(),toolName:G.function.name,input:G.function.arguments}),G.hasFinished=!0));continue}const B=a[$];B.hasFinished||(((ne=I.function)==null?void 0:ne.arguments)!=null&&(B.function.arguments+=(de=(fe=I.function)==null?void 0:fe.arguments)!=null?de:""),d.enqueue({type:"tool-input-delta",id:B.id,delta:(te=I.function.arguments)!=null?te:""}),((ye=B.function)==null?void 0:ye.name)!=null&&((H=B.function)==null?void 0:H.arguments)!=null&&j1(B.function.arguments)&&(d.enqueue({type:"tool-input-end",id:B.id}),d.enqueue({type:"tool-call",toolCallId:(P=B.id)!=null?P:nr(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(E.annotations!=null)for(const I of E.annotations)d.enqueue({type:"source",sourceType:"url",id:nr(),url:I.url_citation.url,title:I.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:c,...p!=null?{providerMetadata:p}:{}})}})),request:{body:n},response:{headers:s}}}};function tI({prompt:t,user:e="user",assistant:r="assistant"}){let n="";t[0].role==="system"&&(n+=`${t[0].content}
|
|
580
580
|
|
|
581
|
-
`,t=t.slice(1));for(const{role:s,content:o}of t)switch(s){case"system":throw new
|
|
581
|
+
`,t=t.slice(1));for(const{role:s,content:o}of t)switch(s){case"system":throw new S7({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const a=o.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${e}:
|
|
582
582
|
${a}
|
|
583
583
|
|
|
584
|
-
`;break}case"assistant":{const a=o.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new
|
|
584
|
+
`;break}case"assistant":{const a=o.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Rr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
|
|
585
585
|
${a}
|
|
586
586
|
|
|
587
|
-
`;break}case"tool":throw new
|
|
587
|
+
`;break}case"tool":throw new Rr({functionality:"tool messages"});default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
|
|
588
588
|
`,{prompt:n,stopSequences:[`
|
|
589
|
-
${e}:`]}}function Z1({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function V1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var rA=St(()=>Ue(C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({text:d(),finish_reason:d(),logprobs:C({tokens:I(d()),token_logprobs:I(M()),top_logprobs:I(ie(d(),M())).nullish()}).nullish()})),usage:C({prompt_tokens:M(),completion_tokens:M(),total_tokens:M()}).nullish()}))),nA=St(()=>Ue(ee([C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({text:d(),finish_reason:d().nullish(),index:M(),logprobs:C({tokens:I(d()),token_logprobs:I(M()),top_logprobs:I(ie(d(),M())).nullish()}).nullish()})),usage:C({prompt_tokens:M(),completion_tokens:M(),total_tokens:M()}).nullish()}),hp]))),F1=St(()=>Ue(C({echo:ne().optional(),logitBias:ie(d(),M()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ee([ne(),M()]).optional()}))),sA=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,tools:l,toolChoice:u,seed:h,providerOptions:f}){const p=[],m={...await ln({provider:"openai",providerOptions:f,schema:F1}),...await ln({provider:this.providerOptionsName,providerOptions:f,schema:F1})};s!=null&&p.push({type:"unsupported-setting",setting:"topK"}),l?.length&&p.push({type:"unsupported-setting",setting:"tools"}),u!=null&&p.push({type:"unsupported-setting",setting:"toolChoice"}),c!=null&&c.type!=="text"&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:_}=tA({prompt:t}),w=[..._??[],...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:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,seed:h,prompt:v,stop:w.length>0?w:void 0},warnings:p}}async doGenerate(t){var e,r,n;const{args:s,warnings:o}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:c}=await Ur({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:s,failedResponseHandler:Tr,successfulResponseHandler:bs(rA),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=i.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:V1(l.finish_reason),request:{body:s},response:{...Z1(i),headers:a,body:c},providerMetadata:u,warnings:o}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Ur({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:n,failedResponseHandler:Tr,successfulResponseHandler:lp(nA),abortSignal:t.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:o.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",h.enqueue({type:"error",error:u.error});return}const f=u.value;if("error"in f){a="error",h.enqueue({type:"error",error:f.error});return}l&&(l=!1,h.enqueue({type:"response-metadata",...Z1(f)}),h.enqueue({type:"text-start",id:"0"})),f.usage!=null&&(c.inputTokens=f.usage.prompt_tokens,c.outputTokens=f.usage.completion_tokens,c.totalTokens=f.usage.total_tokens);const p=f.choices[0];p?.finish_reason!=null&&(a=V1(p.finish_reason)),p?.logprobs!=null&&(i.openai.logprobs=p.logprobs),p?.text!=null&&p.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:p.text})},flush(u){l||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:c})}})),request:{body:n},response:{headers:s}}}},oA=St(()=>Ue(C({dimensions:M().optional(),user:d().optional()}))),aA=St(()=>Ue(C({data:I(C({embedding:I(M())})),usage:C({prompt_tokens:M()}).nullish()}))),iA=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new xP({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await ln({provider:"openai",providerOptions:n,schema:oA}))!=null?s:{},{responseHeaders:a,value:i,rawValue:c}=await Ur({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Cr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:Tr,successfulResponseHandler:bs(aA),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(l=>l.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:c}}}},cA=St(()=>Ue(C({created:M().nullish(),data:I(C({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:C({input_tokens:M().nullish(),output_tokens:M().nullish(),total_tokens:M().nullish(),input_tokens_details:C({image_tokens:M().nullish(),text_tokens:M().nullish()}).nullish()}).nullish()}))),lA={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},uA=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),dA=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=lA[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c,l,u,h;const f=[];n!=null&&f.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&f.push({type:"unsupported-setting",setting:"seed"});const p=(u=(l=(c=this.config._internal)==null?void 0:c.currentDate)==null?void 0:l.call(c))!=null?u:new Date,{value:m,responseHeaders:v}=await Ur({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Cr(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(h=o.openai)!=null?h:{},...uA.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tr,successfulResponseHandler:bs(cA),abortSignal:i,fetch:this.config.fetch});return{images:m.data.map(_=>_.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:m.data.map(_=>({..._.revised_prompt?{revisedPrompt:_.revised_prompt}:{},...m.created!=null?{created:m.created}:{},...m.size!=null?{size:m.size}:{},...m.quality!=null?{quality:m.quality}:{},...m.background!=null?{background:m.background}:{},...m.output_format!=null?{outputFormat:m.output_format}:{}}))}}}}},pA=gt(()=>Ue(C({code:d().nullish(),containerId:d()}))),hA=gt(()=>Ue(C({outputs:I(Xe("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullish()}))),fA=gt(()=>Ue(C({container:ee([d(),C({fileIds:I(d()).optional()})]).optional()}))),mA=ws({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:pA,outputSchema:hA}),gA=(t={})=>mA(t),H1=C({key:d(),type:we(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([d(),M(),ne(),I(d())])}),B1=C({type:we(["and","or"]),filters:I(ee([H1,um(()=>B1)]))}),_A=gt(()=>Ue(C({vectorStoreIds:I(d()),maxNumResults:M().optional(),ranking:C({ranker:d().optional(),scoreThreshold:M().optional()}).optional(),filters:ee([H1,B1]).optional()}))),vA=gt(()=>Ue(C({queries:I(d()),results:I(C({attributes:ie(d(),he()),fileId:d(),filename:d(),score:M(),text:d()})).nullable()}))),yA=ws({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:vA}),wA=gt(()=>Ue(C({background:we(["auto","opaque","transparent"]).optional(),inputFidelity:we(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:we(["auto"]).optional(),outputCompression:M().int().min(0).max(100).optional(),outputFormat:we(["png","jpeg","webp"]).optional(),partialImages:M().int().min(0).max(3).optional(),quality:we(["auto","low","medium","high"]).optional(),size:we(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),bA=gt(()=>Ue(C({}))),SA=gt(()=>Ue(C({result:d()}))),kA=ws({id:"openai.image_generation",name:"image_generation",inputSchema:bA,outputSchema:SA}),CA=(t={})=>kA(t),J1=gt(()=>Ue(C({action:C({type:O("exec"),command:I(d()),timeoutMs:M().optional(),user:d().optional(),workingDirectory:d().optional(),env:ie(d(),d()).optional()})}))),W1=gt(()=>Ue(C({output:d()}))),TA=ws({id:"openai.local_shell",name:"local_shell",inputSchema:J1,outputSchema:W1}),$A=gt(()=>Ue(C({externalWebAccess:ne().optional(),filters:C({allowedDomains:I(d()).optional()}).optional(),searchContextSize:we(["low","medium","high"]).optional(),userLocation:C({type:O("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),EA=gt(()=>Ue(C({}))),xA=gt(()=>Ue(C({action:Xe("type",[C({type:O("search"),query:d().optional()}),C({type:O("openPage"),url:d().nullish()}),C({type:O("findInPage"),url:d().nullish(),pattern:d().nullish()})]),sources:I(Xe("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).optional()}))),IA=ws({id:"openai.web_search",name:"web_search",inputSchema:EA,outputSchema:xA}),RA=(t={})=>IA(t),PA=gt(()=>Ue(C({searchContextSize:we(["low","medium","high"]).optional(),userLocation:C({type:O("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),OA=gt(()=>Ue(C({}))),AA=gt(()=>Ue(C({action:Xe("type",[C({type:O("search"),query:d().optional()}),C({type:O("openPage"),url:d().nullish()}),C({type:O("findInPage"),url:d().nullish(),pattern:d().nullish()})])}))),MA=ws({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:OA,outputSchema:AA}),NA={codeInterpreter:gA,fileSearch:yA,imageGeneration:CA,localShell:TA,webSearchPreview:MA,webSearch:RA};function G1(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function LA({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:s=!1}){var o,a,i,c;const l=[],u=[];for(const{role:h,content:f}of t)switch(h){case"system":{switch(e){case"system":{l.push({role:"system",content:f});break}case"developer":{l.push({role:"developer",content:f});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const p=e;throw new Error(`Unsupported system message mode: ${p}`)}}break}case"user":{l.push({role:"user",content:f.map((p,m)=>{var v,_,w;switch(p.type){case"text":return{type:"input_text",text:p.text};case"file":if(p.mediaType.startsWith("image/")){const g=p.mediaType==="image/*"?"image/jpeg":p.mediaType;return{type:"input_image",...p.data instanceof URL?{image_url:p.data.toString()}:typeof p.data=="string"&&G1(p.data,r)?{file_id:p.data}:{image_url:`data:${g};base64,${Ss(p.data)}`},detail:(_=(v=p.providerOptions)==null?void 0:v.openai)==null?void 0:_.imageDetail}}else{if(p.mediaType==="application/pdf")return p.data instanceof URL?{type:"input_file",file_url:p.data.toString()}:{type:"input_file",...typeof p.data=="string"&&G1(p.data,r)?{file_id:p.data}:{filename:(w=p.filename)!=null?w:`part-${m}.pdf`,file_data:`data:application/pdf;base64,${Ss(p.data)}`}};throw new jr({functionality:`file part media type ${p.mediaType}`})}}})});break}case"assistant":{const p={},m={};for(const v of f)switch(v.type){case"text":{const _=(a=(o=v.providerOptions)==null?void 0:o.openai)==null?void 0:a.itemId;if(n&&_!=null){l.push({type:"item_reference",id:_});break}l.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:_});break}case"tool-call":{if(m[v.toolCallId]=v,v.providerExecuted)break;const _=(c=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:c.itemId;if(n&&_!=null){l.push({type:"item_reference",id:_});break}if(s&&v.toolName==="local_shell"){const w=await cn({value:v.input,schema:J1});l.push({type:"local_shell_call",call_id:v.toolCallId,id:_,action:{type:"exec",command:w.action.command,timeout_ms:w.action.timeoutMs,user:w.action.user,working_directory:w.action.workingDirectory,env:w.action.env}});break}l.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:_});break}case"tool-result":{n?l.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _=await ln({provider:"openai",providerOptions:v.providerOptions,schema:qA}),w=_?.itemId;if(w!=null){const g=p[w];if(n)g===void 0&&(l.push({type:"item_reference",id:w}),p[w]={type:"reasoning",id:w,summary:[]});else{const y=[];v.text.length>0?y.push({type:"summary_text",text:v.text}):g!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),g===void 0?(p[w]={type:"reasoning",id:w,encrypted_content:_?.reasoningEncryptedContent,summary:y},l.push(p[w])):(g.summary.push(...y),_?.reasoningEncryptedContent!=null&&(g.encrypted_content=_.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const p of f){const m=p.output;if(s&&p.toolName==="local_shell"&&m.type==="json"){const _=await cn({value:m.value,schema:W1});l.push({type:"local_shell_call_output",call_id:p.toolCallId,output:_.output});break}let v;switch(m.type){case"text":case"error-text":v=m.value;break;case"json":case"error-json":v=JSON.stringify(m.value);break;case"content":v=m.value.map(_=>{switch(_.type){case"text":return{type:"input_text",text:_.text};case"media":return _.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${_.mediaType};base64,${_.data}`}:{type:"input_file",filename:"data",file_data:`data:${_.mediaType};base64,${_.data}`}}});break}l.push({type:"function_call_output",call_id:p.toolCallId,output:v})}break}default:{const p=h;throw new Error(`Unsupported role: ${p}`)}}return{input:l,warnings:u}}var qA=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function K1({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var jA=St(()=>Ue(ee([C({type:O("response.output_text.delta"),item_id:d(),delta:d(),logprobs:I(C({token:d(),logprob:M(),top_logprobs:I(C({token:d(),logprob:M()}))})).nullish()}),C({type:we(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:M(),input_tokens_details:C({cached_tokens:M().nullish()}).nullish(),output_tokens:M(),output_tokens_details:C({reasoning_tokens:M().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:O("response.created"),response:C({id:d(),created_at:M(),model:d(),service_tier:d().nullish()})}),C({type:O("response.output_item.added"),output_index:M(),item:Xe("type",[C({type:O("message"),id:d()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:O("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:O("web_search_call"),id:d(),status:d()}),C({type:O("computer_call"),id:d(),status:d()}),C({type:O("file_search_call"),id:d()}),C({type:O("image_generation_call"),id:d()}),C({type:O("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:I(Xe("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable(),status:d()})])}),C({type:O("response.output_item.done"),output_index:M(),item:Xe("type",[C({type:O("message"),id:d()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:O("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:O("completed")}),C({type:O("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:I(Xe("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable()}),C({type:O("image_generation_call"),id:d(),result:d()}),C({type:O("web_search_call"),id:d(),status:d(),action:Xe("type",[C({type:O("search"),query:d().nullish(),sources:I(Xe("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).nullish()}),C({type:O("open_page"),url:d().nullish()}),C({type:O("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:O("file_search_call"),id:d(),queries:I(d()),results:I(C({attributes:ie(d(),he()),file_id:d(),filename:d(),score:M(),text:d()})).nullish()}),C({type:O("local_shell_call"),id:d(),call_id:d(),action:C({type:O("exec"),command:I(d()),timeout_ms:M().optional(),user:d().optional(),working_directory:d().optional(),env:ie(d(),d()).optional()})}),C({type:O("computer_call"),id:d(),status:O("completed")})])}),C({type:O("response.function_call_arguments.delta"),item_id:d(),output_index:M(),delta:d()}),C({type:O("response.image_generation_call.partial_image"),item_id:d(),output_index:M(),partial_image_b64:d()}),C({type:O("response.code_interpreter_call_code.delta"),item_id:d(),output_index:M(),delta:d()}),C({type:O("response.code_interpreter_call_code.done"),item_id:d(),output_index:M(),code:d()}),C({type:O("response.output_text.annotation.added"),annotation:Xe("type",[C({type:O("url_citation"),start_index:M(),end_index:M(),url:d(),title:d()}),C({type:O("file_citation"),file_id:d(),filename:d().nullish(),index:M().nullish(),start_index:M().nullish(),end_index:M().nullish(),quote:d().nullish()})])}),C({type:O("response.reasoning_summary_part.added"),item_id:d(),summary_index:M()}),C({type:O("response.reasoning_summary_text.delta"),item_id:d(),summary_index:M(),delta:d()}),C({type:O("response.reasoning_summary_part.done"),item_id:d(),summary_index:M()}),C({type:O("error"),sequence_number:M(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),UA=St(()=>Ue(C({id:d().optional(),created_at:M().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:I(Xe("type",[C({type:O("message"),role:O("assistant"),id:d(),content:I(C({type:O("output_text"),text:d(),logprobs:I(C({token:d(),logprob:M(),top_logprobs:I(C({token:d(),logprob:M()}))})).nullish(),annotations:I(Xe("type",[C({type:O("url_citation"),start_index:M(),end_index:M(),url:d(),title:d()}),C({type:O("file_citation"),file_id:d(),filename:d().nullish(),index:M().nullish(),start_index:M().nullish(),end_index:M().nullish(),quote:d().nullish()}),C({type:O("container_file_citation"),container_id:d(),file_id:d(),filename:d().nullish(),start_index:M().nullish(),end_index:M().nullish(),index:M().nullish()}),C({type:O("file_path"),file_id:d(),index:M().nullish()})]))}))}),C({type:O("web_search_call"),id:d(),status:d(),action:Xe("type",[C({type:O("search"),query:d().nullish(),sources:I(Xe("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).nullish()}),C({type:O("open_page"),url:d().nullish()}),C({type:O("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:O("file_search_call"),id:d(),queries:I(d()),results:I(C({attributes:ie(d(),ee([d(),M(),ne()])),file_id:d(),filename:d(),score:M(),text:d()})).nullish()}),C({type:O("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:I(Xe("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable()}),C({type:O("image_generation_call"),id:d(),result:d()}),C({type:O("local_shell_call"),id:d(),call_id:d(),action:C({type:O("exec"),command:I(d()),timeout_ms:M().optional(),user:d().optional(),working_directory:d().optional(),env:ie(d(),d()).optional()})}),C({type:O("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:O("computer_call"),id:d(),status:d().optional()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish(),summary:I(C({type:O("summary_text"),text:d()}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:M(),input_tokens_details:C({cached_tokens:M().nullish()}).nullish(),output_tokens:M(),output_tokens_details:C({reasoning_tokens:M().nullish()}).nullish()}).optional()}))),Y1=20,zA=St(()=>Ue(C({conversation:d().nullish(),include:I(we(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ee([ne(),M().min(1).max(Y1)]).optional(),maxToolCalls:M().nullish(),metadata:mt().nullish(),parallelToolCalls:ne().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:we(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:we(["auto","flex","priority","default"]).nullish(),store:ne().nullish(),strictJsonSchema:ne().nullish(),textVerbosity:we(["low","medium","high"]).nullish(),truncation:we(["auto","disabled"]).nullish(),user:d().nullish()})));async function DA({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const a of t)switch(a.type){case"function":s.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await cn({value:a.args,schema:_A});s.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{s.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await cn({value:a.args,schema:PA});s.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await cn({value:a.args,schema:$A});s.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await cn({value:a.args,schema:fA});s.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await cn({value:a.args,schema:wA});s.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{const a=o;throw new jr({functionality:`tool choice type: ${a}`})}}}var ZA=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:s,presencePenalty:o,frequencyPenalty:a,seed:i,prompt:c,providerOptions:l,tools:u,toolChoice:h,responseFormat:f}){var p,m,v,_;const w=[],g=z1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),i!=null&&w.push({type:"unsupported-setting",setting:"seed"}),o!=null&&w.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&w.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported-setting",setting:"stopSequences"});const y=await ln({provider:"openai",providerOptions:l,schema:zA});y?.conversation&&y?.previousResponseId&&w.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:S}=await LA({prompt:c,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(p=y?.store)!=null?p:!0,hasLocalShellTool:P("openai.local_shell")});w.push(...S);const k=(m=y?.strictJsonSchema)!=null?m:!1;let T=y?.include;function x(de){T==null?T=[de]:T.includes(de)||(T=[...T,de])}function P(de){return u?.find(se=>se.type==="provider-defined"&&se.id===de)!=null}const q=typeof y?.logprobs=="number"?y?.logprobs:y?.logprobs===!0?Y1:void 0;q&&x("message.output_text.logprobs");const N=(v=u?.find(de=>de.type==="provider-defined"&&(de.id==="openai.web_search"||de.id==="openai.web_search_preview")))==null?void 0:v.name;N&&x("web_search_call.action.sources"),P("openai.code_interpreter")&&x("code_interpreter_call.outputs");const z=y?.store;z===!1&&g.isReasoningModel&&x("reasoning.encrypted_content");const D={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(f?.type==="json"||y?.textVerbosity)&&{text:{...f?.type==="json"&&{format:f.schema!=null?{type:"json_schema",strict:k,name:(_=f.name)!=null?_:"response",description:f.description,schema:f.schema}:{type:"json_object"}},...y?.textVerbosity&&{verbosity:y.textVerbosity}}},conversation:y?.conversation,max_tool_calls:y?.maxToolCalls,metadata:y?.metadata,parallel_tool_calls:y?.parallelToolCalls,previous_response_id:y?.previousResponseId,store:z,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:T,prompt_cache_key:y?.promptCacheKey,prompt_cache_retention:y?.promptCacheRetention,safety_identifier:y?.safetyIdentifier,top_logprobs:q,truncation:y?.truncation,...g.isReasoningModel&&(y?.reasoningEffort!=null||y?.reasoningSummary!=null)&&{reasoning:{...y?.reasoningEffort!=null&&{effort:y.reasoningEffort},...y?.reasoningSummary!=null&&{summary:y.reasoningSummary}}}};g.isReasoningModel?y?.reasoningEffort==="none"&&g.supportsNonReasoningParameters||(D.temperature!=null&&(D.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),D.top_p!=null&&(D.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(y?.reasoningEffort!=null&&w.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),y?.reasoningSummary!=null&&w.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),y?.serviceTier==="flex"&&!g.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete D.service_tier),y?.serviceTier==="priority"&&!g.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete D.service_tier);const{tools:F,toolChoice:oe,toolWarnings:fe}=await DA({tools:u,toolChoice:h,strictJsonSchema:k});return{webSearchToolName:N,args:{...D,tools:F,tool_choice:oe},warnings:[...w,...fe],store:z}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,h,f,p,m,v,_,w,g,y,b,S,k,T,x,P,q,N,z;const{args:D,warnings:F,webSearchToolName:oe}=await this.getArgs(t),fe=this.config.url({path:"/responses",modelId:this.modelId}),de=this.config.provider.replace(".responses",""),{responseHeaders:se,value:_e,rawValue:H}=await Ur({url:fe,headers:Cr(this.config.headers(),t.headers),body:D,failedResponseHandler:Tr,successfulResponseHandler:bs(UA),abortSignal:t.abortSignal,fetch:this.config.fetch});if(_e.error)throw new Jt({message:_e.error.message,url:fe,requestBodyValues:D,statusCode:400,responseHeaders:se,responseBody:H,isRetryable:!1});const A=[],V=[];let j=!1;for(const $ of _e.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const B of $.summary)A.push({type:"reasoning",text:B.text,providerMetadata:{[de]:{itemId:$.id,reasoningEncryptedContent:(e=$.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{A.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),A.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{A.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[de]:{itemId:$.id}}});break}case"message":{for(const B of $.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&V.push(B.logprobs),A.push({type:"text",text:B.text,providerMetadata:{[de]:{itemId:$.id}}});for(const G of B.annotations)G.type==="url_citation"?A.push({type:"source",sourceType:"url",id:(a=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?a:ur(),url:G.url,title:G.title}):G.type==="file_citation"?A.push({type:"source",sourceType:"document",id:(l=(c=(i=this.config).generateId)==null?void 0:c.call(i))!=null?l:ur(),mediaType:"text/plain",title:(h=(u=G.quote)!=null?u:G.filename)!=null?h:"Document",filename:(f=G.filename)!=null?f:G.file_id,...G.file_id?{providerMetadata:{[de]:{fileId:G.file_id}}}:{}}):G.type==="container_file_citation"?A.push({type:"source",sourceType:"document",id:(v=(m=(p=this.config).generateId)==null?void 0:m.call(p))!=null?v:ur(),mediaType:"text/plain",title:(w=(_=G.filename)!=null?_:G.file_id)!=null?w:"Document",filename:(g=G.filename)!=null?g:G.file_id,providerMetadata:{[de]:{fileId:G.file_id,containerId:G.container_id,...G.index!=null?{index:G.index}:{}}}}):G.type==="file_path"&&A.push({type:"source",sourceType:"document",id:(S=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?S:ur(),mediaType:"application/octet-stream",title:G.file_id,filename:G.file_id,providerMetadata:{[de]:{fileId:G.file_id,...G.index!=null?{index:G.index}:{}}}})}break}case"function_call":{j=!0,A.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[de]:{itemId:$.id}}});break}case"web_search_call":{A.push({type:"tool-call",toolCallId:$.id,toolName:oe??"web_search",input:JSON.stringify({}),providerExecuted:!0}),A.push({type:"tool-result",toolCallId:$.id,toolName:oe??"web_search",result:X1($.action),providerExecuted:!0});break}case"computer_call":{A.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),A.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{A.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),A.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(T=(k=$.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?T:null},providerExecuted:!0});break}case"code_interpreter_call":{A.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),A.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[de]:{..._e.id!=null?{responseId:_e.id}:{}}};V.length>0&&(E[de].logprobs=V),typeof _e.service_tier=="string"&&(E[de].serviceTier=_e.service_tier);const R=_e.usage;return{content:A,finishReason:K1({finishReason:(x=_e.incomplete_details)==null?void 0:x.reason,hasFunctionCall:j}),usage:{inputTokens:R.input_tokens,outputTokens:R.output_tokens,totalTokens:R.input_tokens+R.output_tokens,reasoningTokens:(q=(P=R.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?q:void 0,cachedInputTokens:(z=(N=R.input_tokens_details)==null?void 0:N.cached_tokens)!=null?z:void 0},request:{body:D},response:{id:_e.id,timestamp:new Date(_e.created_at*1e3),modelId:_e.model,headers:se,body:H},providerMetadata:E,warnings:F}}async doStream(t){const{args:e,warnings:r,webSearchToolName:n,store:s}=await this.getArgs(t),{responseHeaders:o,value:a}=await Ur({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Tr,successfulResponseHandler:lp(jA),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this,c=this.config.provider.replace(".responses","");let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},h=[];let f=null;const p={},m=[];let v=!1;const _={};let w;return{stream:a.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,y){var b,S,k,T,x,P,q,N,z,D,F,oe,fe,de,se,_e,H,A,V,j,E,R;if(t.includeRawChunks&&y.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){l="error",y.enqueue({type:"error",error:g.error});return}const $=g.value;if(Q1($))$.item.type==="function_call"?(p[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},y.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(p[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),y.enqueue({type:"tool-input-end",id:$.item.id}),y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(p[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(p[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),y.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(m.splice(0,m.length),y.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id}}})):Q1($)&&$.item.type==="reasoning"&&(_[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},y.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(FA($)){if($.item.type==="message")y.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id,...m.length>0&&{annotations:m}}}});else if($.item.type==="function_call")p[$.output_index]=void 0,v=!0,y.enqueue({type:"tool-input-end",id:$.item.call_id}),y.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")p[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:X1($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")p[$.output_index]=void 0,y.enqueue({type:"tool-input-end",id:$.item.id}),y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")p[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(k=(S=$.item.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?k:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")p[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")p[$.output_index]=void 0,y.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const B=_[$.item.id],G=Object.entries(B.summaryParts).filter(([ve,pe])=>pe==="active"||pe==="can-conclude").map(([ve])=>ve);for(const ve of G)y.enqueue({type:"reasoning-end",id:`${$.item.id}:${ve}`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(T=$.item.encrypted_content)!=null?T:null}}});delete _[$.item.id]}}else if(JA($)){const B=p[$.output_index];B!=null&&y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:$.delta})}else if(WA($)){const B=p[$.output_index];B!=null&&y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(GA($)){const B=p[$.output_index];B!=null&&(y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:B.toolCallId}),y.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(BA($))f=$.response.id,y.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(VA($))y.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(P=(x=t.providerOptions)==null?void 0:x.openai)!=null&&P.logprobs&&$.logprobs&&h.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const B=_[$.item_id];B.summaryParts[$.summary_index]="active";for(const G of Object.keys(B.summaryParts))B.summaryParts[G]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${$.item_id}:${G}`,providerMetadata:{[c]:{itemId:$.item_id}}}),B.summaryParts[G]="concluded");y.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id,reasoningEncryptedContent:(N=(q=_[$.item_id])==null?void 0:q.encryptedContent)!=null?N:null}}})}}else $.type==="response.reasoning_summary_text.delta"?y.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[c]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(y.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id}}}),_[$.item_id].summaryParts[$.summary_index]="concluded"):_[$.item_id].summaryParts[$.summary_index]="can-conclude":HA($)?(l=K1({finishReason:(z=$.response.incomplete_details)==null?void 0:z.reason,hasFunctionCall:v}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(F=(D=$.response.usage.output_tokens_details)==null?void 0:D.reasoning_tokens)!=null?F:void 0,u.cachedInputTokens=(fe=(oe=$.response.usage.input_tokens_details)==null?void 0:oe.cached_tokens)!=null?fe:void 0,typeof $.response.service_tier=="string"&&(w=$.response.service_tier)):KA($)?(m.push($.annotation),$.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(_e=(se=(de=i.config).generateId)==null?void 0:se.call(de))!=null?_e:ur(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(V=(A=(H=i.config).generateId)==null?void 0:A.call(H))!=null?V:ur(),mediaType:"text/plain",title:(E=(j=$.annotation.quote)!=null?j:$.annotation.filename)!=null?E:"Document",filename:(R=$.annotation.filename)!=null?R:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[c]:{fileId:$.annotation.file_id}}}:{}})):YA($)&&y.enqueue({type:"error",error:$})},flush(g){const y={[c]:{responseId:f}};h.length>0&&(y[c].logprobs=h),w!==void 0&&(y[c].serviceTier=w),g.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:y})}})),request:{body:e},response:{headers:o}}}};function VA(t){return t.type==="response.output_text.delta"}function FA(t){return t.type==="response.output_item.done"}function HA(t){return t.type==="response.completed"||t.type==="response.incomplete"}function BA(t){return t.type==="response.created"}function JA(t){return t.type==="response.function_call_arguments.delta"}function WA(t){return t.type==="response.code_interpreter_call_code.delta"}function GA(t){return t.type==="response.code_interpreter_call_code.done"}function Q1(t){return t.type==="response.output_item.added"}function KA(t){return t.type==="response.output_text.annotation.added"}function YA(t){return t.type==="error"}function X1(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var QA=St(()=>Ue(C({instructions:d().nullish(),speed:M().min(.25).max(4).default(1).nullish()}))),XA=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:s,language:o,providerOptions:a}){const i=[],c=await ln({provider:"openai",providerOptions:a,schema:QA}),l={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?l.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const u={};for(const h in u){const f=u[h];f!==void 0&&(l[h]=f)}}return o&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:l,warnings:i}}async doGenerate(t){var e,r,n;const s=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:o,warnings:a}=await this.getArgs(t),{value:i,responseHeaders:c,rawValue:l}=await Ur({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),body:o,failedResponseHandler:Tr,successfulResponseHandler:QP(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:c,body:l}}}},eM=St(()=>Ue(C({text:d(),language:d().nullish(),duration:M().nullish(),words:I(C({word:d(),start:M(),end:M()})).nullish(),segments:I(C({id:M(),seek:M(),start:M(),end:M(),text:d(),tokens:I(M()),temperature:M(),avg_logprob:M(),compression_ratio:M(),no_speech_prob:M()})).nullish()}))),tM=St(()=>Ue(C({include:I(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:M().min(0).max(1).default(0).optional(),timestampGranularities:I(we(["word","segment"])).default(["segment"]).optional()}))),ew={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"},rM=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const n=[],s=await ln({provider:"openai",providerOptions:r,schema:tM}),o=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([BO(t)]);o.append("model",this.modelId);const i=UP(e);if(o.append("file",new File([a],"audio",{type:e}),`audio.${i}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[l,u]of Object.entries(c))if(u!=null)if(Array.isArray(u))for(const h of u)o.append(`${l}[]`,String(h));else o.append(l,String(u))}return{formData:o,warnings:n}}async doGenerate(t){var e,r,n,s,o,a,i,c;const l=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:h}=await this.getArgs(t),{value:f,responseHeaders:p,rawValue:m}=await KP({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Cr(this.config.headers(),t.headers),formData:u,failedResponseHandler:Tr,successfulResponseHandler:bs(eM),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=f.language!=null&&f.language in ew?ew[f.language]:void 0;return{text:f.text,segments:(i=(a=(s=f.segments)==null?void 0:s.map(_=>({text:_.text,startSecond:_.start,endSecond:_.end})))!=null?a:(o=f.words)==null?void 0:o.map(_=>({text:_.word,startSecond:_.start,endSecond:_.end})))!=null?i:[],language:v,durationInSeconds:(c=f.duration)!=null?c:void 0,warnings:h,response:{timestamp:l,modelId:this.modelId,headers:p,body:m}}}},nM="2.0.89";function tw(t={}){var e,r;const n=(e=WO(jP({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",s=(r=t.name)!=null?r:"openai",o=()=>x1({Authorization:`Bearer ${qP({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${nM}`),a=v=>new eA(v,{provider:`${s}.chat`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),i=v=>new sA(v,{provider:`${s}.completion`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),c=v=>new iA(v,{provider:`${s}.embedding`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),l=v=>new dA(v,{provider:`${s}.image`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),u=v=>new rM(v,{provider:`${s}.transcription`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),h=v=>new XA(v,{provider:`${s}.speech`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch}),f=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return p(v)},p=v=>new ZA(v,{provider:`${s}.responses`,url:({path:_})=>`${n}${_}`,headers:o,fetch:t.fetch,fileIdPrefixes:["file-"]}),m=function(v){return f(v)};return m.languageModel=f,m.chat=a,m.completion=i,m.responses=p,m.embedding=c,m.textEmbedding=c,m.textEmbeddingModel=c,m.image=l,m.imageModel=l,m.transcription=u,m.transcriptionModel=u,m.speech=h,m.speechModel=h,m.tools=NA,m}tw();function Zo(t){var e,r;return(r=(e=t?.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function sM(t){const e=[];for(const{role:r,content:n,...s}of t){const o=Zo({...s});switch(r){case"system":{e.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){e.push({role:"user",content:n[0].text,...Zo(n[0])});break}e.push({role:"user",content:n.map(a=>{const i=Zo(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const c=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${c};base64,${c8(a.data)}`},...i}}else throw new Gg({functionality:`file part media type ${a.mediaType}`})}}),...o});break}case"assistant":{let a="";const i=[];for(const c of n){const l=Zo(c);switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)},...l});break}}}e.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...o});break}case"tool":{for(const a of n){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}const l=Zo(a);e.push({role:"tool",tool_call_id:a.toolCallId,content:c,...l})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return e}function rw({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function nw(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var mp=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),oM=C({error:C({message:d(),type:d().nullish(),param:mt().nullish(),code:ee([d(),M()]).nullish()})}),aM={errorSchema:oM,errorToMessage:t=>t.error.message};function iM({tools:t,toolChoice:e}){t=t?.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of t)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const o=s;throw new Gg({functionality:`tool choice type: ${o}`})}}}var cM=class{constructor(t,e){this.specificationVersion="v2";var r,n;this.modelId=t,this.config=e;const s=(r=e.errorStructure)!=null?r:aM;this.chunkSchema=uM(s.errorSchema),this.failedResponseHandler=Mn(s),this.supportsStructuredOutputs=(n=e.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,providerOptions:i,stopSequences:c,responseFormat:l,seed:u,toolChoice:h,tools:f}){var p,m,v,_;const w=[],g=Object.assign((p=await r_({provider:"openai-compatible",providerOptions:i,schema:mp}))!=null?p:{},(m=await r_({provider:this.providerOptionsName,providerOptions:i,schema:mp}))!=null?m:{});s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:y,toolChoice:b,toolWarnings:S}=iM({tools:f,toolChoice:h});return{args:{model:this.modelId,user:g.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:l?.type==="json"?this.supportsStructuredOutputs===!0&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,name:(v=l.name)!=null?v:"response",description:l.description}}:{type:"json_object"}:void 0,stop:c,seed:u,...Object.fromEntries(Object.entries((_=i?.[this.providerOptionsName])!=null?_:{}).filter(([k])=>!Object.keys(mp.shape).includes(k))),reasoning_effort:g.reasoningEffort,verbosity:g.textVerbosity,messages:sM(t),tools:y,tool_choice:b},warnings:[...w,...S]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,h,f,p,m,v,_,w;const{args:g,warnings:y}=await this.getArgs({...t}),b=JSON.stringify(g),{responseHeaders:S,value:k,rawValue:T}=await hs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ds(this.config.headers(),t.headers),body:g,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fs(lM),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=k.choices[0],P=[],q=x.message.content;q!=null&&q.length>0&&P.push({type:"text",text:q});const N=(e=x.message.reasoning_content)!=null?e:x.message.reasoning;if(N!=null&&N.length>0&&P.push({type:"reasoning",text:N}),x.message.tool_calls!=null)for(const F of x.message.tool_calls)P.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:Eo(),toolName:F.function.name,input:F.function.arguments});const z={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:T}))},D=(o=k.usage)==null?void 0:o.completion_tokens_details;return D?.accepted_prediction_tokens!=null&&(z[this.providerOptionsName].acceptedPredictionTokens=D?.accepted_prediction_tokens),D?.rejected_prediction_tokens!=null&&(z[this.providerOptionsName].rejectedPredictionTokens=D?.rejected_prediction_tokens),{content:P,finishReason:nw(x.finish_reason),usage:{inputTokens:(i=(a=k.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(l=(c=k.usage)==null?void 0:c.completion_tokens)!=null?l:void 0,totalTokens:(h=(u=k.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(m=(p=(f=k.usage)==null?void 0:f.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?m:void 0,cachedInputTokens:(w=(_=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0},providerMetadata:z,request:{body:b},response:{...rw(k),headers:S,body:T},warnings:y}}async doStream(t){var e;const{args:r,warnings:n}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:a,value:i}=await hs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ds(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:s_(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let l="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const f=this.providerOptionsName;let p=!1,m=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,_){var w,g,y,b,S,k,T,x,P,q,N,z,D;if(t.includeRawChunks&&_.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){l="error",_.enqueue({type:"error",error:v.error});return}const F=v.value;if(o?.processChunk(v.rawValue),"error"in F){l="error",_.enqueue({type:"error",error:F.error.message});return}if(h&&(h=!1,_.enqueue({type:"response-metadata",...rw(F)})),F.usage!=null){const{prompt_tokens:se,completion_tokens:_e,total_tokens:H,prompt_tokens_details:A,completion_tokens_details:V}=F.usage;u.promptTokens=se??void 0,u.completionTokens=_e??void 0,u.totalTokens=H??void 0,V?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=V?.reasoning_tokens),V?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=V?.accepted_prediction_tokens),V?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=V?.rejected_prediction_tokens),A?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=A?.cached_tokens)}const oe=F.choices[0];if(oe?.finish_reason!=null&&(l=nw(oe.finish_reason)),oe?.delta==null)return;const fe=oe.delta,de=(w=fe.reasoning_content)!=null?w:fe.reasoning;if(de&&(p||(_.enqueue({type:"reasoning-start",id:"reasoning-0"}),p=!0),_.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),fe.content&&(m||(_.enqueue({type:"text-start",id:"txt-0"}),m=!0),_.enqueue({type:"text-delta",id:"txt-0",delta:fe.content})),fe.tool_calls!=null)for(const se of fe.tool_calls){const _e=se.index;if(c[_e]==null){if(se.id==null)throw new Og({data:se,message:"Expected 'id' to be a string."});if(((g=se.function)==null?void 0:g.name)==null)throw new Og({data:se,message:"Expected 'function.name' to be a string."});_.enqueue({type:"tool-input-start",id:se.id,toolName:se.function.name}),c[_e]={id:se.id,type:"function",function:{name:se.function.name,arguments:(y=se.function.arguments)!=null?y:""},hasFinished:!1};const A=c[_e];((b=A.function)==null?void 0:b.name)!=null&&((S=A.function)==null?void 0:S.arguments)!=null&&(A.function.arguments.length>0&&_.enqueue({type:"tool-input-delta",id:A.id,delta:A.function.arguments}),t_(A.function.arguments)&&(_.enqueue({type:"tool-input-end",id:A.id}),_.enqueue({type:"tool-call",toolCallId:(k=A.id)!=null?k:Eo(),toolName:A.function.name,input:A.function.arguments}),A.hasFinished=!0));continue}const H=c[_e];H.hasFinished||(((T=se.function)==null?void 0:T.arguments)!=null&&(H.function.arguments+=(P=(x=se.function)==null?void 0:x.arguments)!=null?P:""),_.enqueue({type:"tool-input-delta",id:H.id,delta:(q=se.function.arguments)!=null?q:""}),((N=H.function)==null?void 0:N.name)!=null&&((z=H.function)==null?void 0:z.arguments)!=null&&t_(H.function.arguments)&&(_.enqueue({type:"tool-input-end",id:H.id}),_.enqueue({type:"tool-call",toolCallId:(D=H.id)!=null?D:Eo(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(v){var _,w,g,y,b,S;p&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),m&&v.enqueue({type:"text-end",id:"txt-0"});for(const T of c.filter(x=>!x.hasFinished))v.enqueue({type:"tool-input-end",id:T.id}),v.enqueue({type:"tool-call",toolCallId:(_=T.id)!=null?_:Eo(),toolName:T.function.name,input:T.function.arguments});const k={[f]:{},...o?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[f].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[f].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:l,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(g=u.completionTokens)!=null?g:void 0,totalTokens:(y=u.totalTokens)!=null?y:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(S=u.promptTokensDetails.cachedTokens)!=null?S:void 0},providerMetadata:k})}})),request:{body:s},response:{headers:a}}}},sw=C({prompt_tokens:M().nullish(),completion_tokens:M().nullish(),total_tokens:M().nullish(),prompt_tokens_details:C({cached_tokens:M().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:M().nullish(),accepted_prediction_tokens:M().nullish(),rejected_prediction_tokens:M().nullish()}).nullish()}).nullish(),lM=C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({message:C({role:O("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:I(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:sw}),uM=t=>ee([C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({delta:C({role:we(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:I(C({index:M(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:sw}),t]);C({echo:ne().optional(),logitBias:ie(d(),M()).optional(),suffix:d().optional(),user:d().optional()});var dM=C({prompt_tokens:M(),completion_tokens:M(),total_tokens:M()});C({id:d().nullish(),created:M().nullish(),model:d().nullish(),choices:I(C({text:d(),finish_reason:d()})),usage:dM.nullish()}),C({dimensions:M().optional(),user:d().optional()}),C({data:I(C({embedding:I(M())})),usage:C({prompt_tokens:M()}).nullish(),providerMetadata:ie(d(),ie(d(),mt())).optional()}),C({data:I(C({b64_json:d()}))});var ow=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},pM={extractMetadata:async({parsedBody:t})=>{const e=await ir({value:t,schema:hM});return!e.success||e.value.usage==null?void 0:ow(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,n;const s=await ir({value:e,schema:fM});s.success&&((n=(r=s.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&s.value.usage&&(t=s.value.usage)},buildMetadata:()=>ow(t)}}},aw=C({prompt_cache_hit_tokens:M().nullish(),prompt_cache_miss_tokens:M().nullish()}),hM=C({usage:aw.nullish()}),fM=C({choices:I(C({finish_reason:d().nullish()})).nullish(),usage:aw.nullish()}),mM="1.0.30";function iw(t={}){var e;const r=d_((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),n=()=>on({Authorization:`Bearer ${nx({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${mM}`);class s extends cM{addJsonInstruction(c){var l;if(((l=c.responseFormat)==null?void 0:l.type)!=="json")return c;const f=[...Array.isArray(c.prompt)?c.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...c,prompt:f}}async doGenerate(c){return super.doGenerate(this.addJsonInstruction(c))}async doStream(c){return super.doStream(this.addJsonInstruction(c))}}const o=i=>new s(i,{provider:"deepseek.chat",url:({path:c})=>`${r}${c}`,headers:n,fetch:t.fetch,metadataExtractor:pM}),a=i=>o(i);return a.languageModel=o,a.chat=o,a.textEmbeddingModel=i=>{throw new Zg({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Zg({modelId:i,modelType:"imageModel"})},a}iw();const cw=async t=>{const e={};try{const r=await t.listTools();for(const{name:n,description:s,inputSchema:o}of r.tools){const a=async(i,c)=>t.callTool({name:n,arguments:i},{signal:c?.abortSignal});e[n]=n_({description:s,inputSchema:Io({...o,properties:o.properties??{},additionalProperties:!1}),execute:a})}return e}catch(r){throw r}};function gM(t){const e=Object.entries(t);if(e.length===0)return"";let r=`
|
|
589
|
+
${e}:`]}}function W1({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function G1(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var rI=_t(()=>Le(T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({text:m(),finish_reason:m(),logprobs:T({tokens:M(m()),token_logprobs:M(N()),top_logprobs:M(be(m(),N())).nullish()}).nullish()})),usage:T({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}))),nI=_t(()=>Le(ie([T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({text:m(),finish_reason:m().nullish(),index:N(),logprobs:T({tokens:M(m()),token_logprobs:M(N()),top_logprobs:M(be(m(),N())).nullish()}).nullish()})),usage:T({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}),cd]))),K1=_t(()=>Le(T({echo:me().optional(),logitBias:be(m(),N()).optional(),suffix:m().optional(),user:m().optional(),logprobs:ie([me(),N()]).optional()}))),sI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:c,tools:l,toolChoice:u,seed:p,providerOptions:h}){const d=[],f={...await Xr({provider:"openai",providerOptions:h,schema:K1}),...await Xr({provider:this.providerOptionsName,providerOptions:h,schema:K1})};s!=null&&d.push({type:"unsupported-setting",setting:"topK"}),l?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),c!=null&&c.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:y}=tI({prompt:t}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,seed:p,prompt:v,stop:w.length>0?w:void 0},warnings:d}}async doGenerate(t){var e,r,n;const{args:s,warnings:o}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:c}=await Pr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:s,failedResponseHandler:gr,successfulResponseHandler:ls(rI),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=i.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:G1(l.finish_reason),request:{body:s},response:{...W1(i),headers:a,body:c},providerMetadata:u,warnings:o}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Pr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:sd(nI),abortSignal:t.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:o.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,p){if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",p.enqueue({type:"error",error:h.error});return}l&&(l=!1,p.enqueue({type:"response-metadata",...W1(h)}),p.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(c.inputTokens=h.usage.prompt_tokens,c.outputTokens=h.usage.completion_tokens,c.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=G1(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&p.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){l||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:c})}})),request:{body:n},response:{headers:s}}}},oI=_t(()=>Le(T({dimensions:N().optional(),user:m().optional()}))),aI=_t(()=>Le(T({data:M(T({embedding:M(N())})),usage:T({prompt_tokens:N()}).nullish()}))),iI=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new x7({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Xr({provider:"openai",providerOptions:n,schema:oI}))!=null?s:{},{responseHeaders:a,value:i,rawValue:c}=await Pr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:mr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:gr,successfulResponseHandler:ls(aI),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(l=>l.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:c}}}},cI=_t(()=>Le(T({created:N().nullish(),data:M(T({b64_json:m(),revised_prompt:m().nullish()})),background:m().nullish(),output_format:m().nullish(),size:m().nullish(),quality:m().nullish(),usage:T({input_tokens:N().nullish(),output_tokens:N().nullish(),total_tokens:N().nullish(),input_tokens_details:T({image_tokens:N().nullish(),text_tokens:N().nullish()}).nullish()}).nullish()}))),lI={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},uI=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),dI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=lI[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var c,l,u,p;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(l=(c=this.config._internal)==null?void 0:c.currentDate)==null?void 0:l.call(c))!=null?u:new Date,{value:f,responseHeaders:v}=await Pr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:mr(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=o.openai)!=null?p:{},...uI.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:gr,successfulResponseHandler:ls(cI),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(y=>y.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:f.data.map(y=>({...y.revised_prompt?{revisedPrompt:y.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},pI=dt(()=>Le(T({code:m().nullish(),containerId:m()}))),fI=dt(()=>Le(T({outputs:M(Xe("type",[T({type:L("logs"),logs:m()}),T({type:L("image"),url:m()})])).nullish()}))),hI=dt(()=>Le(T({container:ie([m(),T({fileIds:M(m()).optional()})]).optional()}))),mI=cs({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:pI,outputSchema:fI}),gI=(t={})=>mI(t),Y1=T({key:m(),type:xe(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ie([m(),N(),me(),M(m())])}),Q1=T({type:xe(["and","or"]),filters:M(ie([Y1,sh(()=>Q1)]))}),yI=dt(()=>Le(T({vectorStoreIds:M(m()),maxNumResults:N().optional(),ranking:T({ranker:m().optional(),scoreThreshold:N().optional()}).optional(),filters:ie([Y1,Q1]).optional()}))),_I=dt(()=>Le(T({queries:M(m()),results:M(T({attributes:be(m(),Pe()),fileId:m(),filename:m(),score:N(),text:m()})).nullable()}))),vI=cs({id:"openai.file_search",name:"file_search",inputSchema:T({}),outputSchema:_I}),wI=dt(()=>Le(T({background:xe(["auto","opaque","transparent"]).optional(),inputFidelity:xe(["low","high"]).optional(),inputImageMask:T({fileId:m().optional(),imageUrl:m().optional()}).optional(),model:m().optional(),moderation:xe(["auto"]).optional(),outputCompression:N().int().min(0).max(100).optional(),outputFormat:xe(["png","jpeg","webp"]).optional(),partialImages:N().int().min(0).max(3).optional(),quality:xe(["auto","low","medium","high"]).optional(),size:xe(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),bI=dt(()=>Le(T({}))),kI=dt(()=>Le(T({result:m()}))),SI=cs({id:"openai.image_generation",name:"image_generation",inputSchema:bI,outputSchema:kI}),CI=(t={})=>SI(t),X1=dt(()=>Le(T({action:T({type:L("exec"),command:M(m()),timeoutMs:N().optional(),user:m().optional(),workingDirectory:m().optional(),env:be(m(),m()).optional()})}))),e_=dt(()=>Le(T({output:m()}))),TI=cs({id:"openai.local_shell",name:"local_shell",inputSchema:X1,outputSchema:e_}),$I=dt(()=>Le(T({externalWebAccess:me().optional(),filters:T({allowedDomains:M(m()).optional()}).optional(),searchContextSize:xe(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:m().optional(),city:m().optional(),region:m().optional(),timezone:m().optional()}).optional()}))),EI=dt(()=>Le(T({}))),xI=dt(()=>Le(T({action:Xe("type",[T({type:L("search"),query:m().optional()}),T({type:L("openPage"),url:m().nullish()}),T({type:L("findInPage"),url:m().nullish(),pattern:m().nullish()})]),sources:M(Xe("type",[T({type:L("url"),url:m()}),T({type:L("api"),name:m()})])).optional()}))),II=cs({id:"openai.web_search",name:"web_search",inputSchema:EI,outputSchema:xI}),RI=(t={})=>II(t),PI=dt(()=>Le(T({searchContextSize:xe(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:m().optional(),city:m().optional(),region:m().optional(),timezone:m().optional()}).optional()}))),OI=dt(()=>Le(T({}))),AI=dt(()=>Le(T({action:Xe("type",[T({type:L("search"),query:m().optional()}),T({type:L("openPage"),url:m().nullish()}),T({type:L("findInPage"),url:m().nullish(),pattern:m().nullish()})])}))),MI=cs({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:OI,outputSchema:AI}),NI={codeInterpreter:gI,fileSearch:vI,imageGeneration:CI,localShell:TI,webSearchPreview:MI,webSearch:RI};function t_(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function LI({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:s=!1}){var o,a,i,c;const l=[],u=[];for(const{role:p,content:h}of t)switch(p){case"system":{switch(e){case"system":{l.push({role:"system",content:h});break}case"developer":{l.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{l.push({role:"user",content:h.map((d,f)=>{var v,y,w;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const g=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&t_(d.data,r)?{file_id:d.data}:{image_url:`data:${g};base64,${us(d.data)}`},detail:(y=(v=d.providerOptions)==null?void 0:v.openai)==null?void 0:y.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&t_(d.data,r)?{file_id:d.data}:{filename:(w=d.filename)!=null?w:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${us(d.data)}`}};throw new Rr({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},f={};for(const v of h)switch(v.type){case"text":{const y=(a=(o=v.providerOptions)==null?void 0:o.openai)==null?void 0:a.itemId;if(n&&y!=null){l.push({type:"item_reference",id:y});break}l.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:y});break}case"tool-call":{if(f[v.toolCallId]=v,v.providerExecuted)break;const y=(c=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:c.itemId;if(n&&y!=null){l.push({type:"item_reference",id:y});break}if(s&&v.toolName==="local_shell"){const w=await Qr({value:v.input,schema:X1});l.push({type:"local_shell_call",call_id:v.toolCallId,id:y,action:{type:"exec",command:w.action.command,timeout_ms:w.action.timeoutMs,user:w.action.user,working_directory:w.action.workingDirectory,env:w.action.env}});break}l.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:y});break}case"tool-result":{n?l.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const y=await Xr({provider:"openai",providerOptions:v.providerOptions,schema:jI}),w=y?.itemId;if(w!=null){const g=d[w];if(n)g===void 0&&(l.push({type:"item_reference",id:w}),d[w]={type:"reasoning",id:w,summary:[]});else{const _=[];v.text.length>0?_.push({type:"summary_text",text:v.text}):g!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),g===void 0?(d[w]={type:"reasoning",id:w,encrypted_content:y?.reasoningEncryptedContent,summary:_},l.push(d[w])):(g.summary.push(..._),y?.reasoningEncryptedContent!=null&&(g.encrypted_content=y.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const d of h){const f=d.output;if(s&&d.toolName==="local_shell"&&f.type==="json"){const y=await Qr({value:f.value,schema:e_});l.push({type:"local_shell_call_output",call_id:d.toolCallId,output:y.output});break}let v;switch(f.type){case"text":case"error-text":v=f.value;break;case"json":case"error-json":v=JSON.stringify(f.value);break;case"content":v=f.value.map(y=>{switch(y.type){case"text":return{type:"input_text",text:y.text};case"media":return y.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${y.mediaType};base64,${y.data}`}:{type:"input_file",filename:"data",file_data:`data:${y.mediaType};base64,${y.data}`}}});break}l.push({type:"function_call_output",call_id:d.toolCallId,output:v})}break}default:{const d=p;throw new Error(`Unsupported role: ${d}`)}}return{input:l,warnings:u}}var jI=T({itemId:m().nullish(),reasoningEncryptedContent:m().nullish()});function r_({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var qI=_t(()=>Le(ie([T({type:L("response.output_text.delta"),item_id:m(),delta:m(),logprobs:M(T({token:m(),logprob:N(),top_logprobs:M(T({token:m(),logprob:N()}))})).nullish()}),T({type:xe(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:m()}).nullish(),usage:T({input_tokens:N(),input_tokens_details:T({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:T({reasoning_tokens:N().nullish()}).nullish()}),service_tier:m().nullish()})}),T({type:L("response.created"),response:T({id:m(),created_at:N(),model:m(),service_tier:m().nullish()})}),T({type:L("response.output_item.added"),output_index:N(),item:Xe("type",[T({type:L("message"),id:m()}),T({type:L("reasoning"),id:m(),encrypted_content:m().nullish()}),T({type:L("function_call"),id:m(),call_id:m(),name:m(),arguments:m()}),T({type:L("web_search_call"),id:m(),status:m()}),T({type:L("computer_call"),id:m(),status:m()}),T({type:L("file_search_call"),id:m()}),T({type:L("image_generation_call"),id:m()}),T({type:L("code_interpreter_call"),id:m(),container_id:m(),code:m().nullable(),outputs:M(Xe("type",[T({type:L("logs"),logs:m()}),T({type:L("image"),url:m()})])).nullable(),status:m()})])}),T({type:L("response.output_item.done"),output_index:N(),item:Xe("type",[T({type:L("message"),id:m()}),T({type:L("reasoning"),id:m(),encrypted_content:m().nullish()}),T({type:L("function_call"),id:m(),call_id:m(),name:m(),arguments:m(),status:L("completed")}),T({type:L("code_interpreter_call"),id:m(),code:m().nullable(),container_id:m(),outputs:M(Xe("type",[T({type:L("logs"),logs:m()}),T({type:L("image"),url:m()})])).nullable()}),T({type:L("image_generation_call"),id:m(),result:m()}),T({type:L("web_search_call"),id:m(),status:m(),action:Xe("type",[T({type:L("search"),query:m().nullish(),sources:M(Xe("type",[T({type:L("url"),url:m()}),T({type:L("api"),name:m()})])).nullish()}),T({type:L("open_page"),url:m().nullish()}),T({type:L("find_in_page"),url:m().nullish(),pattern:m().nullish()})])}),T({type:L("file_search_call"),id:m(),queries:M(m()),results:M(T({attributes:be(m(),Pe()),file_id:m(),filename:m(),score:N(),text:m()})).nullish()}),T({type:L("local_shell_call"),id:m(),call_id:m(),action:T({type:L("exec"),command:M(m()),timeout_ms:N().optional(),user:m().optional(),working_directory:m().optional(),env:be(m(),m()).optional()})}),T({type:L("computer_call"),id:m(),status:L("completed")})])}),T({type:L("response.function_call_arguments.delta"),item_id:m(),output_index:N(),delta:m()}),T({type:L("response.image_generation_call.partial_image"),item_id:m(),output_index:N(),partial_image_b64:m()}),T({type:L("response.code_interpreter_call_code.delta"),item_id:m(),output_index:N(),delta:m()}),T({type:L("response.code_interpreter_call_code.done"),item_id:m(),output_index:N(),code:m()}),T({type:L("response.output_text.annotation.added"),annotation:Xe("type",[T({type:L("url_citation"),start_index:N(),end_index:N(),url:m(),title:m()}),T({type:L("file_citation"),file_id:m(),filename:m().nullish(),index:N().nullish(),start_index:N().nullish(),end_index:N().nullish(),quote:m().nullish()})])}),T({type:L("response.reasoning_summary_part.added"),item_id:m(),summary_index:N()}),T({type:L("response.reasoning_summary_text.delta"),item_id:m(),summary_index:N(),delta:m()}),T({type:L("response.reasoning_summary_part.done"),item_id:m(),summary_index:N()}),T({type:L("error"),sequence_number:N(),error:T({type:m(),code:m(),message:m(),param:m().nullish()})}),T({type:m()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),zI=_t(()=>Le(T({id:m().optional(),created_at:N().optional(),error:T({message:m(),type:m(),param:m().nullish(),code:m()}).nullish(),model:m().optional(),output:M(Xe("type",[T({type:L("message"),role:L("assistant"),id:m(),content:M(T({type:L("output_text"),text:m(),logprobs:M(T({token:m(),logprob:N(),top_logprobs:M(T({token:m(),logprob:N()}))})).nullish(),annotations:M(Xe("type",[T({type:L("url_citation"),start_index:N(),end_index:N(),url:m(),title:m()}),T({type:L("file_citation"),file_id:m(),filename:m().nullish(),index:N().nullish(),start_index:N().nullish(),end_index:N().nullish(),quote:m().nullish()}),T({type:L("container_file_citation"),container_id:m(),file_id:m(),filename:m().nullish(),start_index:N().nullish(),end_index:N().nullish(),index:N().nullish()}),T({type:L("file_path"),file_id:m(),index:N().nullish()})]))}))}),T({type:L("web_search_call"),id:m(),status:m(),action:Xe("type",[T({type:L("search"),query:m().nullish(),sources:M(Xe("type",[T({type:L("url"),url:m()}),T({type:L("api"),name:m()})])).nullish()}),T({type:L("open_page"),url:m().nullish()}),T({type:L("find_in_page"),url:m().nullish(),pattern:m().nullish()})])}),T({type:L("file_search_call"),id:m(),queries:M(m()),results:M(T({attributes:be(m(),ie([m(),N(),me()])),file_id:m(),filename:m(),score:N(),text:m()})).nullish()}),T({type:L("code_interpreter_call"),id:m(),code:m().nullable(),container_id:m(),outputs:M(Xe("type",[T({type:L("logs"),logs:m()}),T({type:L("image"),url:m()})])).nullable()}),T({type:L("image_generation_call"),id:m(),result:m()}),T({type:L("local_shell_call"),id:m(),call_id:m(),action:T({type:L("exec"),command:M(m()),timeout_ms:N().optional(),user:m().optional(),working_directory:m().optional(),env:be(m(),m()).optional()})}),T({type:L("function_call"),call_id:m(),name:m(),arguments:m(),id:m()}),T({type:L("computer_call"),id:m(),status:m().optional()}),T({type:L("reasoning"),id:m(),encrypted_content:m().nullish(),summary:M(T({type:L("summary_text"),text:m()}))})])).optional(),service_tier:m().nullish(),incomplete_details:T({reason:m()}).nullish(),usage:T({input_tokens:N(),input_tokens_details:T({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:T({reasoning_tokens:N().nullish()}).nullish()}).optional()}))),n_=20,DI=_t(()=>Le(T({conversation:m().nullish(),include:M(xe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:m().nullish(),logprobs:ie([me(),N().min(1).max(n_)]).optional(),maxToolCalls:N().nullish(),metadata:ht().nullish(),parallelToolCalls:me().nullish(),previousResponseId:m().nullish(),promptCacheKey:m().nullish(),promptCacheRetention:xe(["in_memory","24h"]).nullish(),reasoningEffort:m().nullish(),reasoningSummary:m().nullish(),safetyIdentifier:m().nullish(),serviceTier:xe(["auto","flex","priority","default"]).nullish(),store:me().nullish(),strictJsonSchema:me().nullish(),textVerbosity:xe(["low","medium","high"]).nullish(),truncation:xe(["auto","disabled"]).nullish(),user:m().nullish()})));async function UI({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const a of t)switch(a.type){case"function":s.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await Qr({value:a.args,schema:yI});s.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{s.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await Qr({value:a.args,schema:PI});s.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await Qr({value:a.args,schema:$I});s.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await Qr({value:a.args,schema:hI});s.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await Qr({value:a.args,schema:wI});s.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{const a=o;throw new Rr({functionality:`tool choice type: ${a}`})}}}var ZI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:s,presencePenalty:o,frequencyPenalty:a,seed:i,prompt:c,providerOptions:l,tools:u,toolChoice:p,responseFormat:h}){var d,f,v,y;const w=[],g=B1(this.modelId);s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),i!=null&&w.push({type:"unsupported-setting",setting:"seed"}),o!=null&&w.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&w.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported-setting",setting:"stopSequences"});const _=await Xr({provider:"openai",providerOptions:l,schema:DI});_?.conversation&&_?.previousResponseId&&w.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await LI({prompt:c,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=_?.store)!=null?d:!0,hasLocalShellTool:R("openai.local_shell")});w.push(...k);const S=(f=_?.strictJsonSchema)!=null?f:!1;let C=_?.include;function x(de){C==null?C=[de]:C.includes(de)||(C=[...C,de])}function R(de){return u?.find(te=>te.type==="provider-defined"&&te.id===de)!=null}const j=typeof _?.logprobs=="number"?_?.logprobs:_?.logprobs===!0?n_:void 0;j&&x("message.output_text.logprobs");const O=(v=u?.find(de=>de.type==="provider-defined"&&(de.id==="openai.web_search"||de.id==="openai.web_search_preview")))==null?void 0:v.name;O&&x("web_search_call.action.sources"),R("openai.code_interpreter")&&x("code_interpreter_call.outputs");const D=_?.store;D===!1&&g.isReasoningModel&&x("reasoning.encrypted_content");const U={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(h?.type==="json"||_?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(y=h.name)!=null?y:"response",description:h.description,schema:h.schema}:{type:"json_object"}},..._?.textVerbosity&&{verbosity:_.textVerbosity}}},conversation:_?.conversation,max_tool_calls:_?.maxToolCalls,metadata:_?.metadata,parallel_tool_calls:_?.parallelToolCalls,previous_response_id:_?.previousResponseId,store:D,user:_?.user,instructions:_?.instructions,service_tier:_?.serviceTier,include:C,prompt_cache_key:_?.promptCacheKey,prompt_cache_retention:_?.promptCacheRetention,safety_identifier:_?.safetyIdentifier,top_logprobs:j,truncation:_?.truncation,...g.isReasoningModel&&(_?.reasoningEffort!=null||_?.reasoningSummary!=null)&&{reasoning:{..._?.reasoningEffort!=null&&{effort:_.reasoningEffort},..._?.reasoningSummary!=null&&{summary:_.reasoningSummary}}}};g.isReasoningModel?_?.reasoningEffort==="none"&&g.supportsNonReasoningParameters||(U.temperature!=null&&(U.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),U.top_p!=null&&(U.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(_?.reasoningEffort!=null&&w.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),_?.reasoningSummary!=null&&w.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),_?.serviceTier==="flex"&&!g.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U.service_tier),_?.serviceTier==="priority"&&!g.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete U.service_tier);const{tools:V,toolChoice:ne,toolWarnings:fe}=await UI({tools:u,toolChoice:p,strictJsonSchema:S});return{webSearchToolName:O,args:{...U,tools:V,tool_choice:ne},warnings:[...w,...fe],store:D}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f,v,y,w,g,_,b,k,S,C,x,R,j,O,D;const{args:U,warnings:V,webSearchToolName:ne}=await this.getArgs(t),fe=this.config.url({path:"/responses",modelId:this.modelId}),de=this.config.provider.replace(".responses",""),{responseHeaders:te,value:ye,rawValue:H}=await Pr({url:fe,headers:mr(this.config.headers(),t.headers),body:U,failedResponseHandler:gr,successfulResponseHandler:ls(zI),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ye.error)throw new Ut({message:ye.error.message,url:fe,requestBodyValues:U,statusCode:400,responseHeaders:te,responseBody:H,isRetryable:!1});const P=[],F=[];let q=!1;for(const $ of ye.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const B of $.summary)P.push({type:"reasoning",text:B.text,providerMetadata:{[de]:{itemId:$.id,reasoningEncryptedContent:(e=$.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[de]:{itemId:$.id}}});break}case"message":{for(const B of $.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&F.push(B.logprobs),P.push({type:"text",text:B.text,providerMetadata:{[de]:{itemId:$.id}}});for(const G of B.annotations)G.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?a:nr(),url:G.url,title:G.title}):G.type==="file_citation"?P.push({type:"source",sourceType:"document",id:(l=(c=(i=this.config).generateId)==null?void 0:c.call(i))!=null?l:nr(),mediaType:"text/plain",title:(p=(u=G.quote)!=null?u:G.filename)!=null?p:"Document",filename:(h=G.filename)!=null?h:G.file_id,...G.file_id?{providerMetadata:{[de]:{fileId:G.file_id}}}:{}}):G.type==="container_file_citation"?P.push({type:"source",sourceType:"document",id:(v=(f=(d=this.config).generateId)==null?void 0:f.call(d))!=null?v:nr(),mediaType:"text/plain",title:(w=(y=G.filename)!=null?y:G.file_id)!=null?w:"Document",filename:(g=G.filename)!=null?g:G.file_id,providerMetadata:{[de]:{fileId:G.file_id,containerId:G.container_id,...G.index!=null?{index:G.index}:{}}}}):G.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(k=(b=(_=this.config).generateId)==null?void 0:b.call(_))!=null?k:nr(),mediaType:"application/octet-stream",title:G.file_id,filename:G.file_id,providerMetadata:{[de]:{fileId:G.file_id,...G.index!=null?{index:G.index}:{}}}})}break}case"function_call":{q=!0,P.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[de]:{itemId:$.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:ne??"web_search",input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:ne??"web_search",result:o_($.action),providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(C=(S=$.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?C:null},providerExecuted:!0});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[de]:{...ye.id!=null?{responseId:ye.id}:{}}};F.length>0&&(E[de].logprobs=F),typeof ye.service_tier=="string"&&(E[de].serviceTier=ye.service_tier);const I=ye.usage;return{content:P,finishReason:r_({finishReason:(x=ye.incomplete_details)==null?void 0:x.reason,hasFunctionCall:q}),usage:{inputTokens:I.input_tokens,outputTokens:I.output_tokens,totalTokens:I.input_tokens+I.output_tokens,reasoningTokens:(j=(R=I.output_tokens_details)==null?void 0:R.reasoning_tokens)!=null?j:void 0,cachedInputTokens:(D=(O=I.input_tokens_details)==null?void 0:O.cached_tokens)!=null?D:void 0},request:{body:U},response:{id:ye.id,timestamp:new Date(ye.created_at*1e3),modelId:ye.model,headers:te,body:H},providerMetadata:E,warnings:V}}async doStream(t){const{args:e,warnings:r,webSearchToolName:n,store:s}=await this.getArgs(t),{responseHeaders:o,value:a}=await Pr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:gr,successfulResponseHandler:sd(qI),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this,c=this.config.provider.replace(".responses","");let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},p=[];let h=null;const d={},f=[];let v=!1;const y={};let w;return{stream:a.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,_){var b,k,S,C,x,R,j,O,D,U,V,ne,fe,de,te,ye,H,P,F,q,E,I;if(t.includeRawChunks&&_.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){l="error",_.enqueue({type:"error",error:g.error});return}const $=g.value;if(s_($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},_.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),_.enqueue({type:"tool-input-end",id:$.item.id}),_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},_.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),_.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(f.splice(0,f.length),_.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id}}})):s_($)&&$.item.type==="reasoning"&&(y[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},_.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(VI($)){if($.item.type==="message")_.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[c]:{itemId:$.item.id,...f.length>0&&{annotations:f}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,v=!0,_.enqueue({type:"tool-input-end",id:$.item.call_id}),_.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:o_($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,_.enqueue({type:"tool-input-end",id:$.item.id}),_.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")_.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,_.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[c]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const B=y[$.item.id],G=Object.entries(B.summaryParts).filter(([_e,pe])=>pe==="active"||pe==="can-conclude").map(([_e])=>_e);for(const _e of G)_.enqueue({type:"reasoning-end",id:`${$.item.id}:${_e}`,providerMetadata:{[c]:{itemId:$.item.id,reasoningEncryptedContent:(C=$.item.encrypted_content)!=null?C:null}}});delete y[$.item.id]}}else if(JI($)){const B=d[$.output_index];B!=null&&_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:$.delta})}else if(WI($)){const B=d[$.output_index];B!=null&&_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(GI($)){const B=d[$.output_index];B!=null&&(_.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),_.enqueue({type:"tool-input-end",id:B.toolCallId}),_.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(BI($))h=$.response.id,_.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(FI($))_.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(R=(x=t.providerOptions)==null?void 0:x.openai)!=null&&R.logprobs&&$.logprobs&&p.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const B=y[$.item_id];B.summaryParts[$.summary_index]="active";for(const G of Object.keys(B.summaryParts))B.summaryParts[G]==="can-conclude"&&(_.enqueue({type:"reasoning-end",id:`${$.item_id}:${G}`,providerMetadata:{[c]:{itemId:$.item_id}}}),B.summaryParts[G]="concluded");_.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id,reasoningEncryptedContent:(O=(j=y[$.item_id])==null?void 0:j.encryptedContent)!=null?O:null}}})}}else $.type==="response.reasoning_summary_text.delta"?_.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[c]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(_.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[c]:{itemId:$.item_id}}}),y[$.item_id].summaryParts[$.summary_index]="concluded"):y[$.item_id].summaryParts[$.summary_index]="can-conclude":HI($)?(l=r_({finishReason:(D=$.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:v}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(V=(U=$.response.usage.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?V:void 0,u.cachedInputTokens=(fe=(ne=$.response.usage.input_tokens_details)==null?void 0:ne.cached_tokens)!=null?fe:void 0,typeof $.response.service_tier=="string"&&(w=$.response.service_tier)):KI($)?(f.push($.annotation),$.annotation.type==="url_citation"?_.enqueue({type:"source",sourceType:"url",id:(ye=(te=(de=i.config).generateId)==null?void 0:te.call(de))!=null?ye:nr(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&_.enqueue({type:"source",sourceType:"document",id:(F=(P=(H=i.config).generateId)==null?void 0:P.call(H))!=null?F:nr(),mediaType:"text/plain",title:(E=(q=$.annotation.quote)!=null?q:$.annotation.filename)!=null?E:"Document",filename:(I=$.annotation.filename)!=null?I:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[c]:{fileId:$.annotation.file_id}}}:{}})):YI($)&&_.enqueue({type:"error",error:$})},flush(g){const _={[c]:{responseId:h}};p.length>0&&(_[c].logprobs=p),w!==void 0&&(_[c].serviceTier=w),g.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:_})}})),request:{body:e},response:{headers:o}}}};function FI(t){return t.type==="response.output_text.delta"}function VI(t){return t.type==="response.output_item.done"}function HI(t){return t.type==="response.completed"||t.type==="response.incomplete"}function BI(t){return t.type==="response.created"}function JI(t){return t.type==="response.function_call_arguments.delta"}function WI(t){return t.type==="response.code_interpreter_call_code.delta"}function GI(t){return t.type==="response.code_interpreter_call_code.done"}function s_(t){return t.type==="response.output_item.added"}function KI(t){return t.type==="response.output_text.annotation.added"}function YI(t){return t.type==="error"}function o_(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var QI=_t(()=>Le(T({instructions:m().nullish(),speed:N().min(.25).max(4).default(1).nullish()}))),XI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:s,language:o,providerOptions:a}){const i=[],c=await Xr({provider:"openai",providerOptions:a,schema:QI}),l={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?l.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const u={};for(const p in u){const h=u[p];h!==void 0&&(l[p]=h)}}return o&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:l,warnings:i}}async doGenerate(t){var e,r,n;const s=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:o,warnings:a}=await this.getArgs(t),{value:i,responseHeaders:c,rawValue:l}=await Pr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:o,failedResponseHandler:gr,successfulResponseHandler:Q7(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:c,body:l}}}},eR=_t(()=>Le(T({text:m(),language:m().nullish(),duration:N().nullish(),words:M(T({word:m(),start:N(),end:N()})).nullish(),segments:M(T({id:N(),seek:N(),start:N(),end:N(),text:m(),tokens:M(N()),temperature:N(),avg_logprob:N(),compression_ratio:N(),no_speech_prob:N()})).nullish()}))),tR=_t(()=>Le(T({include:M(m()).optional(),language:m().optional(),prompt:m().optional(),temperature:N().min(0).max(1).default(0).optional(),timestampGranularities:M(xe(["word","segment"])).default(["segment"]).optional()}))),a_={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"},rR=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const n=[],s=await Xr({provider:"openai",providerOptions:r,schema:tR}),o=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([Bx(t)]);o.append("model",this.modelId);const i=z7(e);if(o.append("file",new File([a],"audio",{type:e}),`audio.${i}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[l,u]of Object.entries(c))if(u!=null)if(Array.isArray(u))for(const p of u)o.append(`${l}[]`,String(p));else o.append(l,String(u))}return{formData:o,warnings:n}}async doGenerate(t){var e,r,n,s,o,a,i,c;const l=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:p}=await this.getArgs(t),{value:h,responseHeaders:d,rawValue:f}=await K7({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),formData:u,failedResponseHandler:gr,successfulResponseHandler:ls(eR),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=h.language!=null&&h.language in a_?a_[h.language]:void 0;return{text:h.text,segments:(i=(a=(s=h.segments)==null?void 0:s.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?a:(o=h.words)==null?void 0:o.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:v,durationInSeconds:(c=h.duration)!=null?c:void 0,warnings:p,response:{timestamp:l,modelId:this.modelId,headers:d,body:f}}}},nR="2.0.89";function i_(t={}){var e,r;const n=(e=Wx(q7({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",s=(r=t.name)!=null?r:"openai",o=()=>M1({Authorization:`Bearer ${j7({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${nR}`),a=v=>new eI(v,{provider:`${s}.chat`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),i=v=>new sI(v,{provider:`${s}.completion`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),c=v=>new iI(v,{provider:`${s}.embedding`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),l=v=>new dI(v,{provider:`${s}.image`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),u=v=>new rR(v,{provider:`${s}.transcription`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),p=v=>new XI(v,{provider:`${s}.speech`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch}),h=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(v)},d=v=>new ZI(v,{provider:`${s}.responses`,url:({path:y})=>`${n}${y}`,headers:o,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(v){return h(v)};return f.languageModel=h,f.chat=a,f.completion=i,f.responses=d,f.embedding=c,f.textEmbedding=c,f.textEmbeddingModel=c,f.image=l,f.imageModel=l,f.transcription=u,f.transcriptionModel=u,f.speech=p,f.speechModel=p,f.tools=NI,f}i_();function Eo(t){var e,r;return(r=(e=t?.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function sR(t){const e=[];for(const{role:r,content:n,...s}of t){const o=Eo({...s});switch(r){case"system":{e.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){e.push({role:"user",content:n[0].text,...Eo(n[0])});break}e.push({role:"user",content:n.map(a=>{const i=Eo(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const c=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${c};base64,${cT(a.data)}`},...i}}else throw new t2({functionality:`file part media type ${a.mediaType}`})}}),...o});break}case"assistant":{let a="";const i=[];for(const c of n){const l=Eo(c);switch(c.type){case"text":{a+=c.text;break}case"tool-call":{i.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)},...l});break}}}e.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...o});break}case"tool":{for(const a of n){const i=a.output;let c;switch(i.type){case"text":case"error-text":c=i.value;break;case"content":case"json":case"error-json":c=JSON.stringify(i.value);break}const l=Eo(a);e.push({role:"tool",tool_call_id:a.toolCallId,content:c,...l})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return e}function c_({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function l_(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var ud=T({user:m().optional(),reasoningEffort:m().optional(),textVerbosity:m().optional()}),oR=T({error:T({message:m(),type:m().nullish(),param:ht().nullish(),code:ie([m(),N()]).nullish()})}),aR={errorSchema:oR,errorToMessage:t=>t.error.message};function iR({tools:t,toolChoice:e}){t=t?.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of t)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const o=s;throw new t2({functionality:`tool choice type: ${o}`})}}}var cR=class{constructor(t,e){this.specificationVersion="v2";var r,n;this.modelId=t,this.config=e;const s=(r=e.errorStructure)!=null?r:aR;this.chunkSchema=uR(s.errorSchema),this.failedResponseHandler=bn(s),this.supportsStructuredOutputs=(n=e.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,providerOptions:i,stopSequences:c,responseFormat:l,seed:u,toolChoice:p,tools:h}){var d,f,v,y;const w=[],g=Object.assign((d=await c2({provider:"openai-compatible",providerOptions:i,schema:ud}))!=null?d:{},(f=await c2({provider:this.providerOptionsName,providerOptions:i,schema:ud}))!=null?f:{});s!=null&&w.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:_,toolChoice:b,toolWarnings:k}=iR({tools:h,toolChoice:p});return{args:{model:this.modelId,user:g.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:l?.type==="json"?this.supportsStructuredOutputs===!0&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,name:(v=l.name)!=null?v:"response",description:l.description}}:{type:"json_object"}:void 0,stop:c,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([S])=>!Object.keys(ud.shape).includes(S))),reasoning_effort:g.reasoningEffort,verbosity:g.textVerbosity,messages:sR(t),tools:_,tool_choice:b},warnings:[...w,...k]}}async doGenerate(t){var e,r,n,s,o,a,i,c,l,u,p,h,d,f,v,y,w;const{args:g,warnings:_}=await this.getArgs({...t}),b=JSON.stringify(g),{responseHeaders:k,value:S,rawValue:C}=await ts({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Xn(this.config.headers(),t.headers),body:g,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rs(lR),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=S.choices[0],R=[],j=x.message.content;j!=null&&j.length>0&&R.push({type:"text",text:j});const O=(e=x.message.reasoning_content)!=null?e:x.message.reasoning;if(O!=null&&O.length>0&&R.push({type:"reasoning",text:O}),x.message.tool_calls!=null)for(const V of x.message.tool_calls)R.push({type:"tool-call",toolCallId:(r=V.id)!=null?r:po(),toolName:V.function.name,input:V.function.arguments});const D={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:C}))},U=(o=S.usage)==null?void 0:o.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:R,finishReason:l_(x.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(l=(c=S.usage)==null?void 0:c.completion_tokens)!=null?l:void 0,totalTokens:(p=(u=S.usage)==null?void 0:u.total_tokens)!=null?p:void 0,reasoningTokens:(f=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(w=(y=(v=S.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:D,request:{body:b},response:{...c_(S),headers:k,body:C},warnings:_}}async doStream(t){var e;const{args:r,warnings:n}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:a,value:i}=await ts({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Xn(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:u2(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let l="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let p=!0;const h=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,g,_,b,k,S,C,x,R,j,O,D,U;if(t.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){l="error",y.enqueue({type:"error",error:v.error});return}const V=v.value;if(o?.processChunk(v.rawValue),"error"in V){l="error",y.enqueue({type:"error",error:V.error.message});return}if(p&&(p=!1,y.enqueue({type:"response-metadata",...c_(V)})),V.usage!=null){const{prompt_tokens:te,completion_tokens:ye,total_tokens:H,prompt_tokens_details:P,completion_tokens_details:F}=V.usage;u.promptTokens=te??void 0,u.completionTokens=ye??void 0,u.totalTokens=H??void 0,F?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=F?.reasoning_tokens),F?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=F?.rejected_prediction_tokens),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const ne=V.choices[0];if(ne?.finish_reason!=null&&(l=l_(ne.finish_reason)),ne?.delta==null)return;const fe=ne.delta,de=(w=fe.reasoning_content)!=null?w:fe.reasoning;if(de&&(d||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),fe.content&&(f||(y.enqueue({type:"text-start",id:"txt-0"}),f=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:fe.content})),fe.tool_calls!=null)for(const te of fe.tool_calls){const ye=te.index;if(c[ye]==null){if(te.id==null)throw new qm({data:te,message:"Expected 'id' to be a string."});if(((g=te.function)==null?void 0:g.name)==null)throw new qm({data:te,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),c[ye]={id:te.id,type:"function",function:{name:te.function.name,arguments:(_=te.function.arguments)!=null?_:""},hasFinished:!1};const P=c[ye];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),i2(P.function.arguments)&&(y.enqueue({type:"tool-input-end",id:P.id}),y.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:po(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const H=c[ye];H.hasFinished||(((C=te.function)==null?void 0:C.arguments)!=null&&(H.function.arguments+=(R=(x=te.function)==null?void 0:x.arguments)!=null?R:""),y.enqueue({type:"tool-input-delta",id:H.id,delta:(j=te.function.arguments)!=null?j:""}),((O=H.function)==null?void 0:O.name)!=null&&((D=H.function)==null?void 0:D.arguments)!=null&&i2(H.function.arguments)&&(y.enqueue({type:"tool-input-end",id:H.id}),y.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:po(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(v){var y,w,g,_,b,k;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&v.enqueue({type:"text-end",id:"txt-0"});for(const C of c.filter(x=>!x.hasFinished))v.enqueue({type:"tool-input-end",id:C.id}),v.enqueue({type:"tool-call",toolCallId:(y=C.id)!=null?y:po(),toolName:C.function.name,input:C.function.arguments});const S={[h]:{},...o?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:l,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(g=u.completionTokens)!=null?g:void 0,totalTokens:(_=u.totalTokens)!=null?_:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:s},response:{headers:a}}}},u_=T({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:T({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish(),lR=T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({message:T({role:L("assistant").nullish(),content:m().nullish(),reasoning_content:m().nullish(),reasoning:m().nullish(),tool_calls:M(T({id:m().nullish(),function:T({name:m(),arguments:m()})})).nullish()}),finish_reason:m().nullish()})),usage:u_}),uR=t=>ie([T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({delta:T({role:xe(["assistant"]).nullish(),content:m().nullish(),reasoning_content:m().nullish(),reasoning:m().nullish(),tool_calls:M(T({index:N(),id:m().nullish(),function:T({name:m().nullish(),arguments:m().nullish()})})).nullish()}).nullish(),finish_reason:m().nullish()})),usage:u_}),t]);T({echo:me().optional(),logitBias:be(m(),N()).optional(),suffix:m().optional(),user:m().optional()});var dR=T({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()});T({id:m().nullish(),created:N().nullish(),model:m().nullish(),choices:M(T({text:m(),finish_reason:m()})),usage:dR.nullish()}),T({dimensions:N().optional(),user:m().optional()}),T({data:M(T({embedding:M(N())})),usage:T({prompt_tokens:N()}).nullish(),providerMetadata:be(m(),be(m(),ht())).optional()}),T({data:M(T({b64_json:m()}))});var d_=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},pR={extractMetadata:async({parsedBody:t})=>{const e=await er({value:t,schema:fR});return!e.success||e.value.usage==null?void 0:d_(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,n;const s=await er({value:e,schema:hR});s.success&&((n=(r=s.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&s.value.usage&&(t=s.value.usage)},buildMetadata:()=>d_(t)}}},p_=T({prompt_cache_hit_tokens:N().nullish(),prompt_cache_miss_tokens:N().nullish()}),fR=T({usage:p_.nullish()}),hR=T({choices:M(T({finish_reason:m().nullish()})).nullish(),usage:p_.nullish()}),mR="1.0.30";function f_(t={}){var e;const r=y2((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),n=()=>Kr({Authorization:`Bearer ${nC({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${mR}`);class s extends cR{addJsonInstruction(c){var l;if(((l=c.responseFormat)==null?void 0:l.type)!=="json")return c;const h=[...Array.isArray(c.prompt)?c.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...c,prompt:h}}async doGenerate(c){return super.doGenerate(this.addJsonInstruction(c))}async doStream(c){return super.doStream(this.addJsonInstruction(c))}}const o=i=>new s(i,{provider:"deepseek.chat",url:({path:c})=>`${r}${c}`,headers:n,fetch:t.fetch,metadataExtractor:pR}),a=i=>o(i);return a.languageModel=o,a.chat=o,a.textEmbeddingModel=i=>{throw new Wm({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Wm({modelId:i,modelType:"imageModel"})},a}f_();const h_=async t=>{const e={};try{const r=await t.listTools();for(const{name:n,description:s,inputSchema:o}of r.tools){const a=async(i,c)=>t.callTool({name:n,arguments:i},{signal:c?.abortSignal});e[n]=l2({description:s,inputSchema:ho({...o,properties:o.properties??{},additionalProperties:!1}),execute:a})}return e}catch(r){throw r}};function gR(t){const e=Object.entries(t);if(e.length===0)return"";let r=`
|
|
590
590
|
|
|
591
591
|
# 工具调用
|
|
592
592
|
|
|
@@ -620,10 +620,10 @@ ${e}:`]}}function Z1({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??vo
|
|
|
620
620
|
`,r+=`- 必须严格按照 XML 格式调用工具
|
|
621
621
|
`,r+=`- arguments 必须是有效的 JSON 格式
|
|
622
622
|
`,r+=`- 如果不需要调用工具,直接给出最终答案即可
|
|
623
|
-
`,r}function
|
|
624
|
-
${s}`}async _executeReActToolCall(e,r,n){const s=n[e];if(!s)return{success:!1,error:`工具 ${e} 不存在`};try{const o=s,a=o.execute||o.call;return typeof a!="function"?{success:!1,error:`工具 ${e} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(o){return{success:!1,error:o?.message||String(o)||"工具执行失败"}}}async _chatReAct(e,{model:r,maxSteps:n=5,...s}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o=this._tempMergeTools(s.tools);if(Object.keys(o).length===0)return this._chat(e,{model:r,maxSteps:n,...s});let i=[];s.message&&!s.messages?i.push({role:"user",content:s.message}):s.messages?i=[...s.messages]:i=[...this.messages];const c=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(o,c,s.system)},
|
|
625
|
-
${
|
|
626
|
-
</tool_response>`};c.push(
|
|
627
|
-
${
|
|
628
|
-
</tool_response>`;
|
|
629
|
-
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),
|
|
623
|
+
`,r}function m_(t,e){if(!t||typeof t!="string")return null;const r=t.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),s=JSON.parse(n),o=s.name||s.action||s.tool,a=s.arguments||s.args||s.input||{};if(o&&e[o])return{toolName:o,arguments:a}}catch{}return null}const yR={openai:i_,deepseek:f_};class _R{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.useReActMode=!1,!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const n=e.providerType;let s;typeof n=="string"?s=yR[n]:s=n,this.llm=s({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=e.useReActMode??!1}async _createOneClient(e){try{let r;if("type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new to(new URL(e.url)):"type"in e&&e.type==="extension"?r=new N0(e.sessionId):"transport"in e?r=e.transport:r=e,e.useAISdkClient??!1){const s=await m7({transport:r});return s.__transport__=r,s}else{const s=new O0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await s.connect(r),s.__transport__=r,s}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){try{const r=e.__transport__;if(r&&r instanceof ao||r&&r instanceof ro)return;await r?.terminateSession?.(),await r?.close?.(),await e?.close?.()}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([n,s])=>{const o=await this._createOneClient(s);return{serverName:n,client:o}}));this.mcpClients={},r.forEach(({serverName:n,client:s})=>{this.mcpClients[n]=s})}async _getClientTools(e,r){if(!e)return null;try{return typeof e.tools=="function"?await e.tools():await h_(e)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([n,s])=>{const o=await this._getClientTools(s,n);return{serverName:n,tools:o}}));this.mcpTools={},r.forEach(({serverName:n,tools:s})=>{const o=s&&typeof s=="object"?s:{};this.mcpTools[n]=o})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){if(this.mcpServers[e])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=n;const s=await this._getClientTools(n,e);return this.mcpTools[e]=s&&typeof s=="object"?s:{},this.mcpServers[e]=r,this.onUpdatedTools?.(),n}async removeMcpServer(e){if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[e];delete this.mcpTools[e],n&&Object.keys(n).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),this.onUpdatedTools?.()}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((n,s)=>({...n,...s}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(e,r,n){const s=gR(e);return n?`${n}${s}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
624
|
+
${s}`}async _executeReActToolCall(e,r,n){const s=n[e];if(!s)return{success:!1,error:`工具 ${e} 不存在`};try{const o=s,a=o.execute||o.call;return typeof a!="function"?{success:!1,error:`工具 ${e} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(o){return{success:!1,error:o?.message||String(o)||"工具执行失败"}}}async _chatReAct(e,{model:r,maxSteps:n=5,...s}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o=this._tempMergeTools(s.tools);if(Object.keys(o).length===0)return this._chat(e,{model:r,maxSteps:n,...s});let i=[];s.message&&!s.messages?i.push({role:"user",content:s.message}):s.messages?i=[...s.messages]:i=[...this.messages];const c=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(o,c,s.system)},p=i[0]?.role==="system"?i:[u,...i];return e===Gu?this._chatReActStream(p,o,c,n,s):this._chatReActNonStream(p,o,c,n,s)}_messageHasImage(e){return e&&Array.isArray(e)?e.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(e){if(!e||!e.content)return null;if(!Array.isArray(e.content))return e;const r=e.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...e,content:r}}_buildMessagesForModel(e,r,n=3){const s=[];e&&s.push(e);let o=0;const a=[];for(let i=r.length-1;i>=0;i--){const c=r[i];if(this._messageHasImage(c.content))if(o<n)a.unshift(c),o++;else{const u=this._removeImageFromMessage(c);u&&a.unshift(u)}else a.unshift(c)}return s.push(...a),s}async _chatReActNonStream(e,r,n,s,o){let a=[...e];const i=e[0]?.role==="system"?e[0]:null,c=i?e.slice(1):e;let l=0;const u=o.maxImages??3;for(;l<s;){l++;const h=this._buildMessagesForModel(i,c,u),{tools:d,...f}=o,y=(await fy({model:this.llm(n),messages:h,...f})).text,w={role:"assistant",content:y};c.push(w),a.push(w);const g=m_(y,r);if(!g)return this.messages=a,{text:y,response:{messages:a}};const _=await this._executeReActToolCall(g.toolName,g.arguments,r),S={role:"user",content:`<tool_response>
|
|
625
|
+
${_.success?JSON.stringify(_.result):`工具执行失败 - ${_.error}`}
|
|
626
|
+
</tool_response>`};c.push(S),a.push(S)}return this.messages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(e,r,n,s,o){const a=this,i=this.llm(n);let c,l;const u=new Promise((h,d)=>{c=h,l=d});return{fullStream:new ReadableStream({async start(h){let d=[...e];const f=e[0]?.role==="system"?e[0]:null,v=f?e.slice(1):[...e];let y=0,w="";const g=o.maxImages??3;try{for(;y<s;){y++;const _=a._buildMessagesForModel(f,v,g),{tools:b,...k}=o;delete k.system,delete k.onFinish;const S=await Gu({...k,model:i,messages:_});let C="";for await(const te of S.fullStream)te.type==="text-delta"?(C+=te.text||"",h.enqueue({type:"text-delta",text:te.text})):te.type==="text-start"?h.enqueue({type:"text-start"}):te.type==="text-end"||h.enqueue(te);w+=C;const x={role:"assistant",content:w};v.push(x),d.push(x);const R=m_(w,r);if(!R){h.enqueue({type:"text-end"}),h.close(),a.messages=d,c({messages:d});return}if(R.toolName==="computer"&&R.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.messages=d,c({messages:d});return}const j=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:j,toolName:R.toolName});const O=JSON.stringify(R.arguments,null,2);h.enqueue({type:"tool-input-delta",id:j,delta:O});const D=await a._executeReActToolCall(R.toolName,R.arguments,r);let U,V=D.result;if(D.success&&D.result&&typeof D.result=="object"&&D.result.screenshot){U=D.result.screenshot;const{screenshot:te,...ye}=D.result;V=ye}let ne="";D.success?V&&Array.isArray(V.content)&&V.content.length>0&&V.content[0].text?ne=V.content[0].text:ne=JSON.stringify(V):ne=`工具执行失败 - ${D.error}`;let fe=`<tool_response>
|
|
627
|
+
${ne}
|
|
628
|
+
</tool_response>`;U&&(fe+=`
|
|
629
|
+
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:j,result:fe});const de=U?{role:"user",content:[{type:"text",text:fe},{type:"image",image:U}]}:{role:"user",content:fe};v.push(de),d.push(de),w=""}h.enqueue({type:"text-end"}),h.close(),a.messages=d,c({messages:d})}catch(_){h.error(_),l(_)}}}),response:u}}async _chat(e,{model:r,maxSteps:n=5,...s}){if(this.useReActMode)return this._chatReAct(e,{model:r,maxSteps:n,...s});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o={model:this.llm(r),stopWhen:Hu(n),...s,tools:this._tempMergeTools(s.tools)};s.message&&!s.messages&&(this.messages.push({role:"user",content:s.message}),o.messages=[...this.messages]);const a=e(o);return a?.response?.then(i=>{this.messages.push(...i.messages)}),a}async chat(e){return this._chat(fy,e)}async chatStream(e){return this._chat(Gu,e)}}Oe.AgentModelProvider=_R,Oe.Ajv=Zp,Oe.AuthClientProvider=OS,Oe.ContentScriptServerTransport=o5,Oe.ExtensionClientTransport=N0,Oe.ExtensionPageServerTransport=s5,Oe.InMemoryTransport=ao,Oe.QrCode=gm,Oe.ResourceTemplate=ZS,Oe.UriTemplate=xr,Oe.WebMcpClient=O0,Oe.WebMcpServer=JS,Oe.completable=NS,Oe.createMessageChannelClientTransport=e5,Oe.createMessageChannelPairTransport=GS,Oe.createMessageChannelServerTransport=WS,Oe.createRemoter=j5,Oe.createSSEClientTransport=QS,Oe.createStreamableHTTPClientTransport=XS,Oe.getAISDKTools=h_,Oe.getDisplayName=BS,Oe.isMcpClient=n5,Oe.isMcpServer=YS,Oe.isMessageChannelClientTransport=r5,Oe.isMessageChannelServerTransport=KS,Oe.isSSEClientTransport=t5,Oe.isStreamableHTTPClientTransport=A0,Oe.z=ww,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"})}));
|