@opentiny/next-sdk 0.1.13 → 0.1.14-alpha.0

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.
Files changed (62) hide show
  1. package/agent/AgentModelProvider.ts +49 -20
  2. package/agent/type.ts +4 -4
  3. package/dist/McpSdk.d.ts +14 -0
  4. package/dist/WebAgent.d.ts +5 -0
  5. package/dist/WebMcp.d.ts +20 -0
  6. package/dist/WebMcpClient.d.ts +250 -1488
  7. package/dist/WebMcpServer.d.ts +190 -78
  8. package/dist/Zod.d.ts +1 -0
  9. package/dist/agent/AgentModelProvider.d.ts +6 -4
  10. package/dist/agent/type.d.ts +6 -2
  11. package/dist/agent/utils/getAISDKTools.d.ts +1 -0
  12. package/dist/index.d.ts +2 -1
  13. package/dist/index.es.dev.js +23743 -25868
  14. package/dist/index.es.js +24524 -24312
  15. package/dist/index.js +1789 -25
  16. package/dist/index.umd.dev.js +23845 -25970
  17. package/dist/index.umd.js +185 -129
  18. package/dist/{mcpsdk@1.20.1.dev.js → mcpsdk@1.23.0.dev.js} +13535 -14184
  19. package/dist/{mcpsdk@1.20.1.es.dev.js → mcpsdk@1.23.0.es.dev.js} +13563 -14212
  20. package/dist/mcpsdk@1.23.0.es.js +15584 -0
  21. package/dist/mcpsdk@1.23.0.js +43 -0
  22. package/dist/remoter/createRemoter.d.ts +9 -0
  23. package/dist/remoter/tooltips.d.ts +36 -0
  24. package/dist/script/utils.d.ts +1 -0
  25. package/dist/transport/ExtensionClientTransport.d.ts +3 -2
  26. package/dist/transport/ExtensionContentServerTransport.d.ts +3 -2
  27. package/dist/transport/ExtensionPageServerTransport.d.ts +3 -2
  28. package/dist/vite-build-tsc.d.ts +2 -0
  29. package/dist/vite.config.d.ts +2 -0
  30. package/dist/vite.config.mcpSdk.d.ts +2 -0
  31. package/dist/vite.config.webAgent.d.ts +2 -0
  32. package/dist/vite.config.webMcp.d.ts +2 -0
  33. package/dist/vite.config.webMcpFull.d.ts +2 -0
  34. package/dist/vite.config.zod.d.ts +2 -0
  35. package/dist/webagent.dev.js +18803 -18836
  36. package/dist/webagent.es.dev.js +17726 -17759
  37. package/dist/webagent.es.js +22571 -20829
  38. package/dist/webagent.js +172 -109
  39. package/dist/webmcp-full.dev.js +14463 -15009
  40. package/dist/webmcp-full.es.dev.js +14471 -15017
  41. package/dist/webmcp-full.es.js +13391 -12365
  42. package/dist/webmcp-full.js +43 -16
  43. package/package.json +3 -2
  44. package/remoter/createRemoter.ts +126 -71
  45. package/remoter/tooltips.ts +260 -0
  46. package/tsconfig.json +5 -3
  47. package/vite-build-tsc.ts +60 -0
  48. package/vite-env.d.ts +5 -0
  49. package/dist/WebMcpClient.js +0 -363
  50. package/dist/WebMcpServer.js +0 -283
  51. package/dist/agent/AgentModelProvider.js +0 -293
  52. package/dist/agent/type.js +0 -1
  53. package/dist/agent/utils/getAISDKTools.js +0 -36
  54. package/dist/mcpsdk@1.20.1.es.js +0 -14600
  55. package/dist/mcpsdk@1.20.1.js +0 -16
  56. package/dist/remoter/QrCode.js +0 -55
  57. package/dist/remoter/createRemoter.js +0 -743
  58. package/dist/transport/ExtensionClientTransport.js +0 -81
  59. package/dist/transport/ExtensionContentServerTransport.js +0 -128
  60. package/dist/transport/ExtensionPageServerTransport.js +0 -118
  61. package/dist/transport/messages.js +0 -51
  62. package/dist/utils/uuid.js +0 -10
package/dist/index.umd.js CHANGED
@@ -1,71 +1,125 @@
1
- (function(Ze,ss){typeof exports=="object"&&typeof module<"u"?ss(exports):typeof define=="function"&&define.amd?define(["exports"],ss):(Ze=typeof globalThis<"u"?globalThis:Ze||self,ss(Ze.WebMCP={}))})(this,function(Ze){"use strict";var ss=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $p(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ol={exports:{}},Pp={},Pr={},ga={},os={},Me={},is={};(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(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class a extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((w,b)=>`${w}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((w,b)=>(b instanceof r&&(w[b.str]=(w[b.str]||0)+1),w),{})}}t._Code=a,t.nil=new a("");function n(p,..._){const w=[p[0]];let b=0;for(;b<_.length;)i(w,_[b]),w.push(p[++b]);return new a(w)}t._=n;const s=new a("+");function o(p,..._){const w=[d(p[0])];let b=0;for(;b<_.length;)w.push(s),i(w,_[b]),w.push(s,d(p[++b]));return l(w),new a(w)}t.str=o;function i(p,_){_ instanceof a?p.push(..._._items):_ instanceof r?p.push(_):p.push(f(_))}t.addCodeArg=i;function l(p){let _=1;for(;_<p.length-1;){if(p[_]===s){const w=c(p[_-1],p[_+1]);if(w!==void 0){p.splice(_-1,3,w);continue}p[_++]="+"}_++}}function c(p,_){if(_==='""')return p;if(p==='""')return _;if(typeof p=="string")return _ instanceof r||p[p.length-1]!=='"'?void 0:typeof _!="string"?`${p.slice(0,-1)}${_}"`:_[0]==='"'?p.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(p instanceof r))return`"${p}${_.slice(1)}`}function u(p,_){return _.emptyStr()?p:p.emptyStr()?_:o`${p}${_}`}t.strConcat=u;function f(p){return typeof p=="number"||typeof p=="boolean"||p===null?p:d(Array.isArray(p)?p.join(","):p)}function g(p){return new a(d(p))}t.stringify=g;function d(p){return JSON.stringify(p).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function m(p){return typeof p=="string"&&t.IDENTIFIER.test(p)?new a(`.${p}`):n`[${p}]`}t.getProperty=m;function v(p){if(typeof p=="string"&&t.IDENTIFIER.test(p))return new a(`${p}`);throw new Error(`CodeGen: invalid export name: ${p}, use explicit $id name mapping`)}t.getEsmExportName=v;function h(p){return new a(p.toString())}t.regexpCode=h})(is);var Nl={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=is;class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var a;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(a||(t.UsedValueState=a={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class n{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,f;if(!((f=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||f===void 0)&&f.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}t.Scope=n;class s extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:f}){this.value=c,this.scopePath=(0,e._)`.${new e.Name(u)}[${f}]`}}t.ValueScopeName=s;const o=(0,e._)`\n`;class i extends n{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?o:e.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var f;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const g=this.toName(c),{prefix:d}=g,m=(f=u.key)!==null&&f!==void 0?f:u.ref;let v=this._values[d];if(v){const _=v.get(m);if(_)return _}else v=this._values[d]=new Map;v.set(m,g);const h=this._scope[d]||(this._scope[d]=[]),p=h.length;return h[p]=u.ref,g.setValue(u,{property:d,itemIndex:p}),g}getValue(c,u){const f=this._values[c];if(f)return f.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,e._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},u,f)}_reduceValues(c,u,f={},g){let d=e.nil;for(const m in c){const v=c[m];if(!v)continue;const h=f[m]=f[m]||new Map;v.forEach(p=>{if(h.has(p))return;h.set(p,a.Started);let _=u(p);if(_){const w=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${w} ${p} = ${_};${this.opts._n}`}else if(_=g==null?void 0:g(p))d=(0,e._)`${d}${_}${this.opts._n}`;else throw new r(p);h.set(p,a.Completed)})}return d}}t.ValueScope=i})(Nl),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=is,r=Nl;var a=is;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return a._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return a.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return a.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return a.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return a.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return a.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return a.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return a.Name}});var n=Nl;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return n.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 s{optimizeNodes(){return this}optimizeNames(y,P){return this}}class o extends s{constructor(y,P,j){super(),this.varKind=y,this.name=P,this.rhs=j}render({es5:y,_n:P}){const j=y?r.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${j} ${this.name}${Q};`+P}optimizeNames(y,P){if(y[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,y,P)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(y,P,j){super(),this.lhs=y,this.rhs=P,this.sideEffects=j}render({_n:y}){return`${this.lhs} = ${this.rhs};`+y}optimizeNames(y,P){if(!(this.lhs instanceof e.Name&&!y[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,y,P),this}get names(){const y=this.lhs instanceof e.Name?{}:{...this.lhs.names};return z(y,this.rhs)}}class l extends i{constructor(y,P,j,Q){super(y,j,Q),this.op=P}render({_n:y}){return`${this.lhs} ${this.op}= ${this.rhs};`+y}}class c extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`${this.label}:`+y}}class u extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`break${this.label?` ${this.label}`:""};`+y}}class f extends s{constructor(y){super(),this.error=y}render({_n:y}){return`throw ${this.error};`+y}get names(){return this.error.names}}class g extends s{constructor(y){super(),this.code=y}render({_n:y}){return`${this.code};`+y}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(y,P){return this.code=U(this.code,y,P),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends s{constructor(y=[]){super(),this.nodes=y}render(y){return this.nodes.reduce((P,j)=>P+j.render(y),"")}optimizeNodes(){const{nodes:y}=this;let P=y.length;for(;P--;){const j=y[P].optimizeNodes();Array.isArray(j)?y.splice(P,1,...j):j?y[P]=j:y.splice(P,1)}return y.length>0?this:void 0}optimizeNames(y,P){const{nodes:j}=this;let Q=j.length;for(;Q--;){const ee=j[Q];ee.optimizeNames(y,P)||(G(y,ee.names),j.splice(Q,1))}return j.length>0?this:void 0}get names(){return this.nodes.reduce((y,P)=>K(y,P.names),{})}}class m extends d{render(y){return"{"+y._n+super.render(y)+"}"+y._n}}class v extends d{}class h extends m{}h.kind="else";class p extends m{constructor(y,P){super(P),this.condition=y}render(y){let P=`if(${this.condition})`+super.render(y);return this.else&&(P+="else "+this.else.render(y)),P}optimizeNodes(){super.optimizeNodes();const y=this.condition;if(y===!0)return this.nodes;let P=this.else;if(P){const j=P.optimizeNodes();P=this.else=Array.isArray(j)?new h(j):j}if(P)return y===!1?P instanceof p?P:P.nodes:this.nodes.length?this:new p(se(y),P instanceof p?[P]:P.nodes);if(!(y===!1||!this.nodes.length))return this}optimizeNames(y,P){var j;if(this.else=(j=this.else)===null||j===void 0?void 0:j.optimizeNames(y,P),!!(super.optimizeNames(y,P)||this.else))return this.condition=U(this.condition,y,P),this}get names(){const y=super.names;return z(y,this.condition),this.else&&K(y,this.else.names),y}}p.kind="if";class _ extends m{}_.kind="for";class w extends _{constructor(y){super(),this.iteration=y}render(y){return`for(${this.iteration})`+super.render(y)}optimizeNames(y,P){if(super.optimizeNames(y,P))return this.iteration=U(this.iteration,y,P),this}get names(){return K(super.names,this.iteration.names)}}class b extends _{constructor(y,P,j,Q){super(),this.varKind=y,this.name=P,this.from=j,this.to=Q}render(y){const P=y.es5?r.varKinds.var:this.varKind,{name:j,from:Q,to:ee}=this;return`for(${P} ${j}=${Q}; ${j}<${ee}; ${j}++)`+super.render(y)}get names(){const y=z(super.names,this.from);return z(y,this.to)}}class S extends _{constructor(y,P,j,Q){super(),this.loop=y,this.varKind=P,this.name=j,this.iterable=Q}render(y){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(y)}optimizeNames(y,P){if(super.optimizeNames(y,P))return this.iterable=U(this.iterable,y,P),this}get names(){return K(super.names,this.iterable.names)}}class x extends m{constructor(y,P,j){super(),this.name=y,this.args=P,this.async=j}render(y){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(y)}}x.kind="func";class k extends d{render(y){return"return "+super.render(y)}}k.kind="return";class A extends m{render(y){let P="try"+super.render(y);return this.catch&&(P+=this.catch.render(y)),this.finally&&(P+=this.finally.render(y)),P}optimizeNodes(){var y,P;return super.optimizeNodes(),(y=this.catch)===null||y===void 0||y.optimizeNodes(),(P=this.finally)===null||P===void 0||P.optimizeNodes(),this}optimizeNames(y,P){var j,Q;return super.optimizeNames(y,P),(j=this.catch)===null||j===void 0||j.optimizeNames(y,P),(Q=this.finally)===null||Q===void 0||Q.optimizeNames(y,P),this}get names(){const y=super.names;return this.catch&&K(y,this.catch.names),this.finally&&K(y,this.finally.names),y}}class O extends m{constructor(y){super(),this.error=y}render(y){return`catch(${this.error})`+super.render(y)}}O.kind="catch";class H extends m{render(y){return"finally"+super.render(y)}}H.kind="finally";class J{constructor(y,P={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...P,_n:P.lines?`
2
- `:""},this._extScope=y,this._scope=new r.Scope({parent:y}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(y){return this._scope.name(y)}scopeName(y){return this._extScope.name(y)}scopeValue(y,P){const j=this._extScope.value(y,P);return(this._values[j.prefix]||(this._values[j.prefix]=new Set)).add(j),j}getScopeValue(y,P){return this._extScope.getValue(y,P)}scopeRefs(y){return this._extScope.scopeRefs(y,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(y,P,j,Q){const ee=this._scope.toName(P);return j!==void 0&&Q&&(this._constants[ee.str]=j),this._leafNode(new o(y,ee,j)),ee}const(y,P,j){return this._def(r.varKinds.const,y,P,j)}let(y,P,j){return this._def(r.varKinds.let,y,P,j)}var(y,P,j){return this._def(r.varKinds.var,y,P,j)}assign(y,P,j){return this._leafNode(new i(y,P,j))}add(y,P){return this._leafNode(new l(y,t.operators.ADD,P))}code(y){return typeof y=="function"?y():y!==e.nil&&this._leafNode(new g(y)),this}object(...y){const P=["{"];for(const[j,Q]of y)P.length>1&&P.push(","),P.push(j),(j!==Q||this.opts.es5)&&(P.push(":"),(0,e.addCodeArg)(P,Q));return P.push("}"),new e._Code(P)}if(y,P,j){if(this._blockNode(new p(y)),P&&j)this.code(P).else().code(j).endIf();else if(P)this.code(P).endIf();else if(j)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(y){return this._elseNode(new p(y))}else(){return this._elseNode(new h)}endIf(){return this._endBlockNode(p,h)}_for(y,P){return this._blockNode(y),P&&this.code(P).endFor(),this}for(y,P){return this._for(new w(y),P)}forRange(y,P,j,Q,ee=this.opts.es5?r.varKinds.var:r.varKinds.let){const Se=this._scope.toName(y);return this._for(new b(ee,Se,P,j),()=>Q(Se))}forOf(y,P,j,Q=r.varKinds.const){const ee=this._scope.toName(y);if(this.opts.es5){const Se=P instanceof e.Name?P:this.var("_arr",P);return this.forRange("_i",0,(0,e._)`${Se}.length`,de=>{this.var(ee,(0,e._)`${Se}[${de}]`),j(ee)})}return this._for(new S("of",Q,ee,P),()=>j(ee))}forIn(y,P,j,Q=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(y,(0,e._)`Object.keys(${P})`,j);const ee=this._scope.toName(y);return this._for(new S("in",Q,ee,P),()=>j(ee))}endFor(){return this._endBlockNode(_)}label(y){return this._leafNode(new c(y))}break(y){return this._leafNode(new u(y))}return(y){const P=new k;if(this._blockNode(P),this.code(y),P.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(y,P,j){if(!P&&!j)throw new Error('CodeGen: "try" without "catch" and "finally"');const Q=new A;if(this._blockNode(Q),this.code(y),P){const ee=this.name("e");this._currNode=Q.catch=new O(ee),P(ee)}return j&&(this._currNode=Q.finally=new H,this.code(j)),this._endBlockNode(O,H)}throw(y){return this._leafNode(new f(y))}block(y,P){return this._blockStarts.push(this._nodes.length),y&&this.code(y).endBlock(P),this}endBlock(y){const P=this._blockStarts.pop();if(P===void 0)throw new Error("CodeGen: not in self-balancing block");const j=this._nodes.length-P;if(j<0||y!==void 0&&j!==y)throw new Error(`CodeGen: wrong number of nodes: ${j} vs ${y} expected`);return this._nodes.length=P,this}func(y,P=e.nil,j,Q){return this._blockNode(new x(y,P,j)),Q&&this.code(Q).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize(y=1){for(;y-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(y){return this._currNode.nodes.push(y),this}_blockNode(y){this._currNode.nodes.push(y),this._nodes.push(y)}_endBlockNode(y,P){const j=this._currNode;if(j instanceof y||P&&j instanceof P)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${P?`${y.kind}/${P.kind}`:y.kind}"`)}_elseNode(y){const P=this._currNode;if(!(P instanceof p))throw new Error('CodeGen: "else" without "if"');return this._currNode=P.else=y,this}get _root(){return this._nodes[0]}get _currNode(){const y=this._nodes;return y[y.length-1]}set _currNode(y){const P=this._nodes;P[P.length-1]=y}}t.CodeGen=J;function K(N,y){for(const P in y)N[P]=(N[P]||0)+(y[P]||0);return N}function z(N,y){return y instanceof e._CodeOrName?K(N,y.names):N}function U(N,y,P){if(N instanceof e.Name)return j(N);if(!Q(N))return N;return new e._Code(N._items.reduce((ee,Se)=>(Se instanceof e.Name&&(Se=j(Se)),Se instanceof e._Code?ee.push(...Se._items):ee.push(Se),ee),[]));function j(ee){const Se=P[ee.str];return Se===void 0||y[ee.str]!==1?ee:(delete y[ee.str],Se)}function Q(ee){return ee instanceof e._Code&&ee._items.some(Se=>Se instanceof e.Name&&y[Se.str]===1&&P[Se.str]!==void 0)}}function G(N,y){for(const P in y)N[P]=(N[P]||0)-(y[P]||0)}function se(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,e._)`!${D(N)}`}t.not=se;const ne=R(t.operators.AND);function ce(...N){return N.reduce(ne)}t.and=ce;const pe=R(t.operators.OR);function M(...N){return N.reduce(pe)}t.or=M;function R(N){return(y,P)=>y===e.nil?P:P===e.nil?y:(0,e._)`${D(y)} ${N} ${D(P)}`}function D(N){return N instanceof e.Name?N:(0,e._)`(${N})`}}(Me);var ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.checkStrictMode=ie.getErrorPath=ie.Type=ie.useFunc=ie.setEvaluated=ie.evaluatedPropsToName=ie.mergeEvaluated=ie.eachItem=ie.unescapeJsonPointer=ie.escapeJsonPointer=ie.escapeFragment=ie.unescapeFragment=ie.schemaRefOrVal=ie.schemaHasRulesButRef=ie.schemaHasRules=ie.checkUnknownRules=ie.alwaysValidSchema=ie.toHash=void 0;const Ye=Me,iw=is;function lw(t){const e={};for(const r of t)e[r]=!0;return e}ie.toHash=lw;function cw(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kp(t,e),!xp(e,t.self.RULES.all))}ie.alwaysValidSchema=cw;function kp(t,e=t.schema){const{opts:r,self:a}=t;if(!r.strictSchema||typeof e=="boolean")return;const n=a.RULES.keywords;for(const s in e)n[s]||Op(t,`unknown keyword: "${s}"`)}ie.checkUnknownRules=kp;function xp(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}ie.schemaHasRules=xp;function uw(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ie.schemaHasRulesButRef=uw;function dw({topSchemaRef:t,schemaPath:e},r,a,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ye._)`${r}`}return(0,Ye._)`${t}${e}${(0,Ye.getProperty)(a)}`}ie.schemaRefOrVal=dw;function pw(t){return Ip(decodeURIComponent(t))}ie.unescapeFragment=pw;function fw(t){return encodeURIComponent(Al(t))}ie.escapeFragment=fw;function Al(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ie.escapeJsonPointer=Al;function Ip(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ie.unescapeJsonPointer=Ip;function hw(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}ie.eachItem=hw;function Tp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:a}){return(n,s,o,i)=>{const l=o===void 0?s:o instanceof Ye.Name?(s instanceof Ye.Name?t(n,s,o):e(n,s,o),o):s instanceof Ye.Name?(e(n,o,s),s):r(s,o);return i===Ye.Name&&!(l instanceof Ye.Name)?a(n,l):l}}ie.mergeEvaluated={props:Tp({mergeNames:(t,e,r)=>t.if((0,Ye._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ye._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ye._)`${r} || {}`).code((0,Ye._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ye._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ye._)`${r} || {}`),Ml(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Cp}),items:Tp({mergeNames:(t,e,r)=>t.if((0,Ye._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ye._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ye._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ye._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Cp(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,Ye._)`{}`);return e!==void 0&&Ml(t,r,e),r}ie.evaluatedPropsToName=Cp;function Ml(t,e,r){Object.keys(r).forEach(a=>t.assign((0,Ye._)`${e}${(0,Ye.getProperty)(a)}`,!0))}ie.setEvaluated=Ml;const Rp={};function mw(t,e){return t.scopeValue("func",{ref:e,code:Rp[e.code]||(Rp[e.code]=new iw._Code(e.code))})}ie.useFunc=mw;var jl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(jl||(ie.Type=jl={}));function vw(t,e,r){if(t instanceof Ye.Name){const a=e===jl.Num;return r?a?(0,Ye._)`"[" + ${t} + "]"`:(0,Ye._)`"['" + ${t} + "']"`:a?(0,Ye._)`"/" + ${t}`:(0,Ye._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ye.getProperty)(t).toString():"/"+Al(t)}ie.getErrorPath=vw;function Op(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ie.checkStrictMode=Op;var Fr={};Object.defineProperty(Fr,"__esModule",{value:!0});const qt=Me,gw={data:new qt.Name("data"),valCxt:new qt.Name("valCxt"),instancePath:new qt.Name("instancePath"),parentData:new qt.Name("parentData"),parentDataProperty:new qt.Name("parentDataProperty"),rootData:new qt.Name("rootData"),dynamicAnchors:new qt.Name("dynamicAnchors"),vErrors:new qt.Name("vErrors"),errors:new qt.Name("errors"),this:new qt.Name("this"),self:new qt.Name("self"),scope:new qt.Name("scope"),json:new qt.Name("json"),jsonPos:new qt.Name("jsonPos"),jsonLen:new qt.Name("jsonLen"),jsonPart:new qt.Name("jsonPart")};Fr.default=gw,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=Me,r=ie,a=Fr;t.keywordError={message:({keyword:h})=>(0,e.str)`must pass "${h}" keyword validation`},t.keyword$DataError={message:({keyword:h,schemaType:p})=>p?(0,e.str)`"${h}" keyword must be ${p} ($data)`:(0,e.str)`"${h}" keyword is invalid ($data)`};function n(h,p=t.keywordError,_,w){const{it:b}=h,{gen:S,compositeRule:x,allErrors:k}=b,A=f(h,p,_);w??(x||k)?l(S,A):c(b,(0,e._)`[${A}]`)}t.reportError=n;function s(h,p=t.keywordError,_){const{it:w}=h,{gen:b,compositeRule:S,allErrors:x}=w,k=f(h,p,_);l(b,k),S||x||c(w,a.default.vErrors)}t.reportExtraError=s;function o(h,p){h.assign(a.default.errors,p),h.if((0,e._)`${a.default.vErrors} !== null`,()=>h.if(p,()=>h.assign((0,e._)`${a.default.vErrors}.length`,p),()=>h.assign(a.default.vErrors,null)))}t.resetErrorsCount=o;function i({gen:h,keyword:p,schemaValue:_,data:w,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");const x=h.name("err");h.forRange("i",b,a.default.errors,k=>{h.const(x,(0,e._)`${a.default.vErrors}[${k}]`),h.if((0,e._)`${x}.instancePath === undefined`,()=>h.assign((0,e._)`${x}.instancePath`,(0,e.strConcat)(a.default.instancePath,S.errorPath))),h.assign((0,e._)`${x}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${p}`),S.opts.verbose&&(h.assign((0,e._)`${x}.schema`,_),h.assign((0,e._)`${x}.data`,w))})}t.extendErrors=i;function l(h,p){const _=h.const("err",p);h.if((0,e._)`${a.default.vErrors} === null`,()=>h.assign(a.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${a.default.vErrors}.push(${_})`),h.code((0,e._)`${a.default.errors}++`)}function c(h,p){const{gen:_,validateName:w,schemaEnv:b}=h;b.$async?_.throw((0,e._)`new ${h.ValidationError}(${p})`):(_.assign((0,e._)`${w}.errors`,p),_.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 f(h,p,_){const{createErrors:w}=h.it;return w===!1?(0,e._)`{}`:g(h,p,_)}function g(h,p,_={}){const{gen:w,it:b}=h,S=[d(b,_),m(h,_)];return v(h,p,S),w.object(...S)}function d({errorPath:h},{instancePath:p}){const _=p?(0,e.str)`${h}${(0,r.getErrorPath)(p,r.Type.Str)}`:h;return[a.default.instancePath,(0,e.strConcat)(a.default.instancePath,_)]}function m({keyword:h,it:{errSchemaPath:p}},{schemaPath:_,parentSchema:w}){let b=w?p:(0,e.str)`${p}/${h}`;return _&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function v(h,{params:p,message:_},w){const{keyword:b,data:S,schemaValue:x,it:k}=h,{opts:A,propertyName:O,topSchemaRef:H,schemaPath:J}=k;w.push([u.keyword,b],[u.params,typeof p=="function"?p(h):p||(0,e._)`{}`]),A.messages&&w.push([u.message,typeof _=="function"?_(h):_]),A.verbose&&w.push([u.schema,x],[u.parentSchema,(0,e._)`${H}${J}`],[a.default.data,S]),O&&w.push([u.propertyName,O])}}(os),Object.defineProperty(ga,"__esModule",{value:!0}),ga.boolOrEmptySchema=ga.topBoolOrEmptySchema=void 0;const yw=os,_w=Me,ww=Fr,bw={message:"boolean schema is false"};function Ew(t){const{gen:e,schema:r,validateName:a}=t;r===!1?Np(t,!1):typeof r=="object"&&r.$async===!0?e.return(ww.default.data):(e.assign((0,_w._)`${a}.errors`,null),e.return(!0))}ga.topBoolOrEmptySchema=Ew;function Sw(t,e){const{gen:r,schema:a}=t;a===!1?(r.var(e,!1),Np(t)):r.var(e,!0)}ga.boolOrEmptySchema=Sw;function Np(t,e){const{gen:r,data:a}=t,n={gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,yw.reportError)(n,bw,void 0,e)}var Tt={},qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.getRules=qn.isJSONType=void 0;const $w=["string","number","integer","boolean","null","object","array"],Pw=new Set($w);function kw(t){return typeof t=="string"&&Pw.has(t)}qn.isJSONType=kw;function xw(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}qn.getRules=xw;var un={};Object.defineProperty(un,"__esModule",{value:!0}),un.shouldUseRule=un.shouldUseGroup=un.schemaHasRulesForType=void 0;function Iw({schema:t,self:e},r){const a=e.RULES.types[r];return a&&a!==!0&&Ap(t,a)}un.schemaHasRulesForType=Iw;function Ap(t,e){return e.rules.some(r=>Mp(t,r))}un.shouldUseGroup=Ap;function Mp(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(a=>t[a]!==void 0))}un.shouldUseRule=Mp,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.reportTypeError=Tt.checkDataTypes=Tt.checkDataType=Tt.coerceAndCheckDataType=Tt.getJSONTypes=Tt.getSchemaTypes=Tt.DataType=void 0;const Tw=qn,Cw=un,Rw=os,Re=Me,jp=ie;var ya;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ya||(Tt.DataType=ya={}));function Ow(t){const e=Dp(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Tt.getSchemaTypes=Ow;function Dp(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(Tw.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Tt.getJSONTypes=Dp;function Nw(t,e){const{gen:r,data:a,opts:n}=t,s=Aw(e,n.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Cw.schemaHasRulesForType)(t,e[0]));if(o){const i=Ll(e,a,n.strictNumbers,ya.Wrong);r.if(i,()=>{s.length?Mw(t,e,s):zl(t)})}return o}Tt.coerceAndCheckDataType=Nw;const Lp=new Set(["string","number","integer","boolean","null"]);function Aw(t,e){return e?t.filter(r=>Lp.has(r)||e==="array"&&r==="array"):[]}function Mw(t,e,r){const{gen:a,data:n,opts:s}=t,o=a.let("dataType",(0,Re._)`typeof ${n}`),i=a.let("coerced",(0,Re._)`undefined`);s.coerceTypes==="array"&&a.if((0,Re._)`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>a.assign(n,(0,Re._)`${n}[0]`).assign(o,(0,Re._)`typeof ${n}`).if(Ll(e,n,s.strictNumbers),()=>a.assign(i,n))),a.if((0,Re._)`${i} !== undefined`);for(const c of r)(Lp.has(c)||c==="array"&&s.coerceTypes==="array")&&l(c);a.else(),zl(t),a.endIf(),a.if((0,Re._)`${i} !== undefined`,()=>{a.assign(n,i),jw(t,i)});function l(c){switch(c){case"string":a.elseIf((0,Re._)`${o} == "number" || ${o} == "boolean"`).assign(i,(0,Re._)`"" + ${n}`).elseIf((0,Re._)`${n} === null`).assign(i,(0,Re._)`""`);return;case"number":a.elseIf((0,Re._)`${o} == "boolean" || ${n} === null
3
- || (${o} == "string" && ${n} && ${n} == +${n})`).assign(i,(0,Re._)`+${n}`);return;case"integer":a.elseIf((0,Re._)`${o} === "boolean" || ${n} === null
4
- || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,(0,Re._)`+${n}`);return;case"boolean":a.elseIf((0,Re._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf((0,Re._)`${n} === "true" || ${n} === 1`).assign(i,!0);return;case"null":a.elseIf((0,Re._)`${n} === "" || ${n} === 0 || ${n} === false`),a.assign(i,null);return;case"array":a.elseIf((0,Re._)`${o} === "string" || ${o} === "number"
5
- || ${o} === "boolean" || ${n} === null`).assign(i,(0,Re._)`[${n}]`)}}}function jw({gen:t,parentData:e,parentDataProperty:r},a){t.if((0,Re._)`${e} !== undefined`,()=>t.assign((0,Re._)`${e}[${r}]`,a))}function Dl(t,e,r,a=ya.Correct){const n=a===ya.Correct?Re.operators.EQ:Re.operators.NEQ;let s;switch(t){case"null":return(0,Re._)`${e} ${n} null`;case"array":s=(0,Re._)`Array.isArray(${e})`;break;case"object":s=(0,Re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,Re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,Re._)`typeof ${e} ${n} ${t}`}return a===ya.Correct?s:(0,Re.not)(s);function o(i=Re.nil){return(0,Re.and)((0,Re._)`typeof ${e} == "number"`,i,r?(0,Re._)`isFinite(${e})`:Re.nil)}}Tt.checkDataType=Dl;function Ll(t,e,r,a){if(t.length===1)return Dl(t[0],e,r,a);let n;const s=(0,jp.toHash)(t);if(s.array&&s.object){const o=(0,Re._)`typeof ${e} != "object"`;n=s.null?o:(0,Re._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else n=Re.nil;s.number&&delete s.integer;for(const o in s)n=(0,Re.and)(n,Dl(o,e,r,a));return n}Tt.checkDataTypes=Ll;const Dw={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Re._)`{type: ${t}}`:(0,Re._)`{type: ${e}}`};function zl(t){const e=Lw(t);(0,Rw.reportError)(e,Dw)}Tt.reportTypeError=zl;function Lw(t){const{gen:e,data:r,schema:a}=t,n=(0,jp.schemaRefOrVal)(t,a,"type");return{gen:e,keyword:"type",data:r,schema:a.type,schemaCode:n,schemaValue:n,parentSchema:a,params:{},it:t}}var Oo={};Object.defineProperty(Oo,"__esModule",{value:!0}),Oo.assignDefaults=void 0;const _a=Me,zw=ie;function Uw(t,e){const{properties:r,items:a}=t.schema;if(e==="object"&&r)for(const n in r)zp(t,n,r[n].default);else e==="array"&&Array.isArray(a)&&a.forEach((n,s)=>zp(t,s,n.default))}Oo.assignDefaults=Uw;function zp(t,e,r){const{gen:a,compositeRule:n,data:s,opts:o}=t;if(r===void 0)return;const i=(0,_a._)`${s}${(0,_a.getProperty)(e)}`;if(n){(0,zw.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,_a._)`${i} === undefined`;o.useDefaults==="empty"&&(l=(0,_a._)`${l} || ${i} === null || ${i} === ""`),a.if(l,(0,_a._)`${i} = ${(0,_a.stringify)(r)}`)}var Zr={},je={};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 at=Me,Ul=ie,bn=Fr,qw=ie;function Fw(t,e){const{gen:r,data:a,it:n}=t;r.if(Fl(r,a,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,at._)`${e}`},!0),t.error()})}je.checkReportMissingProp=Fw;function Zw({gen:t,data:e,it:{opts:r}},a,n){return(0,at.or)(...a.map(s=>(0,at.and)(Fl(t,e,s,r.ownProperties),(0,at._)`${n} = ${s}`)))}je.checkMissingProp=Zw;function Vw(t,e){t.setParams({missingProperty:e},!0),t.error()}je.reportMissingProp=Vw;function Up(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,at._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=Up;function ql(t,e,r){return(0,at._)`${Up(t)}.call(${e}, ${r})`}je.isOwnProperty=ql;function Hw(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} !== undefined`;return a?(0,at._)`${n} && ${ql(t,e,r)}`:n}je.propertyInData=Hw;function Fl(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} === undefined`;return a?(0,at.or)(n,(0,at.not)(ql(t,e,r))):n}je.noPropertyInData=Fl;function qp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}je.allSchemaProperties=qp;function Bw(t,e){return qp(e).filter(r=>!(0,Ul.alwaysValidSchema)(t,e[r]))}je.schemaProperties=Bw;function Jw({schemaCode:t,data:e,it:{gen:r,topSchemaRef:a,schemaPath:n,errorPath:s},it:o},i,l,c){const u=c?(0,at._)`${t}, ${e}, ${a}${n}`:e,f=[[bn.default.instancePath,(0,at.strConcat)(bn.default.instancePath,s)],[bn.default.parentData,o.parentData],[bn.default.parentDataProperty,o.parentDataProperty],[bn.default.rootData,bn.default.rootData]];o.opts.dynamicRef&&f.push([bn.default.dynamicAnchors,bn.default.dynamicAnchors]);const g=(0,at._)`${u}, ${r.object(...f)}`;return l!==at.nil?(0,at._)`${i}.call(${l}, ${g})`:(0,at._)`${i}(${g})`}je.callValidateCode=Jw;const Gw=(0,at._)`new RegExp`;function Kw({gen:t,it:{opts:e}},r){const a=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,a);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,at._)`${n.code==="new RegExp"?Gw:(0,qw.useFunc)(t,n)}(${r}, ${a})`})}je.usePattern=Kw;function Ww(t){const{gen:e,data:r,keyword:a,it:n}=t,s=e.name("valid");if(n.allErrors){const i=e.let("valid",!0);return o(()=>e.assign(i,!1)),i}return e.var(s,!0),o(()=>e.break()),s;function o(i){const l=e.const("len",(0,at._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:a,dataProp:c,dataPropType:Ul.Type.Num},s),e.if((0,at.not)(s),i)})}}je.validateArray=Ww;function Qw(t){const{gen:e,schema:r,keyword:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Ul.alwaysValidSchema)(n,l))&&!n.opts.unevaluated)return;const o=e.let("valid",!1),i=e.name("_valid");e.block(()=>r.forEach((l,c)=>{const u=t.subschema({keyword:a,schemaProp:c,compositeRule:!0},i);e.assign(o,(0,at._)`${o} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,at.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}je.validateUnion=Qw,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.validateKeywordUsage=Zr.validSchemaType=Zr.funcKeywordCode=Zr.macroKeywordCode=void 0;const Ht=Me,Fn=Fr,Yw=je,Xw=os;function eb(t,e){const{gen:r,keyword:a,schema:n,parentSchema:s,it:o}=t,i=e.macro.call(o.self,n,s,o),l=Zp(r,a,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);const c=r.name("valid");t.subschema({schema:i,schemaPath:Ht.nil,errSchemaPath:`${o.errSchemaPath}/${a}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Zr.macroKeywordCode=eb;function tb(t,e){var r;const{gen:a,keyword:n,schema:s,parentSchema:o,$data:i,it:l}=t;nb(l,e);const c=!i&&e.compile?e.compile.call(l.self,s,o,l):e.validate,u=Zp(a,n,c),f=a.let("valid");t.block$data(f,g),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function g(){if(e.errors===!1)v(),e.modifying&&Fp(t),h(()=>t.error());else{const p=e.async?d():m();e.modifying&&Fp(t),h(()=>rb(t,p))}}function d(){const p=a.let("ruleErrs",null);return a.try(()=>v((0,Ht._)`await `),_=>a.assign(f,!1).if((0,Ht._)`${_} instanceof ${l.ValidationError}`,()=>a.assign(p,(0,Ht._)`${_}.errors`),()=>a.throw(_))),p}function m(){const p=(0,Ht._)`${u}.errors`;return a.assign(p,null),v(Ht.nil),p}function v(p=e.async?(0,Ht._)`await `:Ht.nil){const _=l.opts.passContext?Fn.default.this:Fn.default.self,w=!("compile"in e&&!i||e.schema===!1);a.assign(f,(0,Ht._)`${p}${(0,Yw.callValidateCode)(t,u,_,w)}`,e.modifying)}function h(p){var _;a.if((0,Ht.not)((_=e.valid)!==null&&_!==void 0?_:f),p)}}Zr.funcKeywordCode=tb;function Fp(t){const{gen:e,data:r,it:a}=t;e.if(a.parentData,()=>e.assign(r,(0,Ht._)`${a.parentData}[${a.parentDataProperty}]`))}function rb(t,e){const{gen:r}=t;r.if((0,Ht._)`Array.isArray(${e})`,()=>{r.assign(Fn.default.vErrors,(0,Ht._)`${Fn.default.vErrors} === null ? ${e} : ${Fn.default.vErrors}.concat(${e})`).assign(Fn.default.errors,(0,Ht._)`${Fn.default.vErrors}.length`),(0,Xw.extendErrors)(t)},()=>t.error())}function nb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Zp(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ht.stringify)(r)})}function ab(t,e,r=!1){return!e.length||e.some(a=>a==="array"?Array.isArray(t):a==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==a||r&&typeof t>"u")}Zr.validSchemaType=ab;function sb({schema:t,opts:e,self:r,errSchemaPath:a},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");const o=n.dependencies;if(o!=null&&o.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){const l=`keyword "${s}" value is invalid at path "${a}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Zr.validateKeywordUsage=sb;var En={};Object.defineProperty(En,"__esModule",{value:!0}),En.extendSubschemaMode=En.extendSubschemaData=En.getSubschema=void 0;const Vr=Me,Vp=ie;function ob(t,{keyword:e,schemaProp:r,schema:a,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&a!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const i=t.schema[e];return r===void 0?{schema:i,schemaPath:(0,Vr._)`${t.schemaPath}${(0,Vr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,Vr._)`${t.schemaPath}${(0,Vr.getProperty)(e)}${(0,Vr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Vp.escapeFragment)(r)}`}}if(a!==void 0){if(n===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}En.getSubschema=ob;function ib(t,e,{dataProp:r,dataPropType:a,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:i}=e;if(r!==void 0){const{errorPath:c,dataPathArr:u,opts:f}=e,g=i.let("data",(0,Vr._)`${e.data}${(0,Vr.getProperty)(r)}`,!0);l(g),t.errorPath=(0,Vr.str)`${c}${(0,Vp.getErrorPath)(r,a,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Vr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(n!==void 0){const c=n instanceof Vr.Name?n:i.let("data",n,!0);l(c),o!==void 0&&(t.propertyName=o)}s&&(t.dataTypes=s);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}En.extendSubschemaData=ib;function lb(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:a,createErrors:n,allErrors:s}){a!==void 0&&(t.compositeRule=a),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}En.extendSubschemaMode=lb;var Dt={},ls=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 a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))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(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},Hp={exports:{}},Sn=Hp.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};No(e,a,n,t,"",t)};Sn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Sn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Sn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Sn.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 No(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var f=a[u];if(Array.isArray(f)){if(u in Sn.arrayKeywords)for(var g=0;g<f.length;g++)No(t,e,r,f[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in Sn.propsKeywords){if(f&&typeof f=="object")for(var d in f)No(t,e,r,f[d],n+"/"+u+"/"+cb(d),s,n,u,a,d)}else(u in Sn.keywords||t.allKeys&&!(u in Sn.skipKeywords))&&No(t,e,r,f,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function cb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var ub=Hp.exports;Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;const db=ie,pb=ls,fb=ub,hb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function mb(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Zl(t):e?Bp(t)<=e:!1}Dt.inlineRef=mb;const vb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Zl(t){for(const e in t){if(vb.has(e))return!0;const r=t[e];if(Array.isArray(r)&&r.some(Zl)||typeof r=="object"&&Zl(r))return!0}return!1}function Bp(t){let e=0;for(const r in t){if(r==="$ref")return 1/0;if(e++,!hb.has(r)&&(typeof t[r]=="object"&&(0,db.eachItem)(t[r],a=>e+=Bp(a)),e===1/0))return 1/0}return e}function Jp(t,e="",r){r!==!1&&(e=wa(e));const a=t.parse(e);return Gp(t,a)}Dt.getFullPath=Jp;function Gp(t,e){return t.serialize(e).split("#")[0]+"#"}Dt._getFullPath=Gp;const gb=/#\/?$/;function wa(t){return t?t.replace(gb,""):""}Dt.normalizeId=wa;function yb(t,e,r){return r=wa(r),t.resolve(e,r)}Dt.resolveUrl=yb;const _b=/^[a-z_][-a-z0-9._]*$/i;function wb(t,e){if(typeof t=="boolean")return{};const{schemaId:r,uriResolver:a}=this.opts,n=wa(t[r]||e),s={"":n},o=Jp(a,n,!1),i={},l=new Set;return fb(t,{allKeys:!0},(f,g,d,m)=>{if(m===void 0)return;const v=o+g;let h=s[m];typeof f[r]=="string"&&(h=p.call(this,f[r])),_.call(this,f.$anchor),_.call(this,f.$dynamicAnchor),s[g]=h;function p(w){const b=this.opts.uriResolver.resolve;if(w=wa(h?b(h,w):w),l.has(w))throw u(w);l.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?c(f,S.schema,w):w!==wa(v)&&(w[0]==="#"?(c(f,i[w],w),i[w]=f):this.refs[w]=v),w}function _(w){if(typeof w=="string"){if(!_b.test(w))throw new Error(`invalid anchor "${w}"`);p.call(this,`#${w}`)}}}),i;function c(f,g,d){if(g!==void 0&&!pb(f,g))throw u(d)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Dt.getSchemaRefs=wb,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.getData=Pr.KeywordCxt=Pr.validateFunctionCode=void 0;const Kp=ga,Wp=Tt,Vl=un,Ao=Tt,bb=Oo,cs=Zr,Hl=En,ve=Me,$e=Fr,Eb=Dt,dn=ie,us=os;function Sb(t){if(ef(t)&&(tf(t),Xp(t))){kb(t);return}Qp(t,()=>(0,Kp.topBoolOrEmptySchema)(t))}Pr.validateFunctionCode=Sb;function Qp({gen:t,validateName:e,schema:r,schemaEnv:a,opts:n},s){n.code.es5?t.func(e,(0,ve._)`${$e.default.data}, ${$e.default.valCxt}`,a.$async,()=>{t.code((0,ve._)`"use strict"; ${Yp(r,n)}`),Pb(t,n),t.code(s)}):t.func(e,(0,ve._)`${$e.default.data}, ${$b(n)}`,a.$async,()=>t.code(Yp(r,n)).code(s))}function $b(t){return(0,ve._)`{${$e.default.instancePath}="", ${$e.default.parentData}, ${$e.default.parentDataProperty}, ${$e.default.rootData}=${$e.default.data}${t.dynamicRef?(0,ve._)`, ${$e.default.dynamicAnchors}={}`:ve.nil}}={}`}function Pb(t,e){t.if($e.default.valCxt,()=>{t.var($e.default.instancePath,(0,ve._)`${$e.default.valCxt}.${$e.default.instancePath}`),t.var($e.default.parentData,(0,ve._)`${$e.default.valCxt}.${$e.default.parentData}`),t.var($e.default.parentDataProperty,(0,ve._)`${$e.default.valCxt}.${$e.default.parentDataProperty}`),t.var($e.default.rootData,(0,ve._)`${$e.default.valCxt}.${$e.default.rootData}`),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ve._)`${$e.default.valCxt}.${$e.default.dynamicAnchors}`)},()=>{t.var($e.default.instancePath,(0,ve._)`""`),t.var($e.default.parentData,(0,ve._)`undefined`),t.var($e.default.parentDataProperty,(0,ve._)`undefined`),t.var($e.default.rootData,$e.default.data),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ve._)`{}`)})}function kb(t){const{schema:e,opts:r,gen:a}=t;Qp(t,()=>{r.$comment&&e.$comment&&nf(t),Rb(t),a.let($e.default.vErrors,null),a.let($e.default.errors,0),r.unevaluated&&xb(t),rf(t),Ab(t)})}function xb(t){const{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ve._)`${r}.evaluated`),e.if((0,ve._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ve._)`${t.evaluated}.props`,(0,ve._)`undefined`)),e.if((0,ve._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ve._)`${t.evaluated}.items`,(0,ve._)`undefined`))}function Yp(t,e){const r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ve._)`/*# sourceURL=${r} */`:ve.nil}function Ib(t,e){if(ef(t)&&(tf(t),Xp(t))){Tb(t,e);return}(0,Kp.boolOrEmptySchema)(t,e)}function Xp({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const r in t)if(e.RULES.all[r])return!0;return!1}function ef(t){return typeof t.schema!="boolean"}function Tb(t,e){const{schema:r,gen:a,opts:n}=t;n.$comment&&r.$comment&&nf(t),Ob(t),Nb(t);const s=a.const("_errs",$e.default.errors);rf(t,s),a.var(e,(0,ve._)`${s} === ${$e.default.errors}`)}function tf(t){(0,dn.checkUnknownRules)(t),Cb(t)}function rf(t,e){if(t.opts.jtd)return af(t,[],!1,e);const r=(0,Wp.getSchemaTypes)(t.schema),a=(0,Wp.coerceAndCheckDataType)(t,r);af(t,r,!a,e)}function Cb(t){const{schema:e,errSchemaPath:r,opts:a,self:n}=t;e.$ref&&a.ignoreKeywordsWithRef&&(0,dn.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Rb(t){const{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,dn.checkStrictMode)(t,"default is ignored in the schema root")}function Ob(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Eb.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Nb(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function nf({gen:t,schemaEnv:e,schema:r,errSchemaPath:a,opts:n}){const s=r.$comment;if(n.$comment===!0)t.code((0,ve._)`${$e.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){const o=(0,ve.str)`${a}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,ve._)`${$e.default.self}.opts.$comment(${s}, ${o}, ${i}.schema)`)}}function Ab(t){const{gen:e,schemaEnv:r,validateName:a,ValidationError:n,opts:s}=t;r.$async?e.if((0,ve._)`${$e.default.errors} === 0`,()=>e.return($e.default.data),()=>e.throw((0,ve._)`new ${n}(${$e.default.vErrors})`)):(e.assign((0,ve._)`${a}.errors`,$e.default.vErrors),s.unevaluated&&Mb(t),e.return((0,ve._)`${$e.default.errors} === 0`))}function Mb({gen:t,evaluated:e,props:r,items:a}){r instanceof ve.Name&&t.assign((0,ve._)`${e}.props`,r),a instanceof ve.Name&&t.assign((0,ve._)`${e}.items`,a)}function af(t,e,r,a){const{gen:n,schema:s,data:o,allErrors:i,opts:l,self:c}=t,{RULES:u}=c;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,dn.schemaHasRulesButRef)(s,u))){n.block(()=>cf(t,"$ref",u.all.$ref.definition));return}l.jtd||jb(t,e),n.block(()=>{for(const g of u.rules)f(g);f(u.post)});function f(g){(0,Vl.shouldUseGroup)(s,g)&&(g.type?(n.if((0,Ao.checkDataType)(g.type,o,l.strictNumbers)),sf(t,g),e.length===1&&e[0]===g.type&&r&&(n.else(),(0,Ao.reportTypeError)(t)),n.endIf()):sf(t,g),i||n.if((0,ve._)`${$e.default.errors} === ${a||0}`))}}function sf(t,e){const{gen:r,schema:a,opts:{useDefaults:n}}=t;n&&(0,bb.assignDefaults)(t,e.type),r.block(()=>{for(const s of e.rules)(0,Vl.shouldUseRule)(a,s)&&cf(t,s.keyword,s.definition,e.type)})}function jb(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Db(t,e),t.opts.allowUnionTypes||Lb(t,e),zb(t,t.dataTypes))}function Db(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{of(t.dataTypes,r)||Bl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),qb(t,e)}}function Lb(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Bl(t,"use allowUnionTypes to allow union type keyword")}function zb(t,e){const r=t.self.RULES.all;for(const a in r){const n=r[a];if(typeof n=="object"&&(0,Vl.shouldUseRule)(t.schema,n)){const{type:s}=n.definition;s.length&&!s.some(o=>Ub(e,o))&&Bl(t,`missing type "${s.join(",")}" for keyword "${a}"`)}}}function Ub(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function of(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function qb(t,e){const r=[];for(const a of t.dataTypes)of(e,a)?r.push(a):e.includes("integer")&&a==="number"&&r.push("integer");t.dataTypes=r}function Bl(t,e){const r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,dn.checkStrictMode)(t,e,t.opts.strictTypes)}class lf{constructor(e,r,a){if((0,cs.validateKeywordUsage)(e,r,a),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=a,this.data=e.data,this.schema=e.schema[a],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,dn.schemaRefOrVal)(e,this.schema,a,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",uf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,cs.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${a} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",$e.default.errors))}result(e,r,a){this.failResult((0,ve.not)(e),r,a)}failResult(e,r,a){this.gen.if(e),a?a():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ve.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:r}=this;this.fail((0,ve._)`${r} !== undefined && (${(0,ve.or)(this.invalid$data(),e)})`)}error(e,r,a){if(r){this.setParams(r),this._error(e,a),this.setParams({});return}this._error(e,a)}_error(e,r){(e?us.reportExtraError:us.reportError)(this,this.def.error,r)}$dataError(){(0,us.reportError)(this,this.def.$dataError||us.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,us.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,a=ve.nil){this.gen.block(()=>{this.check$data(e,a),r()})}check$data(e=ve.nil,r=ve.nil){if(!this.$data)return;const{gen:a,schemaCode:n,schemaType:s,def:o}=this;a.if((0,ve.or)((0,ve._)`${n} === undefined`,r)),e!==ve.nil&&a.assign(e,!0),(s.length||o.validateSchema)&&(a.elseIf(this.invalid$data()),this.$dataError(),e!==ve.nil&&a.assign(e,!1)),a.else()}invalid$data(){const{gen:e,schemaCode:r,schemaType:a,def:n,it:s}=this;return(0,ve.or)(o(),i());function o(){if(a.length){if(!(r instanceof ve.Name))throw new Error("ajv implementation error");const l=Array.isArray(a)?a:[a];return(0,ve._)`${(0,Ao.checkDataTypes)(l,r,s.opts.strictNumbers,Ao.DataType.Wrong)}`}return ve.nil}function i(){if(n.validateSchema){const l=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,ve._)`!${l}(${r})`}return ve.nil}}subschema(e,r){const a=(0,Hl.getSubschema)(this.it,e);(0,Hl.extendSubschemaData)(a,this.it,e),(0,Hl.extendSubschemaMode)(a,e);const n={...this.it,...a,items:void 0,props:void 0};return Ib(n,r),n}mergeEvaluated(e,r){const{it:a,gen:n}=this;a.opts.unevaluated&&(a.props!==!0&&e.props!==void 0&&(a.props=dn.mergeEvaluated.props(n,e.props,a.props,r)),a.items!==!0&&e.items!==void 0&&(a.items=dn.mergeEvaluated.items(n,e.items,a.items,r)))}mergeValidEvaluated(e,r){const{it:a,gen:n}=this;if(a.opts.unevaluated&&(a.props!==!0||a.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,ve.Name)),!0}}Pr.KeywordCxt=lf;function cf(t,e,r,a){const n=new lf(t,r,e);"code"in r?r.code(n,a):n.$data&&r.validate?(0,cs.funcKeywordCode)(n,r):"macro"in r?(0,cs.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,cs.funcKeywordCode)(n,r)}const Fb=/^\/(?:[^~]|~0|~1)*$/,Zb=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function uf(t,{dataLevel:e,dataNames:r,dataPathArr:a}){let n,s;if(t==="")return $e.default.rootData;if(t[0]==="/"){if(!Fb.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=$e.default.rootData}else{const c=Zb.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);const u=+c[1];if(n=c[2],n==="#"){if(u>=e)throw new Error(l("property/index",u));return a[e-u]}if(u>e)throw new Error(l("data",u));if(s=r[e-u],!n)return s}let o=s;const i=n.split("/");for(const c of i)c&&(s=(0,ve._)`${s}${(0,ve.getProperty)((0,dn.unescapeJsonPointer)(c))}`,o=(0,ve._)`${o} && ${s}`);return o;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}Pr.getData=uf;var ds={};Object.defineProperty(ds,"__esModule",{value:!0});let Vb=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ds.default=Vb;var ba={};Object.defineProperty(ba,"__esModule",{value:!0});const Jl=Dt;let Hb=class extends Error{constructor(e,r,a,n){super(n||`can't resolve reference ${a} from id ${r}`),this.missingRef=(0,Jl.resolveUrl)(e,r,a),this.missingSchema=(0,Jl.normalizeId)((0,Jl.getFullPath)(e,this.missingRef))}};ba.default=Hb;var Wt={};Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.resolveSchema=Wt.getCompilingSchema=Wt.resolveRef=Wt.compileSchema=Wt.SchemaEnv=void 0;const kr=Me,Bb=ds,Zn=Fr,xr=Dt,df=ie,Jb=Pr;class Mo{constructor(e){var r;this.refs={},this.dynamicAnchors={};let a;typeof e.schema=="object"&&(a=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,xr.normalizeId)(a==null?void 0:a[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=a==null?void 0:a.$async,this.refs={}}}Wt.SchemaEnv=Mo;function Gl(t){const e=pf.call(this,t);if(e)return e;const r=(0,xr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:a,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new kr.CodeGen(this.scope,{es5:a,lines:n,ownProperties:s});let i;t.$async&&(i=o.scopeValue("Error",{ref:Bb.default,code:(0,kr._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");t.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Zn.default.data,parentData:Zn.default.parentData,parentDataProperty:Zn.default.parentDataProperty,dataNames:[Zn.default.data],dataPathArr:[kr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kr.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kr._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(t),(0,Jb.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const f=o.toString();u=`${o.scopeRefs(Zn.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,t));const d=new Function(`${Zn.default.self}`,`${Zn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:d}),d.errors=null,d.schema=t.schema,d.schemaEnv=t,t.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:l,validateCode:f,scopeValues:o._values}),this.opts.unevaluated){const{props:m,items:v}=c;d.evaluated={props:m instanceof kr.Name?void 0:m,items:v instanceof kr.Name?void 0:v,dynamicProps:m instanceof kr.Name,dynamicItems:v instanceof kr.Name},d.source&&(d.source.evaluated=(0,kr.stringify)(d.evaluated))}return t.validate=d,t}catch(f){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),f}finally{this._compilations.delete(t)}}Wt.compileSchema=Gl;function Gb(t,e,r){var a;r=(0,xr.resolveUrl)(this.opts.uriResolver,e,r);const n=t.refs[r];if(n)return n;let s=Qb.call(this,t,r);if(s===void 0){const o=(a=t.localRefs)===null||a===void 0?void 0:a[r],{schemaId:i}=this.opts;o&&(s=new Mo({schema:o,schemaId:i,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Kb.call(this,s)}Wt.resolveRef=Gb;function Kb(t){return(0,xr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Gl.call(this,t)}function pf(t){for(const e of this._compilations)if(Wb(e,t))return e}Wt.getCompilingSchema=pf;function Wb(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Qb(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||jo.call(this,t,e)}function jo(t,e){const r=this.opts.uriResolver.parse(e),a=(0,xr._getFullPath)(this.opts.uriResolver,r);let n=(0,xr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&a===n)return Kl.call(this,r,t);const s=(0,xr.normalizeId)(a),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){const i=jo.call(this,t,o);return typeof(i==null?void 0:i.schema)!="object"?void 0:Kl.call(this,r,i)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Gl.call(this,o),s===(0,xr.normalizeId)(e)){const{schema:i}=o,{schemaId:l}=this.opts,c=i[l];return c&&(n=(0,xr.resolveUrl)(this.opts.uriResolver,n,c)),new Mo({schema:i,schemaId:l,root:t,baseId:n})}return Kl.call(this,r,o)}}Wt.resolveSchema=jo;const Yb=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Kl(t,{baseId:e,schema:r,root:a}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(const i of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const l=r[(0,df.unescapeFragment)(i)];if(l===void 0)return;r=l;const c=typeof r=="object"&&r[this.opts.schemaId];!Yb.has(i)&&c&&(e=(0,xr.resolveUrl)(this.opts.uriResolver,e,c))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,df.schemaHasRulesButRef)(r,this.RULES)){const i=(0,xr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=jo.call(this,a,i)}const{schemaId:o}=this.opts;if(s=s||new Mo({schema:r,schemaId:o,root:a,baseId:e}),s.schema!==s.root.schema)return s}const Xb={$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 Wl={},Do={exports:{}};const e1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ff=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 hf(t){let e="",r=0,a=0;for(a=0;a<t.length;a++)if(r=t[a].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[a];break}for(a+=1;a<t.length;a++){if(r=t[a].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[a]}return e}const t1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function mf(t){return t.length=0,!0}function r1(t,e,r){if(t.length){const a=hf(t);if(a!=="")e.push(a);else return r.error=!0,!1;t.length=0}return!0}function n1(t){let e=0;const r={error:!1,address:"",zone:""},a=[],n=[];let s=!1,o=!1,i=r1;for(let l=0;l<t.length;l++){const c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(s===!0&&(o=!0),!i(n,a,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),a.push(":");continue}else if(c==="%"){if(!i(n,a,r))break;i=mf}else{n.push(c);continue}}return n.length&&(i===mf?r.zone=n.join(""):o?a.push(n.join("")):a.push(hf(n))),r.address=a.join(""),r}function vf(t){if(a1(t,":")<2)return{host:t,isIPV6:!1};const e=n1(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,a=e.address;return e.zone&&(r+="%"+e.zone,a+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:a}}}function a1(t,e){let r=0;for(let a=0;a<t.length;a++)t[a]===e&&r++;return r}function s1(t){let e=t;const r=[];let a=-1,n=0;for(;n=e.length;){if(n===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(n===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(n===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((a=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,a)),e=e.slice(a)}return r.join("")}function o1(t,e){const r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function i1(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!ff(r)){const a=vf(r);a.isIPV6===!0?r=`[${a.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var gf={nonSimpleDomain:t1,recomposeAuthority:i1,normalizeComponentEncoding:o1,removeDotSegments:s1,isIPv4:ff,isUUID:e1,normalizeIPv6:vf};const{isUUID:l1}=gf,c1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function yf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function _f(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function wf(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function u1(t){return t.secure=yf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function d1(t){if((t.port===(yf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function p1(t,e){if(!t.path)return t.error="URN can not be parsed",t;const r=t.path.match(c1);if(r){const a=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];const n=`${a}:${e.nid||t.nid}`,s=Ql(n);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function f1(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const r=e.scheme||t.scheme||"urn",a=t.nid.toLowerCase(),n=`${r}:${e.nid||a}`,s=Ql(n);s&&(t=s.serialize(t,e));const o=t,i=t.nss;return o.path=`${a||e.nid}:${i}`,e.skipEscape=!0,o}function h1(t,e){const r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!l1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function m1(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const bf={scheme:"http",domainHost:!0,parse:_f,serialize:wf},v1={scheme:"https",domainHost:bf.domainHost,parse:_f,serialize:wf},Lo={scheme:"ws",domainHost:!0,parse:u1,serialize:d1},g1={scheme:"wss",domainHost:Lo.domainHost,parse:Lo.parse,serialize:Lo.serialize},zo={http:bf,https:v1,ws:Lo,wss:g1,urn:{scheme:"urn",parse:p1,serialize:f1,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h1,serialize:m1,skipNormalize:!0}};Object.setPrototypeOf(zo,null);function Ql(t){return t&&(zo[t]||zo[t.toLowerCase()])||void 0}var y1={SCHEMES:zo,getSchemeHandler:Ql};const{normalizeIPv6:_1,removeDotSegments:ps,recomposeAuthority:w1,normalizeComponentEncoding:Uo,isIPv4:b1,nonSimpleDomain:E1}=gf,{SCHEMES:S1,getSchemeHandler:Ef}=y1;function $1(t,e){return typeof t=="string"?t=Hr(pn(t,e),e):typeof t=="object"&&(t=pn(Hr(t,e),e)),t}function P1(t,e,r){const a=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Sf(pn(t,a),pn(e,a),a,!0);return a.skipEscape=!0,Hr(n,a)}function Sf(t,e,r,a){const n={};return a||(t=pn(Hr(t,r),r),e=pn(Hr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=ps(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=ps(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=ps(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=ps(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function k1(t,e,r){return typeof t=="string"?(t=unescape(t),t=Hr(Uo(pn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Hr(Uo(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Hr(Uo(pn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Hr(Uo(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Hr(t,e){const r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},a=Object.assign({},e),n=[],s=Ef(a.scheme||r.scheme);s&&s.serialize&&s.serialize(r,a),r.path!==void 0&&(a.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),a.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");const o=w1(r);if(o!==void 0&&(a.reference!=="suffix"&&n.push("//"),n.push(o),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let i=r.path;!a.absolutePath&&(!s||!s.absolutePath)&&(i=ps(i)),o===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),n.push(i)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}const x1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pn(t,e){const r=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let n=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);const s=t.match(x1);if(s){if(a.scheme=s[1],a.userinfo=s[3],a.host=s[4],a.port=parseInt(s[5],10),a.path=s[6]||"",a.query=s[7],a.fragment=s[8],isNaN(a.port)&&(a.port=s[5]),a.host)if(b1(a.host)===!1){const l=_1(a.host);a.host=l.host.toLowerCase(),n=l.isIPV6}else n=!0;a.scheme===void 0&&a.userinfo===void 0&&a.host===void 0&&a.port===void 0&&a.query===void 0&&!a.path?a.reference="same-document":a.scheme===void 0?a.reference="relative":a.fragment===void 0?a.reference="absolute":a.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");const o=Ef(r.scheme||a.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&a.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&E1(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(i){a.error=a.error||"Host's domain name can not be converted to ASCII: "+i}(!o||o&&!o.skipNormalize)&&(t.indexOf("%")!==-1&&(a.scheme!==void 0&&(a.scheme=unescape(a.scheme)),a.host!==void 0&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),o&&o.parse&&o.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}const Yl={SCHEMES:S1,normalize:$1,resolve:P1,resolveComponent:Sf,equal:k1,serialize:Hr,parse:pn};Do.exports=Yl,Do.exports.default=Yl,Do.exports.fastUri=Yl;var I1=Do.exports;Object.defineProperty(Wl,"__esModule",{value:!0});const $f=I1;$f.code='require("ajv/dist/runtime/uri").default',Wl.default=$f,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=Pr;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Me;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 a=ds,n=ba,s=qn,o=Wt,i=Me,l=Dt,c=Tt,u=ie,f=Xb,g=Wl,d=(M,R)=>new RegExp(M,R);d.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"]),h={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."},p={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function w(M){var R,D,N,y,P,j,Q,ee,Se,de,ge,vt,Te,me,Ne,Ae,ke,tt,Ve,re,ze,Be,Ee,Qe,or;const At=M.strict,wt=(R=M.code)===null||R===void 0?void 0:R.optimize,ir=wt===!0||wt===void 0?1:wt||0,Mt=(N=(D=M.code)===null||D===void 0?void 0:D.regExp)!==null&&N!==void 0?N:d,lr=(y=M.uriResolver)!==null&&y!==void 0?y:g.default;return{strictSchema:(j=(P=M.strictSchema)!==null&&P!==void 0?P:At)!==null&&j!==void 0?j:!0,strictNumbers:(ee=(Q=M.strictNumbers)!==null&&Q!==void 0?Q:At)!==null&&ee!==void 0?ee:!0,strictTypes:(de=(Se=M.strictTypes)!==null&&Se!==void 0?Se:At)!==null&&de!==void 0?de:"log",strictTuples:(vt=(ge=M.strictTuples)!==null&&ge!==void 0?ge:At)!==null&&vt!==void 0?vt:"log",strictRequired:(me=(Te=M.strictRequired)!==null&&Te!==void 0?Te:At)!==null&&me!==void 0?me:!1,code:M.code?{...M.code,optimize:ir,regExp:Mt}:{optimize:ir,regExp:Mt},loopRequired:(Ne=M.loopRequired)!==null&&Ne!==void 0?Ne:_,loopEnum:(Ae=M.loopEnum)!==null&&Ae!==void 0?Ae:_,meta:(ke=M.meta)!==null&&ke!==void 0?ke:!0,messages:(tt=M.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ve=M.inlineRefs)!==null&&Ve!==void 0?Ve:!0,schemaId:(re=M.schemaId)!==null&&re!==void 0?re:"$id",addUsedSchema:(ze=M.addUsedSchema)!==null&&ze!==void 0?ze:!0,validateSchema:(Be=M.validateSchema)!==null&&Be!==void 0?Be:!0,validateFormats:(Ee=M.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(Qe=M.unicodeRegExp)!==null&&Qe!==void 0?Qe:!0,int32range:(or=M.int32range)!==null&&or!==void 0?or:!0,uriResolver:lr}}class b{constructor(R={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,R=this.opts={...R,...w(R)};const{es5:D,lines:N}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:D,lines:N}),this.logger=K(R.logger);const y=R.validateFormats;R.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,h,R,"NOT SUPPORTED"),S.call(this,p,R,"DEPRECATED","warn"),this._metaOpts=H.call(this),R.formats&&A.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),R.keywords&&O.call(this,R.keywords),typeof R.meta=="object"&&this.addMetaSchema(R.meta),k.call(this),R.validateFormats=y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:R,meta:D,schemaId:N}=this.opts;let y=f;N==="id"&&(y={...f},y.id=y.$id,delete y.$id),D&&R&&this.addMetaSchema(y,y[N],!1)}defaultMeta(){const{meta:R,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof R=="object"?R[D]||R:void 0}validate(R,D){let N;if(typeof R=="string"){if(N=this.getSchema(R),!N)throw new Error(`no schema with key or ref "${R}"`)}else N=this.compile(R);const y=N(D);return"$async"in N||(this.errors=N.errors),y}compile(R,D){const N=this._addSchema(R,D);return N.validate||this._compileSchemaEnv(N)}compileAsync(R,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return y.call(this,R,D);async function y(de,ge){await P.call(this,de.$schema);const vt=this._addSchema(de,ge);return vt.validate||j.call(this,vt)}async function P(de){de&&!this.getSchema(de)&&await y.call(this,{$ref:de},!0)}async function j(de){try{return this._compileSchemaEnv(de)}catch(ge){if(!(ge instanceof n.default))throw ge;return Q.call(this,ge),await ee.call(this,ge.missingSchema),j.call(this,de)}}function Q({missingSchema:de,missingRef:ge}){if(this.refs[de])throw new Error(`AnySchema ${de} is loaded but ${ge} cannot be resolved`)}async function ee(de){const ge=await Se.call(this,de);this.refs[de]||await P.call(this,ge.$schema),this.refs[de]||this.addSchema(ge,de,D)}async function Se(de){const ge=this._loading[de];if(ge)return ge;try{return await(this._loading[de]=N(de))}finally{delete this._loading[de]}}}addSchema(R,D,N,y=this.opts.validateSchema){if(Array.isArray(R)){for(const j of R)this.addSchema(j,void 0,N,y);return this}let P;if(typeof R=="object"){const{schemaId:j}=this.opts;if(P=R[j],P!==void 0&&typeof P!="string")throw new Error(`schema ${j} must be string`)}return D=(0,l.normalizeId)(D||P),this._checkUnique(D),this.schemas[D]=this._addSchema(R,N,D,y,!0),this}addMetaSchema(R,D,N=this.opts.validateSchema){return this.addSchema(R,D,!0,N),this}validateSchema(R,D){if(typeof R=="boolean")return!0;let N;if(N=R.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const y=this.validate(N,R);if(!y&&D){const P="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(P);else throw new Error(P)}return y}getSchema(R){let D;for(;typeof(D=x.call(this,R))=="string";)R=D;if(D===void 0){const{schemaId:N}=this.opts,y=new o.SchemaEnv({schema:{},schemaId:N});if(D=o.resolveSchema.call(this,y,R),!D)return;this.refs[R]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(R){if(R instanceof RegExp)return this._removeAllSchemas(this.schemas,R),this._removeAllSchemas(this.refs,R),this;switch(typeof R){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const D=x.call(this,R);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[R],delete this.refs[R],this}case"object":{const D=R;this._cache.delete(D);let N=R[this.opts.schemaId];return N&&(N=(0,l.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(R){for(const D of R)this.addKeyword(D);return this}addKeyword(R,D){let N;if(typeof R=="string")N=R,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=N);else if(typeof R=="object"&&D===void 0){if(D=R,N=D.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,N,D),!D)return(0,u.eachItem)(N,P=>G.call(this,P)),this;ne.call(this,D);const y={...D,type:(0,c.getJSONTypes)(D.type),schemaType:(0,c.getJSONTypes)(D.schemaType)};return(0,u.eachItem)(N,y.type.length===0?P=>G.call(this,P,y):P=>y.type.forEach(j=>G.call(this,P,y,j))),this}getKeyword(R){const D=this.RULES.all[R];return typeof D=="object"?D.definition:!!D}removeKeyword(R){const{RULES:D}=this;delete D.keywords[R],delete D.all[R];for(const N of D.rules){const y=N.rules.findIndex(P=>P.keyword===R);y>=0&&N.rules.splice(y,1)}return this}addFormat(R,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[R]=D,this}errorsText(R=this.errors,{separator:D=", ",dataVar:N="data"}={}){return!R||R.length===0?"No errors":R.map(y=>`${N}${y.instancePath} ${y.message}`).reduce((y,P)=>y+D+P)}$dataMetaSchema(R,D){const N=this.RULES.all;R=JSON.parse(JSON.stringify(R));for(const y of D){const P=y.split("/").slice(1);let j=R;for(const Q of P)j=j[Q];for(const Q in N){const ee=N[Q];if(typeof ee!="object")continue;const{$data:Se}=ee.definition,de=j[Q];Se&&de&&(j[Q]=pe(de))}}return R}_removeAllSchemas(R,D){for(const N in R){const y=R[N];(!D||D.test(N))&&(typeof y=="string"?delete R[N]:y&&!y.meta&&(this._cache.delete(y.schema),delete R[N]))}}_addSchema(R,D,N,y=this.opts.validateSchema,P=this.opts.addUsedSchema){let j;const{schemaId:Q}=this.opts;if(typeof R=="object")j=R[Q];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof R!="boolean")throw new Error("schema must be object or boolean")}let ee=this._cache.get(R);if(ee!==void 0)return ee;N=(0,l.normalizeId)(j||N);const Se=l.getSchemaRefs.call(this,R,N);return ee=new o.SchemaEnv({schema:R,schemaId:Q,meta:D,baseId:N,localRefs:Se}),this._cache.set(ee.schema,ee),P&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=ee),y&&this.validateSchema(R,!0),ee}_checkUnique(R){if(this.schemas[R]||this.refs[R])throw new Error(`schema with key or id "${R}" already exists`)}_compileSchemaEnv(R){if(R.meta?this._compileMetaSchema(R):o.compileSchema.call(this,R),!R.validate)throw new Error("ajv implementation error");return R.validate}_compileMetaSchema(R){const D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,R)}finally{this.opts=D}}}b.ValidationError=a.default,b.MissingRefError=n.default,t.default=b;function S(M,R,D,N="error"){for(const y in M){const P=y;P in R&&this.logger[N](`${D}: option ${y}. ${M[P]}`)}}function x(M){return M=(0,l.normalizeId)(M),this.schemas[M]||this.refs[M]}function k(){const M=this.opts.schemas;if(M)if(Array.isArray(M))this.addSchema(M);else for(const R in M)this.addSchema(M[R],R)}function A(){for(const M in this.opts.formats){const R=this.opts.formats[M];R&&this.addFormat(M,R)}}function O(M){if(Array.isArray(M)){this.addVocabulary(M);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const R in M){const D=M[R];D.keyword||(D.keyword=R),this.addKeyword(D)}}function H(){const M={...this.opts};for(const R of m)delete M[R];return M}const J={log(){},warn(){},error(){}};function K(M){if(M===!1)return J;if(M===void 0)return console;if(M.log&&M.warn&&M.error)return M;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function U(M,R){const{RULES:D}=this;if((0,u.eachItem)(M,N=>{if(D.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!z.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!R&&R.$data&&!("code"in R||"validate"in R))throw new Error('$data keyword must have "code" or "validate" function')}function G(M,R,D){var N;const y=R==null?void 0:R.post;if(D&&y)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:P}=this;let j=y?P.post:P.rules.find(({type:ee})=>ee===D);if(j||(j={type:D,rules:[]},P.rules.push(j)),P.keywords[M]=!0,!R)return;const Q={keyword:M,definition:{...R,type:(0,c.getJSONTypes)(R.type),schemaType:(0,c.getJSONTypes)(R.schemaType)}};R.before?se.call(this,j,Q,R.before):j.rules.push(Q),P.all[M]=Q,(N=R.implements)===null||N===void 0||N.forEach(ee=>this.addKeyword(ee))}function se(M,R,D){const N=M.rules.findIndex(y=>y.keyword===D);N>=0?M.rules.splice(N,0,R):(M.rules.push(R),this.logger.warn(`rule ${D} is not defined`))}function ne(M){let{metaSchema:R}=M;R!==void 0&&(M.$data&&this.opts.$data&&(R=pe(R)),M.validateSchema=this.compile(R,!0))}const ce={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(M){return{anyOf:[M,ce]}}}(Pp);var Xl={},ec={},tc={};Object.defineProperty(tc,"__esModule",{value:!0});const T1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};tc.default=T1;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.callRef=Vn.getValidate=void 0;const C1=ba,Pf=je,Qt=Me,Ea=Fr,kf=Wt,qo=ie,R1={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:r,it:a}=t,{baseId:n,schemaEnv:s,validateName:o,opts:i,self:l}=a,{root:c}=s;if((r==="#"||r==="#/")&&n===c.baseId)return f();const u=kf.resolveRef.call(l,c,n,r);if(u===void 0)throw new C1.default(a.opts.uriResolver,n,r);if(u instanceof kf.SchemaEnv)return g(u);return d(u);function f(){if(s===c)return Fo(t,o,s,s.$async);const m=e.scopeValue("root",{ref:c});return Fo(t,(0,Qt._)`${m}.validate`,c,c.$async)}function g(m){const v=xf(t,m);Fo(t,v,m,m.$async)}function d(m){const v=e.scopeValue("schema",i.code.source===!0?{ref:m,code:(0,Qt.stringify)(m)}:{ref:m}),h=e.name("valid"),p=t.subschema({schema:m,dataTypes:[],schemaPath:Qt.nil,topSchemaRef:v,errSchemaPath:r},h);t.mergeEvaluated(p),t.ok(h)}}};function xf(t,e){const{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Vn.getValidate=xf;function Fo(t,e,r,a){const{gen:n,it:s}=t,{allErrors:o,schemaEnv:i,opts:l}=s,c=l.passContext?Ea.default.this:Qt.nil;a?u():f();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");const m=n.let("valid");n.try(()=>{n.code((0,Qt._)`await ${(0,Pf.callValidateCode)(t,e,c)}`),d(e),o||n.assign(m,!0)},v=>{n.if((0,Qt._)`!(${v} instanceof ${s.ValidationError})`,()=>n.throw(v)),g(v),o||n.assign(m,!1)}),t.ok(m)}function f(){t.result((0,Pf.callValidateCode)(t,e,c),()=>d(e),()=>g(e))}function g(m){const v=(0,Qt._)`${m}.errors`;n.assign(Ea.default.vErrors,(0,Qt._)`${Ea.default.vErrors} === null ? ${v} : ${Ea.default.vErrors}.concat(${v})`),n.assign(Ea.default.errors,(0,Qt._)`${Ea.default.vErrors}.length`)}function d(m){var v;if(!s.opts.unevaluated)return;const h=(v=r==null?void 0:r.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=qo.mergeEvaluated.props(n,h.props,s.props));else{const p=n.var("props",(0,Qt._)`${m}.evaluated.props`);s.props=qo.mergeEvaluated.props(n,p,s.props,Qt.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=qo.mergeEvaluated.items(n,h.items,s.items));else{const p=n.var("items",(0,Qt._)`${m}.evaluated.items`);s.items=qo.mergeEvaluated.items(n,p,s.items,Qt.Name)}}}Vn.callRef=Fo,Vn.default=R1,Object.defineProperty(ec,"__esModule",{value:!0});const O1=tc,N1=Vn,A1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",O1.default,N1.default];ec.default=A1;var rc={},nc={};Object.defineProperty(nc,"__esModule",{value:!0});const Zo=Me,$n=Zo.operators,Vo={maximum:{okStr:"<=",ok:$n.LTE,fail:$n.GT},minimum:{okStr:">=",ok:$n.GTE,fail:$n.LT},exclusiveMaximum:{okStr:"<",ok:$n.LT,fail:$n.GTE},exclusiveMinimum:{okStr:">",ok:$n.GT,fail:$n.LTE}},M1={message:({keyword:t,schemaCode:e})=>(0,Zo.str)`must be ${Vo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Zo._)`{comparison: ${Vo[t].okStr}, limit: ${e}}`},j1={keyword:Object.keys(Vo),type:"number",schemaType:"number",$data:!0,error:M1,code(t){const{keyword:e,data:r,schemaCode:a}=t;t.fail$data((0,Zo._)`${r} ${Vo[e].fail} ${a} || isNaN(${r})`)}};nc.default=j1;var ac={};Object.defineProperty(ac,"__esModule",{value:!0});const fs=Me,D1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>(0,fs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,fs._)`{multipleOf: ${t}}`},code(t){const{gen:e,data:r,schemaCode:a,it:n}=t,s=n.opts.multipleOfPrecision,o=e.let("res"),i=s?(0,fs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,fs._)`${o} !== parseInt(${o})`;t.fail$data((0,fs._)`(${a} === 0 || (${o} = ${r}/${a}, ${i}))`)}};ac.default=D1;var sc={},oc={};Object.defineProperty(oc,"__esModule",{value:!0});function If(t){const e=t.length;let r=0,a=0,n;for(;a<e;)r++,n=t.charCodeAt(a++),n>=55296&&n<=56319&&a<e&&(n=t.charCodeAt(a),(n&64512)===56320&&a++);return r}oc.default=If,If.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(sc,"__esModule",{value:!0});const Hn=Me,L1=ie,z1=oc,U1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxLength"?"more":"fewer";return(0,Hn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Hn._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a,it:n}=t,s=e==="maxLength"?Hn.operators.GT:Hn.operators.LT,o=n.opts.unicode===!1?(0,Hn._)`${r}.length`:(0,Hn._)`${(0,L1.useFunc)(t.gen,z1.default)}(${r})`;t.fail$data((0,Hn._)`${o} ${s} ${a}`)}};sc.default=U1;var ic={};Object.defineProperty(ic,"__esModule",{value:!0});const q1=je,Ho=Me,F1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,Ho.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ho._)`{pattern: ${t}}`},code(t){const{data:e,$data:r,schema:a,schemaCode:n,it:s}=t,o=s.opts.unicodeRegExp?"u":"",i=r?(0,Ho._)`(new RegExp(${n}, ${o}))`:(0,q1.usePattern)(t,a);t.fail$data((0,Ho._)`!${i}.test(${e})`)}};ic.default=F1;var lc={};Object.defineProperty(lc,"__esModule",{value:!0});const hs=Me,Z1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxProperties"?"more":"fewer";return(0,hs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hs._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxProperties"?hs.operators.GT:hs.operators.LT;t.fail$data((0,hs._)`Object.keys(${r}).length ${n} ${a}`)}};lc.default=Z1;var cc={};Object.defineProperty(cc,"__esModule",{value:!0});const ms=je,vs=Me,V1=ie,H1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:t}})=>(0,vs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,vs._)`{missingProperty: ${t}}`},code(t){const{gen:e,schema:r,schemaCode:a,data:n,$data:s,it:o}=t,{opts:i}=o;if(!s&&r.length===0)return;const l=r.length>=i.loopRequired;if(o.allErrors?c():u(),i.strictRequired){const d=t.parentSchema.properties,{definedProperties:m}=t.it;for(const v of r)if((d==null?void 0:d[v])===void 0&&!m.has(v)){const h=o.schemaEnv.baseId+o.errSchemaPath,p=`required property "${v}" is not defined at "${h}" (strictRequired)`;(0,V1.checkStrictMode)(o,p,o.opts.strictRequired)}}function c(){if(l||s)t.block$data(vs.nil,f);else for(const d of r)(0,ms.checkReportMissingProp)(t,d)}function u(){const d=e.let("missing");if(l||s){const m=e.let("valid",!0);t.block$data(m,()=>g(d,m)),t.ok(m)}else e.if((0,ms.checkMissingProp)(t,r,d)),(0,ms.reportMissingProp)(t,d),e.else()}function f(){e.forOf("prop",a,d=>{t.setParams({missingProperty:d}),e.if((0,ms.noPropertyInData)(e,n,d,i.ownProperties),()=>t.error())})}function g(d,m){t.setParams({missingProperty:d}),e.forOf(d,a,()=>{e.assign(m,(0,ms.propertyInData)(e,n,d,i.ownProperties)),e.if((0,vs.not)(m),()=>{t.error(),e.break()})},vs.nil)}}};cc.default=H1;var uc={};Object.defineProperty(uc,"__esModule",{value:!0});const gs=Me,B1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxItems"?"more":"fewer";return(0,gs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gs._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxItems"?gs.operators.GT:gs.operators.LT;t.fail$data((0,gs._)`${r}.length ${n} ${a}`)}};uc.default=B1;var dc={},ys={};Object.defineProperty(ys,"__esModule",{value:!0});const Tf=ls;Tf.code='require("ajv/dist/runtime/equal").default',ys.default=Tf,Object.defineProperty(dc,"__esModule",{value:!0});const pc=Tt,Lt=Me,J1=ie,G1=ys,K1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:t,j:e}})=>(0,Lt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Lt._)`{i: ${t}, j: ${e}}`},code(t){const{gen:e,data:r,$data:a,schema:n,parentSchema:s,schemaCode:o,it:i}=t;if(!a&&!n)return;const l=e.let("valid"),c=s.items?(0,pc.getSchemaTypes)(s.items):[];t.block$data(l,u,(0,Lt._)`${o} === false`),t.ok(l);function u(){const m=e.let("i",(0,Lt._)`${r}.length`),v=e.let("j");t.setParams({i:m,j:v}),e.assign(l,!0),e.if((0,Lt._)`${m} > 1`,()=>(f()?g:d)(m,v))}function f(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function g(m,v){const h=e.name("item"),p=(0,pc.checkDataTypes)(c,h,i.opts.strictNumbers,pc.DataType.Wrong),_=e.const("indices",(0,Lt._)`{}`);e.for((0,Lt._)`;${m}--;`,()=>{e.let(h,(0,Lt._)`${r}[${m}]`),e.if(p,(0,Lt._)`continue`),c.length>1&&e.if((0,Lt._)`typeof ${h} == "string"`,(0,Lt._)`${h} += "_"`),e.if((0,Lt._)`typeof ${_}[${h}] == "number"`,()=>{e.assign(v,(0,Lt._)`${_}[${h}]`),t.error(),e.assign(l,!1).break()}).code((0,Lt._)`${_}[${h}] = ${m}`)})}function d(m,v){const h=(0,J1.useFunc)(e,G1.default),p=e.name("outer");e.label(p).for((0,Lt._)`;${m}--;`,()=>e.for((0,Lt._)`${v} = ${m}; ${v}--;`,()=>e.if((0,Lt._)`${h}(${r}[${m}], ${r}[${v}])`,()=>{t.error(),e.assign(l,!1).break(p)})))}}};dc.default=K1;var fc={};Object.defineProperty(fc,"__esModule",{value:!0});const hc=Me,W1=ie,Q1=ys,Y1={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>(0,hc._)`{allowedValue: ${t}}`},code(t){const{gen:e,data:r,$data:a,schemaCode:n,schema:s}=t;a||s&&typeof s=="object"?t.fail$data((0,hc._)`!${(0,W1.useFunc)(e,Q1.default)}(${r}, ${n})`):t.fail((0,hc._)`${s} !== ${r}`)}};fc.default=Y1;var mc={};Object.defineProperty(mc,"__esModule",{value:!0});const _s=Me,X1=ie,eE=ys,tE={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,_s._)`{allowedValues: ${t}}`},code(t){const{gen:e,data:r,$data:a,schema:n,schemaCode:s,it:o}=t;if(!a&&n.length===0)throw new Error("enum must have non-empty array");const i=n.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,X1.useFunc)(e,eE.default));let u;if(i||a)u=e.let("valid"),t.block$data(u,f);else{if(!Array.isArray(n))throw new Error("ajv implementation error");const d=e.const("vSchema",s);u=(0,_s.or)(...n.map((m,v)=>g(d,v)))}t.pass(u);function f(){e.assign(u,!1),e.forOf("v",s,d=>e.if((0,_s._)`${c()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function g(d,m){const v=n[m];return typeof v=="object"&&v!==null?(0,_s._)`${c()}(${r}, ${d}[${m}])`:(0,_s._)`${r} === ${v}`}}};mc.default=tE,Object.defineProperty(rc,"__esModule",{value:!0});const rE=nc,nE=ac,aE=sc,sE=ic,oE=lc,iE=cc,lE=uc,cE=dc,uE=fc,dE=mc,pE=[rE.default,nE.default,aE.default,sE.default,oE.default,iE.default,lE.default,cE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uE.default,dE.default];rc.default=pE;var vc={},Sa={};Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.validateAdditionalItems=void 0;const Bn=Me,gc=ie,fE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,Bn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Bn._)`{limit: ${t}}`},code(t){const{parentSchema:e,it:r}=t,{items:a}=e;if(!Array.isArray(a)){(0,gc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Cf(t,a)}};function Cf(t,e){const{gen:r,schema:a,data:n,keyword:s,it:o}=t;o.items=!0;const i=r.const("len",(0,Bn._)`${n}.length`);if(a===!1)t.setParams({len:e.length}),t.pass((0,Bn._)`${i} <= ${e.length}`);else if(typeof a=="object"&&!(0,gc.alwaysValidSchema)(o,a)){const c=r.var("valid",(0,Bn._)`${i} <= ${e.length}`);r.if((0,Bn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,i,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:gc.Type.Num},c),o.allErrors||r.if((0,Bn.not)(c),()=>r.break())})}}Sa.validateAdditionalItems=Cf,Sa.default=fE;var yc={},$a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.validateTuple=void 0;const Rf=Me,Bo=ie,hE=je,mE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:r}=t;if(Array.isArray(e))return Of(t,"additionalItems",e);r.items=!0,!(0,Bo.alwaysValidSchema)(r,e)&&t.ok((0,hE.validateArray)(t))}};function Of(t,e,r=t.schema){const{gen:a,parentSchema:n,data:s,keyword:o,it:i}=t;u(n),i.opts.unevaluated&&r.length&&i.items!==!0&&(i.items=Bo.mergeEvaluated.items(a,r.length,i.items));const l=a.name("valid"),c=a.const("len",(0,Rf._)`${s}.length`);r.forEach((f,g)=>{(0,Bo.alwaysValidSchema)(i,f)||(a.if((0,Rf._)`${c} > ${g}`,()=>t.subschema({keyword:o,schemaProp:g,dataProp:g},l)),t.ok(l))});function u(f){const{opts:g,errSchemaPath:d}=i,m=r.length,v=m===f.minItems&&(m===f.maxItems||f[e]===!1);if(g.strictTuples&&!v){const h=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,Bo.checkStrictMode)(i,h,g.strictTuples)}}}$a.validateTuple=Of,$a.default=mE,Object.defineProperty(yc,"__esModule",{value:!0});const vE=$a,gE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,vE.validateTuple)(t,"items")};yc.default=gE;var _c={};Object.defineProperty(_c,"__esModule",{value:!0});const Nf=Me,yE=ie,_E=je,wE=Sa,bE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,Nf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nf._)`{limit: ${t}}`},code(t){const{schema:e,parentSchema:r,it:a}=t,{prefixItems:n}=r;a.items=!0,!(0,yE.alwaysValidSchema)(a,e)&&(n?(0,wE.validateAdditionalItems)(t,n):t.ok((0,_E.validateArray)(t)))}};_c.default=bE;var wc={};Object.defineProperty(wc,"__esModule",{value:!0});const mr=Me,Jo=ie,EE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:e}})=>e===void 0?(0,mr.str)`must contain at least ${t} valid item(s)`:(0,mr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,mr._)`{minContains: ${t}}`:(0,mr._)`{minContains: ${t}, maxContains: ${e}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;let o,i;const{minContains:l,maxContains:c}=a;s.opts.next?(o=l===void 0?1:l,i=c):o=1;const u=e.const("len",(0,mr._)`${n}.length`);if(t.setParams({min:o,max:i}),i===void 0&&o===0){(0,Jo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&o>i){(0,Jo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Jo.alwaysValidSchema)(s,r)){let v=(0,mr._)`${u} >= ${o}`;i!==void 0&&(v=(0,mr._)`${v} && ${u} <= ${i}`),t.pass(v);return}s.items=!0;const f=e.name("valid");i===void 0&&o===1?d(f,()=>e.if(f,()=>e.break())):o===0?(e.let(f,!0),i!==void 0&&e.if((0,mr._)`${n}.length > 0`,g)):(e.let(f,!1),g()),t.result(f,()=>t.reset());function g(){const v=e.name("_valid"),h=e.let("count",0);d(v,()=>e.if(v,()=>m(h)))}function d(v,h){e.forRange("i",0,u,p=>{t.subschema({keyword:"contains",dataProp:p,dataPropType:Jo.Type.Num,compositeRule:!0},v),h()})}function m(v){e.code((0,mr._)`${v}++`),i===void 0?e.if((0,mr._)`${v} >= ${o}`,()=>e.assign(f,!0).break()):(e.if((0,mr._)`${v} > ${i}`,()=>e.assign(f,!1).break()),o===1?e.assign(f,!0):e.if((0,mr._)`${v} >= ${o}`,()=>e.assign(f,!0)))}}};wc.default=EE;var Af={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Me,r=ie,a=je;t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,e.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,e._)`{property: ${l},
6
- missingProperty: ${f},
1
+ (function(xe,Zr){typeof exports=="object"&&typeof module<"u"?Zr(exports):typeof define=="function"&&define.amd?define(["exports"],Zr):(xe=typeof globalThis<"u"?globalThis:xe||self,Zr(xe.WebMCP={}))})(this,function(xe){"use strict";function Zr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ui={exports:{}},Ld={},Yt={},Ur={},To={},me={},xo={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(w){if(super(),!e.IDENTIFIER.test(w))throw new Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(w){super(),this._items=typeof w=="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((_,b)=>`${_}${b}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((_,b)=>(b instanceof n&&(_[b.str]=(_[b.str]||0)+1),_),{})}}e._Code=r,e.nil=new r("");function o(d,...w){const _=[d[0]];let b=0;for(;b<w.length;)i(_,w[b]),_.push(d[++b]);return new r(_)}e._=o;const s=new r("+");function a(d,...w){const _=[f(d[0])];let b=0;for(;b<w.length;)_.push(s),i(_,w[b]),_.push(s,f(d[++b]));return l(_),new r(_)}e.str=a;function i(d,w){w instanceof r?d.push(...w._items):w instanceof n?d.push(w):d.push(h(w))}e.addCodeArg=i;function l(d){let w=1;for(;w<d.length-1;){if(d[w]===s){const _=c(d[w-1],d[w+1]);if(_!==void 0){d.splice(w-1,3,_);continue}d[w++]="+"}w++}}function c(d,w){if(w==='""')return d;if(d==='""')return w;if(typeof d=="string")return w instanceof n||d[d.length-1]!=='"'?void 0:typeof w!="string"?`${d.slice(0,-1)}${w}"`:w[0]==='"'?d.slice(0,-1)+w.slice(1):void 0;if(typeof w=="string"&&w[0]==='"'&&!(d instanceof n))return`"${d}${w.slice(1)}`}function u(d,w){return w.emptyStr()?d:d.emptyStr()?w:a`${d}${w}`}e.strConcat=u;function h(d){return typeof d=="number"||typeof d=="boolean"||d===null?d:f(Array.isArray(d)?d.join(","):d)}function y(d){return new r(f(d))}e.stringify=y;function f(d){return JSON.stringify(d).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function g(d){return typeof d=="string"&&e.IDENTIFIER.test(d)?new r(`.${d}`):o`[${d}]`}e.getProperty=g;function v(d){if(typeof d=="string"&&e.IDENTIFIER.test(d))return new r(`${d}`);throw new Error(`CodeGen: invalid export name: ${d}, use explicit $id name mapping`)}e.getEsmExportName=v;function m(d){return new r(d.toString())}e.regexpCode=m})(xo);var qi={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=xo;class n extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var r;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${h}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const y=this.toName(c),{prefix:f}=y,g=(h=u.key)!==null&&h!==void 0?h:u.ref;let v=this._values[f];if(v){const w=v.get(g);if(w)return w}else v=this._values[f]=new Map;v.set(g,y);const m=this._scope[f]||(this._scope[f]=[]),d=m.length;return m[d]=u.ref,y.setValue(u,{property:f,itemIndex:d}),y}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,t._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,y=>{if(y.value===void 0)throw new Error(`CodeGen: name "${y}" has no value`);return y.value.code},u,h)}_reduceValues(c,u,h={},y){let f=t.nil;for(const g in c){const v=c[g];if(!v)continue;const m=h[g]=h[g]||new Map;v.forEach(d=>{if(m.has(d))return;m.set(d,r.Started);let w=u(d);if(w){const _=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${_} ${d} = ${w};${this.opts._n}`}else if(w=y==null?void 0:y(d))f=(0,t._)`${f}${w}${this.opts._n}`;else throw new n(d);m.set(d,r.Completed)})}return f}}e.ValueScope=i})(qi),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=xo,n=qi;var r=xo;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=qi;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames($,k){return this}}class a extends s{constructor($,k,S){super(),this.varKind=$,this.name=k,this.rhs=S}render({es5:$,_n:k}){const S=$?n.varKinds.var:this.varKind,z=this.rhs===void 0?"":` = ${this.rhs}`;return`${S} ${this.name}${z};`+k}optimizeNames($,k){if($[this.name.str])return this.rhs&&(this.rhs=H(this.rhs,$,k)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor($,k,S){super(),this.lhs=$,this.rhs=k,this.sideEffects=S}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,k){if(!(this.lhs instanceof t.Name&&!$[this.lhs.str]&&!this.sideEffects))return this.rhs=H(this.rhs,$,k),this}get names(){const $=this.lhs instanceof t.Name?{}:{...this.lhs.names};return J($,this.rhs)}}class l extends i{constructor($,k,S,z){super($,S,z),this.op=k}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class c extends s{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class u extends s{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class h extends s{constructor($){super(),this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class y extends s{constructor($){super(),this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,k){return this.code=H(this.code,$,k),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor($=[]){super(),this.nodes=$}render($){return this.nodes.reduce((k,S)=>k+S.render($),"")}optimizeNodes(){const{nodes:$}=this;let k=$.length;for(;k--;){const S=$[k].optimizeNodes();Array.isArray(S)?$.splice(k,1,...S):S?$[k]=S:$.splice(k,1)}return $.length>0?this:void 0}optimizeNames($,k){const{nodes:S}=this;let z=S.length;for(;z--;){const D=S[z];D.optimizeNames($,k)||(ue($,D.names),S.splice(z,1))}return S.length>0?this:void 0}get names(){return this.nodes.reduce(($,k)=>B($,k.names),{})}}class g extends f{render($){return"{"+$._n+super.render($)+"}"+$._n}}class v extends f{}class m extends g{}m.kind="else";class d extends g{constructor($,k){super(k),this.condition=$}render($){let k=`if(${this.condition})`+super.render($);return this.else&&(k+="else "+this.else.render($)),k}optimizeNodes(){super.optimizeNodes();const $=this.condition;if($===!0)return this.nodes;let k=this.else;if(k){const S=k.optimizeNodes();k=this.else=Array.isArray(S)?new m(S):S}if(k)return $===!1?k instanceof d?k:k.nodes:this.nodes.length?this:new d(Ce($),k instanceof d?[k]:k.nodes);if(!($===!1||!this.nodes.length))return this}optimizeNames($,k){var S;if(this.else=(S=this.else)===null||S===void 0?void 0:S.optimizeNames($,k),!!(super.optimizeNames($,k)||this.else))return this.condition=H(this.condition,$,k),this}get names(){const $=super.names;return J($,this.condition),this.else&&B($,this.else.names),$}}d.kind="if";class w extends g{}w.kind="for";class _ extends w{constructor($){super(),this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,k){if(super.optimizeNames($,k))return this.iteration=H(this.iteration,$,k),this}get names(){return B(super.names,this.iteration.names)}}class b extends w{constructor($,k,S,z){super(),this.varKind=$,this.name=k,this.from=S,this.to=z}render($){const k=$.es5?n.varKinds.var:this.varKind,{name:S,from:z,to:D}=this;return`for(${k} ${S}=${z}; ${S}<${D}; ${S}++)`+super.render($)}get names(){const $=J(super.names,this.from);return J($,this.to)}}class T extends w{constructor($,k,S,z){super(),this.loop=$,this.varKind=k,this.name=S,this.iterable=z}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,k){if(super.optimizeNames($,k))return this.iterable=H(this.iterable,$,k),this}get names(){return B(super.names,this.iterable.names)}}class P extends g{constructor($,k,S){super(),this.name=$,this.args=k,this.async=S}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}P.kind="func";class E extends f{render($){return"return "+super.render($)}}E.kind="return";class Z extends g{render($){let k="try"+super.render($);return this.catch&&(k+=this.catch.render($)),this.finally&&(k+=this.finally.render($)),k}optimizeNodes(){var $,k;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames($,k){var S,z;return super.optimizeNames($,k),(S=this.catch)===null||S===void 0||S.optimizeNames($,k),(z=this.finally)===null||z===void 0||z.optimizeNames($,k),this}get names(){const $=super.names;return this.catch&&B($,this.catch.names),this.finally&&B($,this.finally.names),$}}class U extends g{constructor($){super(),this.error=$}render($){return`catch(${this.error})`+super.render($)}}U.kind="catch";class W extends g{render($){return"finally"+super.render($)}}W.kind="finally";class V{constructor($,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?`
2
+ `:""},this._extScope=$,this._scope=new n.Scope({parent:$}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,k){const S=this._extScope.value($,k);return(this._values[S.prefix]||(this._values[S.prefix]=new Set)).add(S),S}getScopeValue($,k){return this._extScope.getValue($,k)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,k,S,z){const D=this._scope.toName(k);return S!==void 0&&z&&(this._constants[D.str]=S),this._leafNode(new a($,D,S)),D}const($,k,S){return this._def(n.varKinds.const,$,k,S)}let($,k,S){return this._def(n.varKinds.let,$,k,S)}var($,k,S){return this._def(n.varKinds.var,$,k,S)}assign($,k,S){return this._leafNode(new i($,k,S))}add($,k){return this._leafNode(new l($,e.operators.ADD,k))}code($){return typeof $=="function"?$():$!==t.nil&&this._leafNode(new y($)),this}object(...$){const k=["{"];for(const[S,z]of $)k.length>1&&k.push(","),k.push(S),(S!==z||this.opts.es5)&&(k.push(":"),(0,t.addCodeArg)(k,z));return k.push("}"),new t._Code(k)}if($,k,S){if(this._blockNode(new d($)),k&&S)this.code(k).else().code(S).endIf();else if(k)this.code(k).endIf();else if(S)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new d($))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(d,m)}_for($,k){return this._blockNode($),k&&this.code(k).endFor(),this}for($,k){return this._for(new _($),k)}forRange($,k,S,z,D=this.opts.es5?n.varKinds.var:n.varKinds.let){const ve=this._scope.toName($);return this._for(new b(D,ve,k,S),()=>z(ve))}forOf($,k,S,z=n.varKinds.const){const D=this._scope.toName($);if(this.opts.es5){const ve=k instanceof t.Name?k:this.var("_arr",k);return this.forRange("_i",0,(0,t._)`${ve}.length`,ce=>{this.var(D,(0,t._)`${ve}[${ce}]`),S(D)})}return this._for(new T("of",z,D,k),()=>S(D))}forIn($,k,S,z=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,t._)`Object.keys(${k})`,S);const D=this._scope.toName($);return this._for(new T("in",z,D,k),()=>S(D))}endFor(){return this._endBlockNode(w)}label($){return this._leafNode(new c($))}break($){return this._leafNode(new u($))}return($){const k=new E;if(this._blockNode(k),this.code($),k.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try($,k,S){if(!k&&!S)throw new Error('CodeGen: "try" without "catch" and "finally"');const z=new Z;if(this._blockNode(z),this.code($),k){const D=this.name("e");this._currNode=z.catch=new U(D),k(D)}return S&&(this._currNode=z.finally=new W,this.code(S)),this._endBlockNode(U,W)}throw($){return this._leafNode(new h($))}block($,k){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(k),this}endBlock($){const k=this._blockStarts.pop();if(k===void 0)throw new Error("CodeGen: not in self-balancing block");const S=this._nodes.length-k;if(S<0||$!==void 0&&S!==$)throw new Error(`CodeGen: wrong number of nodes: ${S} vs ${$} expected`);return this._nodes.length=k,this}func($,k=t.nil,S,z){return this._blockNode(new P($,k,S)),z&&this.code(z).endFunc(),this}endFunc(){return this._endBlockNode(P)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,k){const S=this._currNode;if(S instanceof $||k&&S instanceof k)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${k?`${$.kind}/${k.kind}`:$.kind}"`)}_elseNode($){const k=this._currNode;if(!(k instanceof d))throw new Error('CodeGen: "else" without "if"');return this._currNode=k.else=$,this}get _root(){return this._nodes[0]}get _currNode(){const $=this._nodes;return $[$.length-1]}set _currNode($){const k=this._nodes;k[k.length-1]=$}}e.CodeGen=V;function B(R,$){for(const k in $)R[k]=(R[k]||0)+($[k]||0);return R}function J(R,$){return $ instanceof t._CodeOrName?B(R,$.names):R}function H(R,$,k){if(R instanceof t.Name)return S(R);if(!z(R))return R;return new t._Code(R._items.reduce((D,ve)=>(ve instanceof t.Name&&(ve=S(ve)),ve instanceof t._Code?D.push(...ve._items):D.push(ve),D),[]));function S(D){const ve=k[D.str];return ve===void 0||$[D.str]!==1?D:(delete $[D.str],ve)}function z(D){return D instanceof t._Code&&D._items.some(ve=>ve instanceof t.Name&&$[ve.str]===1&&k[ve.str]!==void 0)}}function ue(R,$){for(const k in $)R[k]=(R[k]||0)-($[k]||0)}function Ce(R){return typeof R=="boolean"||typeof R=="number"||R===null?!R:(0,t._)`!${M(R)}`}e.not=Ce;const ae=x(e.operators.AND);function ye(...R){return R.reduce(ae)}e.and=ye;const he=x(e.operators.OR);function L(...R){return R.reduce(he)}e.or=L;function x(R){return($,k)=>$===t.nil?k:k===t.nil?$:(0,t._)`${M($)} ${R} ${M(k)}`}function M(R){return R instanceof t.Name?R:(0,t._)`(${R})`}}(me);var K={};Object.defineProperty(K,"__esModule",{value:!0}),K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;const Ue=me,dy=xo;function py(e){const t={};for(const n of e)t[n]=!0;return t}K.toHash=py;function fy(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(zd(e,t),!Dd(t,e.self.RULES.all))}K.alwaysValidSchema=fy;function zd(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||Fd(e,`unknown keyword: "${s}"`)}K.checkUnknownRules=zd;function Dd(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}K.schemaHasRules=Dd;function hy(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}K.schemaHasRulesButRef=hy;function my({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Ue._)`${n}`}return(0,Ue._)`${e}${t}${(0,Ue.getProperty)(r)}`}K.schemaRefOrVal=my;function gy(e){return Zd(decodeURIComponent(e))}K.unescapeFragment=gy;function yy(e){return encodeURIComponent(Vi(e))}K.escapeFragment=yy;function Vi(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=Vi;function Zd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=Zd;function vy(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}K.eachItem=vy;function Ud({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,a,i)=>{const l=a===void 0?s:a instanceof Ue.Name?(s instanceof Ue.Name?e(o,s,a):t(o,s,a),a):s instanceof Ue.Name?(t(o,a,s),s):n(s,a);return i===Ue.Name&&!(l instanceof Ue.Name)?r(o,l):l}}K.mergeEvaluated={props:Ud({mergeNames:(e,t,n)=>e.if((0,Ue._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,Ue._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,Ue._)`${n} || {}`).code((0,Ue._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,Ue._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,Ue._)`${n} || {}`),Fi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:qd}),items:Ud({mergeNames:(e,t,n)=>e.if((0,Ue._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,Ue._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,Ue._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,Ue._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function qd(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,Ue._)`{}`);return t!==void 0&&Fi(e,n,t),n}K.evaluatedPropsToName=qd;function Fi(e,t,n){Object.keys(n).forEach(r=>e.assign((0,Ue._)`${t}${(0,Ue.getProperty)(r)}`,!0))}K.setEvaluated=Fi;const Vd={};function _y(e,t){return e.scopeValue("func",{ref:t,code:Vd[t.code]||(Vd[t.code]=new dy._Code(t.code))})}K.useFunc=_y;var Bi;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Bi||(K.Type=Bi={}));function wy(e,t,n){if(e instanceof Ue.Name){const r=t===Bi.Num;return n?r?(0,Ue._)`"[" + ${e} + "]"`:(0,Ue._)`"['" + ${e} + "']"`:r?(0,Ue._)`"/" + ${e}`:(0,Ue._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Ue.getProperty)(e).toString():"/"+Vi(e)}K.getErrorPath=wy;function Fd(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}K.checkStrictMode=Fd;var yn={};Object.defineProperty(yn,"__esModule",{value:!0});const ft=me,by={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};yn.default=by,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=me,n=K,r=yn;e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:d})=>d?(0,t.str)`"${m}" keyword must be ${d} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,d=e.keywordError,w,_){const{it:b}=m,{gen:T,compositeRule:P,allErrors:E}=b,Z=h(m,d,w);_??(P||E)?l(T,Z):c(b,(0,t._)`[${Z}]`)}e.reportError=o;function s(m,d=e.keywordError,w){const{it:_}=m,{gen:b,compositeRule:T,allErrors:P}=_,E=h(m,d,w);l(b,E),T||P||c(_,r.default.vErrors)}e.reportExtraError=s;function a(m,d){m.assign(r.default.errors,d),m.if((0,t._)`${r.default.vErrors} !== null`,()=>m.if(d,()=>m.assign((0,t._)`${r.default.vErrors}.length`,d),()=>m.assign(r.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:m,keyword:d,schemaValue:w,data:_,errsCount:b,it:T}){if(b===void 0)throw new Error("ajv implementation error");const P=m.name("err");m.forRange("i",b,r.default.errors,E=>{m.const(P,(0,t._)`${r.default.vErrors}[${E}]`),m.if((0,t._)`${P}.instancePath === undefined`,()=>m.assign((0,t._)`${P}.instancePath`,(0,t.strConcat)(r.default.instancePath,T.errorPath))),m.assign((0,t._)`${P}.schemaPath`,(0,t.str)`${T.errSchemaPath}/${d}`),T.opts.verbose&&(m.assign((0,t._)`${P}.schema`,w),m.assign((0,t._)`${P}.data`,_))})}e.extendErrors=i;function l(m,d){const w=m.const("err",d);m.if((0,t._)`${r.default.vErrors} === null`,()=>m.assign(r.default.vErrors,(0,t._)`[${w}]`),(0,t._)`${r.default.vErrors}.push(${w})`),m.code((0,t._)`${r.default.errors}++`)}function c(m,d){const{gen:w,validateName:_,schemaEnv:b}=m;b.$async?w.throw((0,t._)`new ${m.ValidationError}(${d})`):(w.assign((0,t._)`${_}.errors`,d),w.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(m,d,w){const{createErrors:_}=m.it;return _===!1?(0,t._)`{}`:y(m,d,w)}function y(m,d,w={}){const{gen:_,it:b}=m,T=[f(b,w),g(m,w)];return v(m,d,T),_.object(...T)}function f({errorPath:m},{instancePath:d}){const w=d?(0,t.str)`${m}${(0,n.getErrorPath)(d,n.Type.Str)}`:m;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,w)]}function g({keyword:m,it:{errSchemaPath:d}},{schemaPath:w,parentSchema:_}){let b=_?d:(0,t.str)`${d}/${m}`;return w&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(w,n.Type.Str)}`),[u.schemaPath,b]}function v(m,{params:d,message:w},_){const{keyword:b,data:T,schemaValue:P,it:E}=m,{opts:Z,propertyName:U,topSchemaRef:W,schemaPath:V}=E;_.push([u.keyword,b],[u.params,typeof d=="function"?d(m):d||(0,t._)`{}`]),Z.messages&&_.push([u.message,typeof w=="function"?w(m):w]),Z.verbose&&_.push([u.schema,P],[u.parentSchema,(0,t._)`${W}${V}`],[r.default.data,T]),U&&_.push([u.propertyName,U])}}(To),Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.boolOrEmptySchema=Ur.topBoolOrEmptySchema=void 0;const Sy=To,Cy=me,$y=yn,ky={message:"boolean schema is false"};function Ty(e){const{gen:t,schema:n,validateName:r}=e;n===!1?Bd(e,!1):typeof n=="object"&&n.$async===!0?t.return($y.default.data):(t.assign((0,Cy._)`${r}.errors`,null),t.return(!0))}Ur.topBoolOrEmptySchema=Ty;function xy(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),Bd(e)):n.var(t,!0)}Ur.boolOrEmptySchema=xy;function Bd(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Sy.reportError)(o,ky,void 0,t)}var Xe={},mr={};Object.defineProperty(mr,"__esModule",{value:!0}),mr.getRules=mr.isJSONType=void 0;const Ey=["string","number","integer","boolean","null","object","array"],Iy=new Set(Ey);function Py(e){return typeof e=="string"&&Iy.has(e)}mr.isJSONType=Py;function Ry(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}mr.getRules=Ry;var Mn={};Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.shouldUseRule=Mn.shouldUseGroup=Mn.schemaHasRulesForType=void 0;function Oy({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&Hd(e,r)}Mn.schemaHasRulesForType=Oy;function Hd(e,t){return t.rules.some(n=>Jd(e,n))}Mn.shouldUseGroup=Hd;function Jd(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}Mn.shouldUseRule=Jd,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.reportTypeError=Xe.checkDataTypes=Xe.checkDataType=Xe.coerceAndCheckDataType=Xe.getJSONTypes=Xe.getSchemaTypes=Xe.DataType=void 0;const Ny=mr,Ay=Mn,My=To,pe=me,Wd=K;var qr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(qr||(Xe.DataType=qr={}));function jy(e){const t=Gd(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Xe.getSchemaTypes=jy;function Gd(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ny.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Xe.getJSONTypes=Gd;function Ly(e,t){const{gen:n,data:r,opts:o}=e,s=zy(t,o.coerceTypes),a=t.length>0&&!(s.length===0&&t.length===1&&(0,Ay.schemaHasRulesForType)(e,t[0]));if(a){const i=Ji(t,r,o.strictNumbers,qr.Wrong);n.if(i,()=>{s.length?Dy(e,t,s):Wi(e)})}return a}Xe.coerceAndCheckDataType=Ly;const Kd=new Set(["string","number","integer","boolean","null"]);function zy(e,t){return t?e.filter(n=>Kd.has(n)||t==="array"&&n==="array"):[]}function Dy(e,t,n){const{gen:r,data:o,opts:s}=e,a=r.let("dataType",(0,pe._)`typeof ${o}`),i=r.let("coerced",(0,pe._)`undefined`);s.coerceTypes==="array"&&r.if((0,pe._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,pe._)`${o}[0]`).assign(a,(0,pe._)`typeof ${o}`).if(Ji(t,o,s.strictNumbers),()=>r.assign(i,o))),r.if((0,pe._)`${i} !== undefined`);for(const c of n)(Kd.has(c)||c==="array"&&s.coerceTypes==="array")&&l(c);r.else(),Wi(e),r.endIf(),r.if((0,pe._)`${i} !== undefined`,()=>{r.assign(o,i),Zy(e,i)});function l(c){switch(c){case"string":r.elseIf((0,pe._)`${a} == "number" || ${a} == "boolean"`).assign(i,(0,pe._)`"" + ${o}`).elseIf((0,pe._)`${o} === null`).assign(i,(0,pe._)`""`);return;case"number":r.elseIf((0,pe._)`${a} == "boolean" || ${o} === null
3
+ || (${a} == "string" && ${o} && ${o} == +${o})`).assign(i,(0,pe._)`+${o}`);return;case"integer":r.elseIf((0,pe._)`${a} === "boolean" || ${o} === null
4
+ || (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(i,(0,pe._)`+${o}`);return;case"boolean":r.elseIf((0,pe._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(i,!1).elseIf((0,pe._)`${o} === "true" || ${o} === 1`).assign(i,!0);return;case"null":r.elseIf((0,pe._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(i,null);return;case"array":r.elseIf((0,pe._)`${a} === "string" || ${a} === "number"
5
+ || ${a} === "boolean" || ${o} === null`).assign(i,(0,pe._)`[${o}]`)}}}function Zy({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,pe._)`${t} !== undefined`,()=>e.assign((0,pe._)`${t}[${n}]`,r))}function Hi(e,t,n,r=qr.Correct){const o=r===qr.Correct?pe.operators.EQ:pe.operators.NEQ;let s;switch(e){case"null":return(0,pe._)`${t} ${o} null`;case"array":s=(0,pe._)`Array.isArray(${t})`;break;case"object":s=(0,pe._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a((0,pe._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return(0,pe._)`typeof ${t} ${o} ${e}`}return r===qr.Correct?s:(0,pe.not)(s);function a(i=pe.nil){return(0,pe.and)((0,pe._)`typeof ${t} == "number"`,i,n?(0,pe._)`isFinite(${t})`:pe.nil)}}Xe.checkDataType=Hi;function Ji(e,t,n,r){if(e.length===1)return Hi(e[0],t,n,r);let o;const s=(0,Wd.toHash)(e);if(s.array&&s.object){const a=(0,pe._)`typeof ${t} != "object"`;o=s.null?a:(0,pe._)`!${t} || ${a}`,delete s.null,delete s.array,delete s.object}else o=pe.nil;s.number&&delete s.integer;for(const a in s)o=(0,pe.and)(o,Hi(a,t,n,r));return o}Xe.checkDataTypes=Ji;const Uy={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,pe._)`{type: ${e}}`:(0,pe._)`{type: ${t}}`};function Wi(e){const t=qy(e);(0,My.reportError)(t,Uy)}Xe.reportTypeError=Wi;function qy(e){const{gen:t,data:n,schema:r}=e,o=(0,Wd.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var Ys={};Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.assignDefaults=void 0;const Vr=me,Vy=K;function Fy(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Yd(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Yd(e,s,o.default))}Ys.assignDefaults=Fy;function Yd(e,t,n){const{gen:r,compositeRule:o,data:s,opts:a}=e;if(n===void 0)return;const i=(0,Vr._)`${s}${(0,Vr.getProperty)(t)}`;if(o){(0,Vy.checkStrictMode)(e,`default is ignored for: ${i}`);return}let l=(0,Vr._)`${i} === undefined`;a.useDefaults==="empty"&&(l=(0,Vr._)`${l} || ${i} === null || ${i} === ""`),r.if(l,(0,Vr._)`${i} = ${(0,Vr.stringify)(n)}`)}var vn={},_e={};Object.defineProperty(_e,"__esModule",{value:!0}),_e.validateUnion=_e.validateArray=_e.usePattern=_e.callValidateCode=_e.schemaProperties=_e.allSchemaProperties=_e.noPropertyInData=_e.propertyInData=_e.isOwnProperty=_e.hasPropFunc=_e.reportMissingProp=_e.checkMissingProp=_e.checkReportMissingProp=void 0;const Fe=me,Gi=K,Wn=yn,By=K;function Hy(e,t){const{gen:n,data:r,it:o}=e;n.if(Yi(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Fe._)`${t}`},!0),e.error()})}_e.checkReportMissingProp=Hy;function Jy({gen:e,data:t,it:{opts:n}},r,o){return(0,Fe.or)(...r.map(s=>(0,Fe.and)(Yi(e,t,s,n.ownProperties),(0,Fe._)`${o} = ${s}`)))}_e.checkMissingProp=Jy;function Wy(e,t){e.setParams({missingProperty:t},!0),e.error()}_e.reportMissingProp=Wy;function Qd(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Fe._)`Object.prototype.hasOwnProperty`})}_e.hasPropFunc=Qd;function Ki(e,t,n){return(0,Fe._)`${Qd(e)}.call(${t}, ${n})`}_e.isOwnProperty=Ki;function Gy(e,t,n,r){const o=(0,Fe._)`${t}${(0,Fe.getProperty)(n)} !== undefined`;return r?(0,Fe._)`${o} && ${Ki(e,t,n)}`:o}_e.propertyInData=Gy;function Yi(e,t,n,r){const o=(0,Fe._)`${t}${(0,Fe.getProperty)(n)} === undefined`;return r?(0,Fe.or)(o,(0,Fe.not)(Ki(e,t,n))):o}_e.noPropertyInData=Yi;function Xd(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}_e.allSchemaProperties=Xd;function Ky(e,t){return Xd(t).filter(n=>!(0,Gi.alwaysValidSchema)(e,t[n]))}_e.schemaProperties=Ky;function Yy({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:a},i,l,c){const u=c?(0,Fe._)`${e}, ${t}, ${r}${o}`:t,h=[[Wn.default.instancePath,(0,Fe.strConcat)(Wn.default.instancePath,s)],[Wn.default.parentData,a.parentData],[Wn.default.parentDataProperty,a.parentDataProperty],[Wn.default.rootData,Wn.default.rootData]];a.opts.dynamicRef&&h.push([Wn.default.dynamicAnchors,Wn.default.dynamicAnchors]);const y=(0,Fe._)`${u}, ${n.object(...h)}`;return l!==Fe.nil?(0,Fe._)`${i}.call(${l}, ${y})`:(0,Fe._)`${i}(${y})`}_e.callValidateCode=Yy;const Qy=(0,Fe._)`new RegExp`;function Xy({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Fe._)`${o.code==="new RegExp"?Qy:(0,By.useFunc)(e,o)}(${n}, ${r})`})}_e.usePattern=Xy;function ev(e){const{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){const i=t.let("valid",!0);return a(()=>t.assign(i,!1)),i}return t.var(s,!0),a(()=>t.break()),s;function a(i){const l=t.const("len",(0,Fe._)`${n}.length`);t.forRange("i",0,l,c=>{e.subschema({keyword:r,dataProp:c,dataPropType:Gi.Type.Num},s),t.if((0,Fe.not)(s),i)})}}_e.validateArray=ev;function tv(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,Gi.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;const a=t.let("valid",!1),i=t.name("_valid");t.block(()=>n.forEach((l,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);t.assign(a,(0,Fe._)`${a} || ${i}`),e.mergeValidEvaluated(u,i)||t.if((0,Fe.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}_e.validateUnion=tv,Object.defineProperty(vn,"__esModule",{value:!0}),vn.validateKeywordUsage=vn.validSchemaType=vn.funcKeywordCode=vn.macroKeywordCode=void 0;const gt=me,gr=yn,nv=_e,rv=To;function ov(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:a}=e,i=t.macro.call(a.self,o,s,a),l=tp(n,r,i);a.opts.validateSchema!==!1&&a.self.validateSchema(i,!0);const c=n.name("valid");e.subschema({schema:i,schemaPath:gt.nil,errSchemaPath:`${a.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},c),e.pass(c,()=>e.error(!0))}vn.macroKeywordCode=ov;function sv(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:a,$data:i,it:l}=e;iv(l,t);const c=!i&&t.compile?t.compile.call(l.self,s,a,l):t.validate,u=tp(r,o,c),h=r.let("valid");e.block$data(h,y),e.ok((n=t.valid)!==null&&n!==void 0?n:h);function y(){if(t.errors===!1)v(),t.modifying&&ep(e),m(()=>e.error());else{const d=t.async?f():g();t.modifying&&ep(e),m(()=>av(e,d))}}function f(){const d=r.let("ruleErrs",null);return r.try(()=>v((0,gt._)`await `),w=>r.assign(h,!1).if((0,gt._)`${w} instanceof ${l.ValidationError}`,()=>r.assign(d,(0,gt._)`${w}.errors`),()=>r.throw(w))),d}function g(){const d=(0,gt._)`${u}.errors`;return r.assign(d,null),v(gt.nil),d}function v(d=t.async?(0,gt._)`await `:gt.nil){const w=l.opts.passContext?gr.default.this:gr.default.self,_=!("compile"in t&&!i||t.schema===!1);r.assign(h,(0,gt._)`${d}${(0,nv.callValidateCode)(e,u,w,_)}`,t.modifying)}function m(d){var w;r.if((0,gt.not)((w=t.valid)!==null&&w!==void 0?w:h),d)}}vn.funcKeywordCode=sv;function ep(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,gt._)`${r.parentData}[${r.parentDataProperty}]`))}function av(e,t){const{gen:n}=e;n.if((0,gt._)`Array.isArray(${t})`,()=>{n.assign(gr.default.vErrors,(0,gt._)`${gr.default.vErrors} === null ? ${t} : ${gr.default.vErrors}.concat(${t})`).assign(gr.default.errors,(0,gt._)`${gr.default.vErrors}.length`),(0,rv.extendErrors)(e)},()=>e.error())}function iv({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function tp(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,gt.stringify)(n)})}function lv(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}vn.validSchemaType=lv;function cv({schema:e,opts:t,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const a=o.dependencies;if(a!=null&&a.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))throw new Error(`parent schema must have dependencies of ${s}: ${a.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const l=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}vn.validateKeywordUsage=cv;var Gn={};Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.extendSubschemaMode=Gn.extendSubschemaData=Gn.getSubschema=void 0;const _n=me,np=K;function uv(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:a}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const i=e.schema[t];return n===void 0?{schema:i,schemaPath:(0,_n._)`${e.schemaPath}${(0,_n.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:i[n],schemaPath:(0,_n._)`${e.schemaPath}${(0,_n.getProperty)(t)}${(0,_n.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,np.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:a,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Gn.getSubschema=uv;function dv(e,t,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:a}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:i}=t;if(n!==void 0){const{errorPath:c,dataPathArr:u,opts:h}=t,y=i.let("data",(0,_n._)`${t.data}${(0,_n.getProperty)(n)}`,!0);l(y),e.errorPath=(0,_n.str)`${c}${(0,np.getErrorPath)(n,r,h.jsPropertySyntax)}`,e.parentDataProperty=(0,_n._)`${n}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){const c=o instanceof _n.Name?o:i.let("data",o,!0);l(c),a!==void 0&&(e.propertyName=a)}s&&(e.dataTypes=s);function l(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c]}}Gn.extendSubschemaData=dv;function pv(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}Gn.extendSubschemaMode=pv;var at={},rp=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var a=s[o];if(!e(t[a],n[a]))return!1}return!0}return t!==t&&n!==n},op={exports:{}},Kn=op.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Qs(t,r,o,e,"",e)};Kn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Kn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Kn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Kn.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 Qs(e,t,n,r,o,s,a,i,l,c){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,a,i,l,c);for(var u in r){var h=r[u];if(Array.isArray(h)){if(u in Kn.arrayKeywords)for(var y=0;y<h.length;y++)Qs(e,t,n,h[y],o+"/"+u+"/"+y,s,o,u,r,y)}else if(u in Kn.propsKeywords){if(h&&typeof h=="object")for(var f in h)Qs(e,t,n,h[f],o+"/"+u+"/"+fv(f),s,o,u,r,f)}else(u in Kn.keywords||e.allKeys&&!(u in Kn.skipKeywords))&&Qs(e,t,n,h,o+"/"+u,s,o,u,r)}n(r,o,s,a,i,l,c)}}function fv(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var hv=op.exports;Object.defineProperty(at,"__esModule",{value:!0}),at.getSchemaRefs=at.resolveUrl=at.normalizeId=at._getFullPath=at.getFullPath=at.inlineRef=void 0;const mv=K,gv=rp,yv=hv,vv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _v(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Qi(e):t?sp(e)<=t:!1}at.inlineRef=_v;const wv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qi(e){for(const t in e){if(wv.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(Qi)||typeof n=="object"&&Qi(n))return!0}return!1}function sp(e){let t=0;for(const n in e){if(n==="$ref")return 1/0;if(t++,!vv.has(n)&&(typeof e[n]=="object"&&(0,mv.eachItem)(e[n],r=>t+=sp(r)),t===1/0))return 1/0}return t}function ap(e,t="",n){n!==!1&&(t=Fr(t));const r=e.parse(t);return ip(e,r)}at.getFullPath=ap;function ip(e,t){return e.serialize(t).split("#")[0]+"#"}at._getFullPath=ip;const bv=/#\/?$/;function Fr(e){return e?e.replace(bv,""):""}at.normalizeId=Fr;function Sv(e,t,n){return n=Fr(n),e.resolve(t,n)}at.resolveUrl=Sv;const Cv=/^[a-z_][-a-z0-9._]*$/i;function $v(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Fr(e[n]||t),s={"":o},a=ap(r,o,!1),i={},l=new Set;return yv(e,{allKeys:!0},(h,y,f,g)=>{if(g===void 0)return;const v=a+y;let m=s[g];typeof h[n]=="string"&&(m=d.call(this,h[n])),w.call(this,h.$anchor),w.call(this,h.$dynamicAnchor),s[y]=m;function d(_){const b=this.opts.uriResolver.resolve;if(_=Fr(m?b(m,_):_),l.has(_))throw u(_);l.add(_);let T=this.refs[_];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?c(h,T.schema,_):_!==Fr(v)&&(_[0]==="#"?(c(h,i[_],_),i[_]=h):this.refs[_]=v),_}function w(_){if(typeof _=="string"){if(!Cv.test(_))throw new Error(`invalid anchor "${_}"`);d.call(this,`#${_}`)}}}),i;function c(h,y,f){if(y!==void 0&&!gv(h,y))throw u(f)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}at.getSchemaRefs=$v,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.getData=Yt.KeywordCxt=Yt.validateFunctionCode=void 0;const lp=Ur,cp=Xe,Xi=Mn,Xs=Xe,kv=Ys,Eo=vn,el=Gn,ee=me,ie=yn,Tv=at,jn=K,Io=To;function xv(e){if(fp(e)&&(hp(e),pp(e))){Pv(e);return}up(e,()=>(0,lp.topBoolOrEmptySchema)(e))}Yt.validateFunctionCode=xv;function up({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,ee._)`${ie.default.data}, ${ie.default.valCxt}`,r.$async,()=>{e.code((0,ee._)`"use strict"; ${dp(n,o)}`),Iv(e,o),e.code(s)}):e.func(t,(0,ee._)`${ie.default.data}, ${Ev(o)}`,r.$async,()=>e.code(dp(n,o)).code(s))}function Ev(e){return(0,ee._)`{${ie.default.instancePath}="", ${ie.default.parentData}, ${ie.default.parentDataProperty}, ${ie.default.rootData}=${ie.default.data}${e.dynamicRef?(0,ee._)`, ${ie.default.dynamicAnchors}={}`:ee.nil}}={}`}function Iv(e,t){e.if(ie.default.valCxt,()=>{e.var(ie.default.instancePath,(0,ee._)`${ie.default.valCxt}.${ie.default.instancePath}`),e.var(ie.default.parentData,(0,ee._)`${ie.default.valCxt}.${ie.default.parentData}`),e.var(ie.default.parentDataProperty,(0,ee._)`${ie.default.valCxt}.${ie.default.parentDataProperty}`),e.var(ie.default.rootData,(0,ee._)`${ie.default.valCxt}.${ie.default.rootData}`),t.dynamicRef&&e.var(ie.default.dynamicAnchors,(0,ee._)`${ie.default.valCxt}.${ie.default.dynamicAnchors}`)},()=>{e.var(ie.default.instancePath,(0,ee._)`""`),e.var(ie.default.parentData,(0,ee._)`undefined`),e.var(ie.default.parentDataProperty,(0,ee._)`undefined`),e.var(ie.default.rootData,ie.default.data),t.dynamicRef&&e.var(ie.default.dynamicAnchors,(0,ee._)`{}`)})}function Pv(e){const{schema:t,opts:n,gen:r}=e;up(e,()=>{n.$comment&&t.$comment&&gp(e),Mv(e),r.let(ie.default.vErrors,null),r.let(ie.default.errors,0),n.unevaluated&&Rv(e),mp(e),zv(e)})}function Rv(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,ee._)`${n}.evaluated`),t.if((0,ee._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,ee._)`${e.evaluated}.props`,(0,ee._)`undefined`)),t.if((0,ee._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,ee._)`${e.evaluated}.items`,(0,ee._)`undefined`))}function dp(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,ee._)`/*# sourceURL=${n} */`:ee.nil}function Ov(e,t){if(fp(e)&&(hp(e),pp(e))){Nv(e,t);return}(0,lp.boolOrEmptySchema)(e,t)}function pp({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function fp(e){return typeof e.schema!="boolean"}function Nv(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&gp(e),jv(e),Lv(e);const s=r.const("_errs",ie.default.errors);mp(e,s),r.var(t,(0,ee._)`${s} === ${ie.default.errors}`)}function hp(e){(0,jn.checkUnknownRules)(e),Av(e)}function mp(e,t){if(e.opts.jtd)return yp(e,[],!1,t);const n=(0,cp.getSchemaTypes)(e.schema),r=(0,cp.coerceAndCheckDataType)(e,n);yp(e,n,!r,t)}function Av(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,jn.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Mv(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,jn.checkStrictMode)(e,"default is ignored in the schema root")}function jv(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Tv.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Lv(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function gp({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,ee._)`${ie.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const a=(0,ee.str)`${r}/$comment`,i=e.scopeValue("root",{ref:t.root});e.code((0,ee._)`${ie.default.self}.opts.$comment(${s}, ${a}, ${i}.schema)`)}}function zv(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,ee._)`${ie.default.errors} === 0`,()=>t.return(ie.default.data),()=>t.throw((0,ee._)`new ${o}(${ie.default.vErrors})`)):(t.assign((0,ee._)`${r}.errors`,ie.default.vErrors),s.unevaluated&&Dv(e),t.return((0,ee._)`${ie.default.errors} === 0`))}function Dv({gen:e,evaluated:t,props:n,items:r}){n instanceof ee.Name&&e.assign((0,ee._)`${t}.props`,n),r instanceof ee.Name&&e.assign((0,ee._)`${t}.items`,r)}function yp(e,t,n,r){const{gen:o,schema:s,data:a,allErrors:i,opts:l,self:c}=e,{RULES:u}=c;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,jn.schemaHasRulesButRef)(s,u))){o.block(()=>bp(e,"$ref",u.all.$ref.definition));return}l.jtd||Zv(e,t),o.block(()=>{for(const y of u.rules)h(y);h(u.post)});function h(y){(0,Xi.shouldUseGroup)(s,y)&&(y.type?(o.if((0,Xs.checkDataType)(y.type,a,l.strictNumbers)),vp(e,y),t.length===1&&t[0]===y.type&&n&&(o.else(),(0,Xs.reportTypeError)(e)),o.endIf()):vp(e,y),i||o.if((0,ee._)`${ie.default.errors} === ${r||0}`))}}function vp(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,kv.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,Xi.shouldUseRule)(r,s)&&bp(e,s.keyword,s.definition,t.type)})}function Zv(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Uv(e,t),e.opts.allowUnionTypes||qv(e,t),Vv(e,e.dataTypes))}function Uv(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{_p(e.dataTypes,n)||tl(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),Bv(e,t)}}function qv(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&tl(e,"use allowUnionTypes to allow union type keyword")}function Vv(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,Xi.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(a=>Fv(t,a))&&tl(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function Fv(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function _p(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Bv(e,t){const n=[];for(const r of e.dataTypes)_p(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function tl(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,jn.checkStrictMode)(e,t,e.opts.strictTypes)}class wp{constructor(t,n,r){if((0,Eo.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,jn.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",Sp(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Eo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",ie.default.errors))}result(t,n,r){this.failResult((0,ee.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,ee.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:n}=this;this.fail((0,ee._)`${n} !== undefined && (${(0,ee.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?Io.reportExtraError:Io.reportError)(this,this.def.error,n)}$dataError(){(0,Io.reportError)(this,this.def.$dataError||Io.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Io.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=ee.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=ee.nil,n=ee.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:a}=this;r.if((0,ee.or)((0,ee._)`${o} === undefined`,n)),t!==ee.nil&&r.assign(t,!0),(s.length||a.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==ee.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,ee.or)(a(),i());function a(){if(r.length){if(!(n instanceof ee.Name))throw new Error("ajv implementation error");const l=Array.isArray(r)?r:[r];return(0,ee._)`${(0,Xs.checkDataTypes)(l,n,s.opts.strictNumbers,Xs.DataType.Wrong)}`}return ee.nil}function i(){if(o.validateSchema){const l=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,ee._)`!${l}(${n})`}return ee.nil}}subschema(t,n){const r=(0,el.getSubschema)(this.it,t);(0,el.extendSubschemaData)(r,this.it,t),(0,el.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return Ov(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=jn.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=jn.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,ee.Name)),!0}}Yt.KeywordCxt=wp;function bp(e,t,n,r){const o=new wp(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Eo.funcKeywordCode)(o,n):"macro"in n?(0,Eo.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Eo.funcKeywordCode)(o,n)}const Hv=/^\/(?:[^~]|~0|~1)*$/,Jv=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Sp(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return ie.default.rootData;if(e[0]==="/"){if(!Hv.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=ie.default.rootData}else{const c=Jv.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);const u=+c[1];if(o=c[2],o==="#"){if(u>=t)throw new Error(l("property/index",u));return r[t-u]}if(u>t)throw new Error(l("data",u));if(s=n[t-u],!o)return s}let a=s;const i=o.split("/");for(const c of i)c&&(s=(0,ee._)`${s}${(0,ee.getProperty)((0,jn.unescapeJsonPointer)(c))}`,a=(0,ee._)`${a} && ${s}`);return a;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${t}`}}Yt.getData=Sp;var Po={};Object.defineProperty(Po,"__esModule",{value:!0});class Wv extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}Po.default=Wv;var Br={};Object.defineProperty(Br,"__esModule",{value:!0});const nl=at;class Gv extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,nl.resolveUrl)(t,n,r),this.missingSchema=(0,nl.normalizeId)((0,nl.getFullPath)(t,this.missingRef))}}Br.default=Gv;var $t={};Object.defineProperty($t,"__esModule",{value:!0}),$t.resolveSchema=$t.getCompilingSchema=$t.resolveRef=$t.compileSchema=$t.SchemaEnv=void 0;const Qt=me,Kv=Po,yr=yn,Xt=at,Cp=K,Yv=Yt;class ea{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Xt.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}$t.SchemaEnv=ea;function rl(e){const t=$p.call(this,e);if(t)return t;const n=(0,Xt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,a=new Qt.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:Kv.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));const l=a.scopeName("validate");e.validateName=l;const c={gen:a,allErrors:this.opts.allErrors,data:yr.default.data,parentData:yr.default.parentData,parentDataProperty:yr.default.parentDataProperty,dataNames:[yr.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Qt.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Qt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(e),(0,Yv.validateFunctionCode)(c),a.optimize(this.opts.code.optimize);const h=a.toString();u=`${a.scopeRefs(yr.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,e));const f=new Function(`${yr.default.self}`,`${yr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:h,scopeValues:a._values}),this.opts.unevaluated){const{props:g,items:v}=c;f.evaluated={props:g instanceof Qt.Name?void 0:g,items:v instanceof Qt.Name?void 0:v,dynamicProps:g instanceof Qt.Name,dynamicItems:v instanceof Qt.Name},f.source&&(f.source.evaluated=(0,Qt.stringify)(f.evaluated))}return e.validate=f,e}catch(h){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(e)}}$t.compileSchema=rl;function Qv(e,t,n){var r;n=(0,Xt.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=t_.call(this,e,n);if(s===void 0){const a=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:i}=this.opts;a&&(s=new ea({schema:a,schemaId:i,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=Xv.call(this,s)}$t.resolveRef=Qv;function Xv(e){return(0,Xt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:rl.call(this,e)}function $p(e){for(const t of this._compilations)if(e_(t,e))return t}$t.getCompilingSchema=$p;function e_(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function t_(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||ta.call(this,e,t)}function ta(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Xt._getFullPath)(this.opts.uriResolver,n);let o=(0,Xt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return ol.call(this,n,e);const s=(0,Xt.normalizeId)(r),a=this.refs[s]||this.schemas[s];if(typeof a=="string"){const i=ta.call(this,e,a);return typeof(i==null?void 0:i.schema)!="object"?void 0:ol.call(this,n,i)}if(typeof(a==null?void 0:a.schema)=="object"){if(a.validate||rl.call(this,a),s===(0,Xt.normalizeId)(t)){const{schema:i}=a,{schemaId:l}=this.opts,c=i[l];return c&&(o=(0,Xt.resolveUrl)(this.opts.uriResolver,o,c)),new ea({schema:i,schemaId:l,root:e,baseId:o})}return ol.call(this,n,a)}}$t.resolveSchema=ta;const n_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ol(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const i of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const l=n[(0,Cp.unescapeFragment)(i)];if(l===void 0)return;n=l;const c=typeof n=="object"&&n[this.opts.schemaId];!n_.has(i)&&c&&(t=(0,Xt.resolveUrl)(this.opts.uriResolver,t,c))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Cp.schemaHasRulesButRef)(n,this.RULES)){const i=(0,Xt.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=ta.call(this,r,i)}const{schemaId:a}=this.opts;if(s=s||new ea({schema:n,schemaId:a,root:r,baseId:t}),s.schema!==s.root.schema)return s}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 sl={},na={exports:{}};const o_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kp=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 Tp(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const s_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function xp(e){return e.length=0,!0}function a_(e,t,n){if(e.length){const r=Tp(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function i_(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,a=!1,i=a_;for(let l=0;l<e.length;l++){const c=e[l];if(!(c==="["||c==="]"))if(c===":"){if(s===!0&&(a=!0),!i(o,r,n))break;if(++t>7){n.error=!0;break}l>0&&e[l-1]===":"&&(s=!0),r.push(":");continue}else if(c==="%"){if(!i(o,r,n))break;i=xp}else{o.push(c);continue}}return o.length&&(i===xp?n.zone=o.join(""):a?r.push(o.join("")):r.push(Tp(o))),n.address=r.join(""),n}function Ep(e){if(l_(e,":")<2)return{host:e,isIPV6:!1};const t=i_(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function l_(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function c_(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}function u_(e,t){const n=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function d_(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!kp(n)){const r=Ep(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=e.host}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var Ip={nonSimpleDomain:s_,recomposeAuthority:d_,normalizeComponentEncoding:u_,removeDotSegments:c_,isIPv4:kp,isUUID:o_,normalizeIPv6:Ep};const{isUUID:p_}=Ip,f_=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Pp(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Rp(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Op(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function h_(e){return e.secure=Pp(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function m_(e){if((e.port===(Pp(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function g_(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(f_);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=al(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function y_(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=al(o);s&&(e=s.serialize(e,t));const a=e,i=e.nss;return a.path=`${r||t.nid}:${i}`,t.skipEscape=!0,a}function v_(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!p_(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function __(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Np={scheme:"http",domainHost:!0,parse:Rp,serialize:Op},w_={scheme:"https",domainHost:Np.domainHost,parse:Rp,serialize:Op},ra={scheme:"ws",domainHost:!0,parse:h_,serialize:m_},b_={scheme:"wss",domainHost:ra.domainHost,parse:ra.parse,serialize:ra.serialize},oa={http:Np,https:w_,ws:ra,wss:b_,urn:{scheme:"urn",parse:g_,serialize:y_,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:v_,serialize:__,skipNormalize:!0}};Object.setPrototypeOf(oa,null);function al(e){return e&&(oa[e]||oa[e.toLowerCase()])||void 0}var S_={SCHEMES:oa,getSchemeHandler:al};const{normalizeIPv6:C_,removeDotSegments:Ro,recomposeAuthority:$_,normalizeComponentEncoding:sa,isIPv4:k_,nonSimpleDomain:T_}=Ip,{SCHEMES:x_,getSchemeHandler:Ap}=S_;function E_(e,t){return typeof e=="string"?e=wn(Ln(e,t),t):typeof e=="object"&&(e=Ln(wn(e,t),t)),e}function I_(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Mp(Ln(e,r),Ln(t,r),r,!0);return r.skipEscape=!0,wn(o,r)}function Mp(e,t,n,r){const o={};return r||(e=Ln(wn(e,n),n),t=Ln(wn(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Ro(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Ro(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Ro(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=Ro(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function P_(e,t,n){return typeof e=="string"?(e=unescape(e),e=wn(sa(Ln(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=wn(sa(e,!0),{...n,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=wn(sa(Ln(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=wn(sa(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function wn(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=Ap(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const a=$_(n);if(a!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(a),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let i=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(i=Ro(i)),a===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),o.push(i)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const R_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ln(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const s=e.match(R_);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(k_(r.host)===!1){const l=C_(r.host);r.host=l.host.toLowerCase(),o=l.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const a=Ap(n.scheme||r.scheme);if(!n.unicodeSupport&&(!a||!a.unicodeSupport)&&r.host&&(n.domainHost||a&&a.domainHost)&&o===!1&&T_(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(i){r.error=r.error||"Host's domain name can not be converted to ASCII: "+i}(!a||a&&!a.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),a&&a.parse&&a.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}const il={SCHEMES:x_,normalize:E_,resolve:I_,resolveComponent:Mp,equal:P_,serialize:wn,parse:Ln};na.exports=il,na.exports.default=il,na.exports.fastUri=il;var O_=na.exports;Object.defineProperty(sl,"__esModule",{value:!0});const jp=O_;jp.code='require("ajv/dist/runtime/uri").default',sl.default=jp,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Yt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=me;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=Po,o=Br,s=mr,a=$t,i=me,l=at,c=Xe,u=K,h=r_,y=sl,f=(L,x)=>new RegExp(L,x);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={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."},d={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w=200;function _(L){var x,M,R,$,k,S,z,D,ve,ce,Te,Wt,He,$e,Pe,Ge,we,nt,Rt,G,Ae,Gt,Me,Ot,Fn;const Nt=L.strict,dt=(x=L.code)===null||x===void 0?void 0:x.optimize,Kt=dt===!0||dt===void 0?1:dt||0,fr=(R=(M=L.code)===null||M===void 0?void 0:M.regExp)!==null&&R!==void 0?R:f,hr=($=L.uriResolver)!==null&&$!==void 0?$:y.default;return{strictSchema:(S=(k=L.strictSchema)!==null&&k!==void 0?k:Nt)!==null&&S!==void 0?S:!0,strictNumbers:(D=(z=L.strictNumbers)!==null&&z!==void 0?z:Nt)!==null&&D!==void 0?D:!0,strictTypes:(ce=(ve=L.strictTypes)!==null&&ve!==void 0?ve:Nt)!==null&&ce!==void 0?ce:"log",strictTuples:(Wt=(Te=L.strictTuples)!==null&&Te!==void 0?Te:Nt)!==null&&Wt!==void 0?Wt:"log",strictRequired:($e=(He=L.strictRequired)!==null&&He!==void 0?He:Nt)!==null&&$e!==void 0?$e:!1,code:L.code?{...L.code,optimize:Kt,regExp:fr}:{optimize:Kt,regExp:fr},loopRequired:(Pe=L.loopRequired)!==null&&Pe!==void 0?Pe:w,loopEnum:(Ge=L.loopEnum)!==null&&Ge!==void 0?Ge:w,meta:(we=L.meta)!==null&&we!==void 0?we:!0,messages:(nt=L.messages)!==null&&nt!==void 0?nt:!0,inlineRefs:(Rt=L.inlineRefs)!==null&&Rt!==void 0?Rt:!0,schemaId:(G=L.schemaId)!==null&&G!==void 0?G:"$id",addUsedSchema:(Ae=L.addUsedSchema)!==null&&Ae!==void 0?Ae:!0,validateSchema:(Gt=L.validateSchema)!==null&&Gt!==void 0?Gt:!0,validateFormats:(Me=L.validateFormats)!==null&&Me!==void 0?Me:!0,unicodeRegExp:(Ot=L.unicodeRegExp)!==null&&Ot!==void 0?Ot:!0,int32range:(Fn=L.int32range)!==null&&Fn!==void 0?Fn:!0,uriResolver:hr}}class b{constructor(x={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,x=this.opts={...x,..._(x)};const{es5:M,lines:R}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:M,lines:R}),this.logger=B(x.logger);const $=x.validateFormats;x.validateFormats=!1,this.RULES=(0,s.getRules)(),T.call(this,m,x,"NOT SUPPORTED"),T.call(this,d,x,"DEPRECATED","warn"),this._metaOpts=W.call(this),x.formats&&Z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),x.keywords&&U.call(this,x.keywords),typeof x.meta=="object"&&this.addMetaSchema(x.meta),E.call(this),x.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:x,meta:M,schemaId:R}=this.opts;let $=h;R==="id"&&($={...h},$.id=$.$id,delete $.$id),M&&x&&this.addMetaSchema($,$[R],!1)}defaultMeta(){const{meta:x,schemaId:M}=this.opts;return this.opts.defaultMeta=typeof x=="object"?x[M]||x:void 0}validate(x,M){let R;if(typeof x=="string"){if(R=this.getSchema(x),!R)throw new Error(`no schema with key or ref "${x}"`)}else R=this.compile(x);const $=R(M);return"$async"in R||(this.errors=R.errors),$}compile(x,M){const R=this._addSchema(x,M);return R.validate||this._compileSchemaEnv(R)}compileAsync(x,M){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:R}=this.opts;return $.call(this,x,M);async function $(ce,Te){await k.call(this,ce.$schema);const Wt=this._addSchema(ce,Te);return Wt.validate||S.call(this,Wt)}async function k(ce){ce&&!this.getSchema(ce)&&await $.call(this,{$ref:ce},!0)}async function S(ce){try{return this._compileSchemaEnv(ce)}catch(Te){if(!(Te instanceof o.default))throw Te;return z.call(this,Te),await D.call(this,Te.missingSchema),S.call(this,ce)}}function z({missingSchema:ce,missingRef:Te}){if(this.refs[ce])throw new Error(`AnySchema ${ce} is loaded but ${Te} cannot be resolved`)}async function D(ce){const Te=await ve.call(this,ce);this.refs[ce]||await k.call(this,Te.$schema),this.refs[ce]||this.addSchema(Te,ce,M)}async function ve(ce){const Te=this._loading[ce];if(Te)return Te;try{return await(this._loading[ce]=R(ce))}finally{delete this._loading[ce]}}}addSchema(x,M,R,$=this.opts.validateSchema){if(Array.isArray(x)){for(const S of x)this.addSchema(S,void 0,R,$);return this}let k;if(typeof x=="object"){const{schemaId:S}=this.opts;if(k=x[S],k!==void 0&&typeof k!="string")throw new Error(`schema ${S} must be string`)}return M=(0,l.normalizeId)(M||k),this._checkUnique(M),this.schemas[M]=this._addSchema(x,R,M,$,!0),this}addMetaSchema(x,M,R=this.opts.validateSchema){return this.addSchema(x,M,!0,R),this}validateSchema(x,M){if(typeof x=="boolean")return!0;let R;if(R=x.$schema,R!==void 0&&typeof R!="string")throw new Error("$schema must be a string");if(R=R||this.opts.defaultMeta||this.defaultMeta(),!R)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const $=this.validate(R,x);if(!$&&M){const k="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(k);else throw new Error(k)}return $}getSchema(x){let M;for(;typeof(M=P.call(this,x))=="string";)x=M;if(M===void 0){const{schemaId:R}=this.opts,$=new a.SchemaEnv({schema:{},schemaId:R});if(M=a.resolveSchema.call(this,$,x),!M)return;this.refs[x]=M}return M.validate||this._compileSchemaEnv(M)}removeSchema(x){if(x instanceof RegExp)return this._removeAllSchemas(this.schemas,x),this._removeAllSchemas(this.refs,x),this;switch(typeof x){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const M=P.call(this,x);return typeof M=="object"&&this._cache.delete(M.schema),delete this.schemas[x],delete this.refs[x],this}case"object":{const M=x;this._cache.delete(M);let R=x[this.opts.schemaId];return R&&(R=(0,l.normalizeId)(R),delete this.schemas[R],delete this.refs[R]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(x){for(const M of x)this.addKeyword(M);return this}addKeyword(x,M){let R;if(typeof x=="string")R=x,typeof M=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),M.keyword=R);else if(typeof x=="object"&&M===void 0){if(M=x,R=M.keyword,Array.isArray(R)&&!R.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(H.call(this,R,M),!M)return(0,u.eachItem)(R,k=>ue.call(this,k)),this;ae.call(this,M);const $={...M,type:(0,c.getJSONTypes)(M.type),schemaType:(0,c.getJSONTypes)(M.schemaType)};return(0,u.eachItem)(R,$.type.length===0?k=>ue.call(this,k,$):k=>$.type.forEach(S=>ue.call(this,k,$,S))),this}getKeyword(x){const M=this.RULES.all[x];return typeof M=="object"?M.definition:!!M}removeKeyword(x){const{RULES:M}=this;delete M.keywords[x],delete M.all[x];for(const R of M.rules){const $=R.rules.findIndex(k=>k.keyword===x);$>=0&&R.rules.splice($,1)}return this}addFormat(x,M){return typeof M=="string"&&(M=new RegExp(M)),this.formats[x]=M,this}errorsText(x=this.errors,{separator:M=", ",dataVar:R="data"}={}){return!x||x.length===0?"No errors":x.map($=>`${R}${$.instancePath} ${$.message}`).reduce(($,k)=>$+M+k)}$dataMetaSchema(x,M){const R=this.RULES.all;x=JSON.parse(JSON.stringify(x));for(const $ of M){const k=$.split("/").slice(1);let S=x;for(const z of k)S=S[z];for(const z in R){const D=R[z];if(typeof D!="object")continue;const{$data:ve}=D.definition,ce=S[z];ve&&ce&&(S[z]=he(ce))}}return x}_removeAllSchemas(x,M){for(const R in x){const $=x[R];(!M||M.test(R))&&(typeof $=="string"?delete x[R]:$&&!$.meta&&(this._cache.delete($.schema),delete x[R]))}}_addSchema(x,M,R,$=this.opts.validateSchema,k=this.opts.addUsedSchema){let S;const{schemaId:z}=this.opts;if(typeof x=="object")S=x[z];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof x!="boolean")throw new Error("schema must be object or boolean")}let D=this._cache.get(x);if(D!==void 0)return D;R=(0,l.normalizeId)(S||R);const ve=l.getSchemaRefs.call(this,x,R);return D=new a.SchemaEnv({schema:x,schemaId:z,meta:M,baseId:R,localRefs:ve}),this._cache.set(D.schema,D),k&&!R.startsWith("#")&&(R&&this._checkUnique(R),this.refs[R]=D),$&&this.validateSchema(x,!0),D}_checkUnique(x){if(this.schemas[x]||this.refs[x])throw new Error(`schema with key or id "${x}" already exists`)}_compileSchemaEnv(x){if(x.meta?this._compileMetaSchema(x):a.compileSchema.call(this,x),!x.validate)throw new Error("ajv implementation error");return x.validate}_compileMetaSchema(x){const M=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,x)}finally{this.opts=M}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function T(L,x,M,R="error"){for(const $ in L){const k=$;k in x&&this.logger[R](`${M}: option ${$}. ${L[k]}`)}}function P(L){return L=(0,l.normalizeId)(L),this.schemas[L]||this.refs[L]}function E(){const L=this.opts.schemas;if(L)if(Array.isArray(L))this.addSchema(L);else for(const x in L)this.addSchema(L[x],x)}function Z(){for(const L in this.opts.formats){const x=this.opts.formats[L];x&&this.addFormat(L,x)}}function U(L){if(Array.isArray(L)){this.addVocabulary(L);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const x in L){const M=L[x];M.keyword||(M.keyword=x),this.addKeyword(M)}}function W(){const L={...this.opts};for(const x of g)delete L[x];return L}const V={log(){},warn(){},error(){}};function B(L){if(L===!1)return V;if(L===void 0)return console;if(L.log&&L.warn&&L.error)return L;throw new Error("logger must implement log, warn and error methods")}const J=/^[a-z_$][a-z0-9_$:-]*$/i;function H(L,x){const{RULES:M}=this;if((0,u.eachItem)(L,R=>{if(M.keywords[R])throw new Error(`Keyword ${R} is already defined`);if(!J.test(R))throw new Error(`Keyword ${R} has invalid name`)}),!!x&&x.$data&&!("code"in x||"validate"in x))throw new Error('$data keyword must have "code" or "validate" function')}function ue(L,x,M){var R;const $=x==null?void 0:x.post;if(M&&$)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:k}=this;let S=$?k.post:k.rules.find(({type:D})=>D===M);if(S||(S={type:M,rules:[]},k.rules.push(S)),k.keywords[L]=!0,!x)return;const z={keyword:L,definition:{...x,type:(0,c.getJSONTypes)(x.type),schemaType:(0,c.getJSONTypes)(x.schemaType)}};x.before?Ce.call(this,S,z,x.before):S.rules.push(z),k.all[L]=z,(R=x.implements)===null||R===void 0||R.forEach(D=>this.addKeyword(D))}function Ce(L,x,M){const R=L.rules.findIndex($=>$.keyword===M);R>=0?L.rules.splice(R,0,x):(L.rules.push(x),this.logger.warn(`rule ${M} is not defined`))}function ae(L){let{metaSchema:x}=L;x!==void 0&&(L.$data&&this.opts.$data&&(x=he(x)),L.validateSchema=this.compile(x,!0))}const ye={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(L){return{anyOf:[L,ye]}}}(Ld);var ll={},cl={},ul={};Object.defineProperty(ul,"__esModule",{value:!0});const N_={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ul.default=N_;var vr={};Object.defineProperty(vr,"__esModule",{value:!0}),vr.callRef=vr.getValidate=void 0;const A_=Br,Lp=_e,kt=me,Hr=yn,zp=$t,aa=K,M_={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:a,opts:i,self:l}=r,{root:c}=s;if((n==="#"||n==="#/")&&o===c.baseId)return h();const u=zp.resolveRef.call(l,c,o,n);if(u===void 0)throw new A_.default(r.opts.uriResolver,o,n);if(u instanceof zp.SchemaEnv)return y(u);return f(u);function h(){if(s===c)return ia(e,a,s,s.$async);const g=t.scopeValue("root",{ref:c});return ia(e,(0,kt._)`${g}.validate`,c,c.$async)}function y(g){const v=Dp(e,g);ia(e,v,g,g.$async)}function f(g){const v=t.scopeValue("schema",i.code.source===!0?{ref:g,code:(0,kt.stringify)(g)}:{ref:g}),m=t.name("valid"),d=e.subschema({schema:g,dataTypes:[],schemaPath:kt.nil,topSchemaRef:v,errSchemaPath:n},m);e.mergeEvaluated(d),e.ok(m)}}};function Dp(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,kt._)`${n.scopeValue("wrapper",{ref:t})}.validate`}vr.getValidate=Dp;function ia(e,t,n,r){const{gen:o,it:s}=e,{allErrors:a,schemaEnv:i,opts:l}=s,c=l.passContext?Hr.default.this:kt.nil;r?u():h();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");const g=o.let("valid");o.try(()=>{o.code((0,kt._)`await ${(0,Lp.callValidateCode)(e,t,c)}`),f(t),a||o.assign(g,!0)},v=>{o.if((0,kt._)`!(${v} instanceof ${s.ValidationError})`,()=>o.throw(v)),y(v),a||o.assign(g,!1)}),e.ok(g)}function h(){e.result((0,Lp.callValidateCode)(e,t,c),()=>f(t),()=>y(t))}function y(g){const v=(0,kt._)`${g}.errors`;o.assign(Hr.default.vErrors,(0,kt._)`${Hr.default.vErrors} === null ? ${v} : ${Hr.default.vErrors}.concat(${v})`),o.assign(Hr.default.errors,(0,kt._)`${Hr.default.vErrors}.length`)}function f(g){var v;if(!s.opts.unevaluated)return;const m=(v=n==null?void 0:n.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=aa.mergeEvaluated.props(o,m.props,s.props));else{const d=o.var("props",(0,kt._)`${g}.evaluated.props`);s.props=aa.mergeEvaluated.props(o,d,s.props,kt.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=aa.mergeEvaluated.items(o,m.items,s.items));else{const d=o.var("items",(0,kt._)`${g}.evaluated.items`);s.items=aa.mergeEvaluated.items(o,d,s.items,kt.Name)}}}vr.callRef=ia,vr.default=M_,Object.defineProperty(cl,"__esModule",{value:!0});const j_=ul,L_=vr,z_=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",j_.default,L_.default];cl.default=z_;var dl={},pl={};Object.defineProperty(pl,"__esModule",{value:!0});const la=me,Yn=la.operators,ca={maximum:{okStr:"<=",ok:Yn.LTE,fail:Yn.GT},minimum:{okStr:">=",ok:Yn.GTE,fail:Yn.LT},exclusiveMaximum:{okStr:"<",ok:Yn.LT,fail:Yn.GTE},exclusiveMinimum:{okStr:">",ok:Yn.GT,fail:Yn.LTE}},D_={message:({keyword:e,schemaCode:t})=>(0,la.str)`must be ${ca[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,la._)`{comparison: ${ca[e].okStr}, limit: ${t}}`},Z_={keyword:Object.keys(ca),type:"number",schemaType:"number",$data:!0,error:D_,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,la._)`${n} ${ca[t].fail} ${r} || isNaN(${n})`)}};pl.default=Z_;var fl={};Object.defineProperty(fl,"__esModule",{value:!0});const Oo=me,U_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>(0,Oo.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Oo._)`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,a=t.let("res"),i=s?(0,Oo._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:(0,Oo._)`${a} !== parseInt(${a})`;e.fail$data((0,Oo._)`(${r} === 0 || (${a} = ${n}/${r}, ${i}))`)}};fl.default=U_;var hl={},ml={};Object.defineProperty(ml,"__esModule",{value:!0});function Zp(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}ml.default=Zp,Zp.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(hl,"__esModule",{value:!0});const _r=me,q_=K,V_=ml,F_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,_r.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,_r._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?_r.operators.GT:_r.operators.LT,a=o.opts.unicode===!1?(0,_r._)`${n}.length`:(0,_r._)`${(0,q_.useFunc)(e.gen,V_.default)}(${n})`;e.fail$data((0,_r._)`${a} ${s} ${r}`)}};hl.default=F_;var gl={};Object.defineProperty(gl,"__esModule",{value:!0});const B_=_e,ua=me,H_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>(0,ua.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,ua._)`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:r,schemaCode:o,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=n?(0,ua._)`(new RegExp(${o}, ${a}))`:(0,B_.usePattern)(e,r);e.fail$data((0,ua._)`!${i}.test(${t})`)}};gl.default=H_;var yl={};Object.defineProperty(yl,"__esModule",{value:!0});const No=me,J_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,No.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,No._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?No.operators.GT:No.operators.LT;e.fail$data((0,No._)`Object.keys(${n}).length ${o} ${r}`)}};yl.default=J_;var vl={};Object.defineProperty(vl,"__esModule",{value:!0});const Ao=_e,Mo=me,W_=K,G_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>(0,Mo.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Mo._)`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:a}=e,{opts:i}=a;if(!s&&n.length===0)return;const l=n.length>=i.loopRequired;if(a.allErrors?c():u(),i.strictRequired){const f=e.parentSchema.properties,{definedProperties:g}=e.it;for(const v of n)if((f==null?void 0:f[v])===void 0&&!g.has(v)){const m=a.schemaEnv.baseId+a.errSchemaPath,d=`required property "${v}" is not defined at "${m}" (strictRequired)`;(0,W_.checkStrictMode)(a,d,a.opts.strictRequired)}}function c(){if(l||s)e.block$data(Mo.nil,h);else for(const f of n)(0,Ao.checkReportMissingProp)(e,f)}function u(){const f=t.let("missing");if(l||s){const g=t.let("valid",!0);e.block$data(g,()=>y(f,g)),e.ok(g)}else t.if((0,Ao.checkMissingProp)(e,n,f)),(0,Ao.reportMissingProp)(e,f),t.else()}function h(){t.forOf("prop",r,f=>{e.setParams({missingProperty:f}),t.if((0,Ao.noPropertyInData)(t,o,f,i.ownProperties),()=>e.error())})}function y(f,g){e.setParams({missingProperty:f}),t.forOf(f,r,()=>{t.assign(g,(0,Ao.propertyInData)(t,o,f,i.ownProperties)),t.if((0,Mo.not)(g),()=>{e.error(),t.break()})},Mo.nil)}}};vl.default=G_;var _l={};Object.defineProperty(_l,"__esModule",{value:!0});const jo=me,K_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,jo.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,jo._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?jo.operators.GT:jo.operators.LT;e.fail$data((0,jo._)`${n}.length ${o} ${r}`)}};_l.default=K_;var wl={},Lo={};Object.defineProperty(Lo,"__esModule",{value:!0});const Up=rp;Up.code='require("ajv/dist/runtime/equal").default',Lo.default=Up,Object.defineProperty(wl,"__esModule",{value:!0});const bl=Xe,it=me,Y_=K,Q_=Lo,X_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>(0,it.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,it._)`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:a,it:i}=e;if(!r&&!o)return;const l=t.let("valid"),c=s.items?(0,bl.getSchemaTypes)(s.items):[];e.block$data(l,u,(0,it._)`${a} === false`),e.ok(l);function u(){const g=t.let("i",(0,it._)`${n}.length`),v=t.let("j");e.setParams({i:g,j:v}),t.assign(l,!0),t.if((0,it._)`${g} > 1`,()=>(h()?y:f)(g,v))}function h(){return c.length>0&&!c.some(g=>g==="object"||g==="array")}function y(g,v){const m=t.name("item"),d=(0,bl.checkDataTypes)(c,m,i.opts.strictNumbers,bl.DataType.Wrong),w=t.const("indices",(0,it._)`{}`);t.for((0,it._)`;${g}--;`,()=>{t.let(m,(0,it._)`${n}[${g}]`),t.if(d,(0,it._)`continue`),c.length>1&&t.if((0,it._)`typeof ${m} == "string"`,(0,it._)`${m} += "_"`),t.if((0,it._)`typeof ${w}[${m}] == "number"`,()=>{t.assign(v,(0,it._)`${w}[${m}]`),e.error(),t.assign(l,!1).break()}).code((0,it._)`${w}[${m}] = ${g}`)})}function f(g,v){const m=(0,Y_.useFunc)(t,Q_.default),d=t.name("outer");t.label(d).for((0,it._)`;${g}--;`,()=>t.for((0,it._)`${v} = ${g}; ${v}--;`,()=>t.if((0,it._)`${m}(${n}[${g}], ${n}[${v}])`,()=>{e.error(),t.assign(l,!1).break(d)})))}}};wl.default=X_;var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Cl=me,ew=K,tw=Lo,nw={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>(0,Cl._)`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Cl._)`!${(0,ew.useFunc)(t,tw.default)}(${n}, ${o})`):e.fail((0,Cl._)`${s} !== ${n}`)}};Sl.default=nw;var $l={};Object.defineProperty($l,"__esModule",{value:!0});const zo=me,rw=K,ow=Lo,sw={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,zo._)`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:a}=e;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const i=o.length>=a.opts.loopEnum;let l;const c=()=>l??(l=(0,rw.useFunc)(t,ow.default));let u;if(i||r)u=t.let("valid"),e.block$data(u,h);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const f=t.const("vSchema",s);u=(0,zo.or)(...o.map((g,v)=>y(f,v)))}e.pass(u);function h(){t.assign(u,!1),t.forOf("v",s,f=>t.if((0,zo._)`${c()}(${n}, ${f})`,()=>t.assign(u,!0).break()))}function y(f,g){const v=o[g];return typeof v=="object"&&v!==null?(0,zo._)`${c()}(${n}, ${f}[${g}])`:(0,zo._)`${n} === ${v}`}}};$l.default=sw,Object.defineProperty(dl,"__esModule",{value:!0});const aw=pl,iw=fl,lw=hl,cw=gl,uw=yl,dw=vl,pw=_l,fw=wl,hw=Sl,mw=$l,gw=[aw.default,iw.default,lw.default,cw.default,uw.default,dw.default,pw.default,fw.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hw.default,mw.default];dl.default=gw;var kl={},Jr={};Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.validateAdditionalItems=void 0;const wr=me,Tl=K,yw={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,wr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,wr._)`{limit: ${e}}`},code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Tl.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}qp(e,r)}};function qp(e,t){const{gen:n,schema:r,data:o,keyword:s,it:a}=e;a.items=!0;const i=n.const("len",(0,wr._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,wr._)`${i} <= ${t.length}`);else if(typeof r=="object"&&!(0,Tl.alwaysValidSchema)(a,r)){const c=n.var("valid",(0,wr._)`${i} <= ${t.length}`);n.if((0,wr.not)(c),()=>l(c)),e.ok(c)}function l(c){n.forRange("i",t.length,i,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:Tl.Type.Num},c),a.allErrors||n.if((0,wr.not)(c),()=>n.break())})}}Jr.validateAdditionalItems=qp,Jr.default=yw;var xl={},Wr={};Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.validateTuple=void 0;const Vp=me,da=K,vw=_e,_w={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Fp(e,"additionalItems",t);n.items=!0,!(0,da.alwaysValidSchema)(n,t)&&e.ok((0,vw.validateArray)(e))}};function Fp(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:a,it:i}=e;u(o),i.opts.unevaluated&&n.length&&i.items!==!0&&(i.items=da.mergeEvaluated.items(r,n.length,i.items));const l=r.name("valid"),c=r.const("len",(0,Vp._)`${s}.length`);n.forEach((h,y)=>{(0,da.alwaysValidSchema)(i,h)||(r.if((0,Vp._)`${c} > ${y}`,()=>e.subschema({keyword:a,schemaProp:y,dataProp:y},l)),e.ok(l))});function u(h){const{opts:y,errSchemaPath:f}=i,g=n.length,v=g===h.minItems&&(g===h.maxItems||h[t]===!1);if(y.strictTuples&&!v){const m=`"${a}" is ${g}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,da.checkStrictMode)(i,m,y.strictTuples)}}}Wr.validateTuple=Fp,Wr.default=_w,Object.defineProperty(xl,"__esModule",{value:!0});const ww=Wr,bw={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,ww.validateTuple)(e,"items")};xl.default=bw;var El={};Object.defineProperty(El,"__esModule",{value:!0});const Bp=me,Sw=K,Cw=_e,$w=Jr,kw={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,Bp.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Bp._)`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,Sw.alwaysValidSchema)(r,t)&&(o?(0,$w.validateAdditionalItems)(e,o):e.ok((0,Cw.validateArray)(e)))}};El.default=kw;var Il={};Object.defineProperty(Il,"__esModule",{value:!0});const qt=me,pa=K,Tw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>t===void 0?(0,qt.str)`must contain at least ${e} valid item(s)`:(0,qt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,qt._)`{minContains: ${e}}`:(0,qt._)`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let a,i;const{minContains:l,maxContains:c}=r;s.opts.next?(a=l===void 0?1:l,i=c):a=1;const u=t.const("len",(0,qt._)`${o}.length`);if(e.setParams({min:a,max:i}),i===void 0&&a===0){(0,pa.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&a>i){(0,pa.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,pa.alwaysValidSchema)(s,n)){let v=(0,qt._)`${u} >= ${a}`;i!==void 0&&(v=(0,qt._)`${v} && ${u} <= ${i}`),e.pass(v);return}s.items=!0;const h=t.name("valid");i===void 0&&a===1?f(h,()=>t.if(h,()=>t.break())):a===0?(t.let(h,!0),i!==void 0&&t.if((0,qt._)`${o}.length > 0`,y)):(t.let(h,!1),y()),e.result(h,()=>e.reset());function y(){const v=t.name("_valid"),m=t.let("count",0);f(v,()=>t.if(v,()=>g(m)))}function f(v,m){t.forRange("i",0,u,d=>{e.subschema({keyword:"contains",dataProp:d,dataPropType:pa.Type.Num,compositeRule:!0},v),m()})}function g(v){t.code((0,qt._)`${v}++`),i===void 0?t.if((0,qt._)`${v} >= ${a}`,()=>t.assign(h,!0).break()):(t.if((0,qt._)`${v} > ${i}`,()=>t.assign(h,!1).break()),a===1?t.assign(h,!0):t.if((0,qt._)`${v} >= ${a}`,()=>t.assign(h,!0)))}}};Il.default=Tw;var Hp={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=me,n=K,r=_e;e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,t.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,t._)`{property: ${l},
6
+ missingProperty: ${h},
7
7
  depsCount: ${c},
8
- deps: ${u}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=s(l);o(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const f in l){if(f==="__proto__")continue;const g=Array.isArray(l[f])?c:u;g[f]=l[f]}return[c,u]}function o(l,c=l.schema){const{gen:u,data:f,it:g}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const m in c){const v=c[m];if(v.length===0)continue;const h=(0,a.propertyInData)(u,f,m,g.opts.ownProperties);l.setParams({property:m,depsCount:v.length,deps:v.join(", ")}),g.allErrors?u.if(h,()=>{for(const p of v)(0,a.checkReportMissingProp)(l,p)}):(u.if((0,e._)`${h} && (${(0,a.checkMissingProp)(l,v,d)})`),(0,a.reportMissingProp)(l,d),u.else())}}t.validatePropertyDeps=o;function i(l,c=l.schema){const{gen:u,data:f,keyword:g,it:d}=l,m=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(d,c[v])||(u.if((0,a.propertyInData)(u,f,v,d.opts.ownProperties),()=>{const h=l.subschema({keyword:g,schemaProp:v},m);l.mergeValidEvaluated(h,m)},()=>u.var(m,!0)),l.ok(m))}t.validateSchemaDeps=i,t.default=n})(Af);var bc={};Object.defineProperty(bc,"__esModule",{value:!0});const Mf=Me,SE=ie,$E={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>(0,Mf._)`{propertyName: ${t.propertyName}}`},code(t){const{gen:e,schema:r,data:a,it:n}=t;if((0,SE.alwaysValidSchema)(n,r))return;const s=e.name("valid");e.forIn("key",a,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,Mf.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};bc.default=$E;var Go={};Object.defineProperty(Go,"__esModule",{value:!0});const Ko=je,Ir=Me,PE=Fr,Wo=ie,kE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:t})=>(0,Ir._)`{additionalProperty: ${t.additionalProperty}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,errsCount:s,it:o}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Wo.alwaysValidSchema)(o,r))return;const c=(0,Ko.allSchemaProperties)(a.properties),u=(0,Ko.allSchemaProperties)(a.patternProperties);f(),t.ok((0,Ir._)`${s} === ${PE.default.errors}`);function f(){e.forIn("key",n,h=>{!c.length&&!u.length?m(h):e.if(g(h),()=>m(h))})}function g(h){let p;if(c.length>8){const _=(0,Wo.schemaRefOrVal)(o,a.properties,"properties");p=(0,Ko.isOwnProperty)(e,_,h)}else c.length?p=(0,Ir.or)(...c.map(_=>(0,Ir._)`${h} === ${_}`)):p=Ir.nil;return u.length&&(p=(0,Ir.or)(p,...u.map(_=>(0,Ir._)`${(0,Ko.usePattern)(t,_)}.test(${h})`))),(0,Ir.not)(p)}function d(h){e.code((0,Ir._)`delete ${n}[${h}]`)}function m(h){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){d(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Wo.alwaysValidSchema)(o,r)){const p=e.name("valid");l.removeAdditional==="failing"?(v(h,p,!1),e.if((0,Ir.not)(p),()=>{t.reset(),d(h)})):(v(h,p),i||e.if((0,Ir.not)(p),()=>e.break()))}}function v(h,p,_){const w={keyword:"additionalProperties",dataProp:h,dataPropType:Wo.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,p)}}};Go.default=kE;var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});const xE=Pr,jf=je,Sc=ie,Df=Go,IE={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;s.opts.removeAdditional==="all"&&a.additionalProperties===void 0&&Df.default.code(new xE.KeywordCxt(s,Df.default,"additionalProperties"));const o=(0,jf.allSchemaProperties)(r);for(const f of o)s.definedProperties.add(f);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Sc.mergeEvaluated.props(e,(0,Sc.toHash)(o),s.props));const i=o.filter(f=>!(0,Sc.alwaysValidSchema)(s,r[f]));if(i.length===0)return;const l=e.name("valid");for(const f of i)c(f)?u(f):(e.if((0,jf.propertyInData)(e,n,f,s.opts.ownProperties)),u(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function c(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function u(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};Ec.default=IE;var $c={};Object.defineProperty($c,"__esModule",{value:!0});const Lf=je,Qo=Me,zf=ie,Uf=ie,TE={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,data:a,parentSchema:n,it:s}=t,{opts:o}=s,i=(0,Lf.allSchemaProperties)(r),l=i.filter(v=>(0,zf.alwaysValidSchema)(s,r[v]));if(i.length===0||l.length===i.length&&(!s.opts.unevaluated||s.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&n.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Qo.Name)&&(s.props=(0,Uf.evaluatedPropsToName)(e,s.props));const{props:f}=s;g();function g(){for(const v of i)c&&d(v),s.allErrors?m(v):(e.var(u,!0),m(v),e.if(u))}function d(v){for(const h in c)new RegExp(v).test(h)&&(0,zf.checkStrictMode)(s,`property ${h} matches pattern ${v} (use allowMatchingProperties)`)}function m(v){e.forIn("key",a,h=>{e.if((0,Qo._)`${(0,Lf.usePattern)(t,v)}.test(${h})`,()=>{const p=l.includes(v);p||t.subschema({keyword:"patternProperties",schemaProp:v,dataProp:h,dataPropType:Uf.Type.Str},u),s.opts.unevaluated&&f!==!0?e.assign((0,Qo._)`${f}[${h}]`,!0):!p&&!s.allErrors&&e.if((0,Qo.not)(u),()=>e.break())})})}}};$c.default=TE;var Pc={};Object.defineProperty(Pc,"__esModule",{value:!0});const CE=ie,RE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:r,it:a}=t;if((0,CE.alwaysValidSchema)(a,r)){t.fail();return}const n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Pc.default=RE;var kc={};Object.defineProperty(kc,"__esModule",{value:!0});const OE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:je.validateUnion,error:{message:"must match a schema in anyOf"}};kc.default=OE;var xc={};Object.defineProperty(xc,"__esModule",{value:!0});const Yo=Me,NE=ie,AE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Yo._)`{passingSchemas: ${t.passing}}`},code(t){const{gen:e,schema:r,parentSchema:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&a.discriminator)return;const s=r,o=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(c),t.result(o,()=>t.reset(),()=>t.error(!0));function c(){s.forEach((u,f)=>{let g;(0,NE.alwaysValidSchema)(n,u)?e.var(l,!0):g=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,Yo._)`${l} && ${o}`).assign(o,!1).assign(i,(0,Yo._)`[${i}, ${f}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(i,f),g&&t.mergeEvaluated(g,Yo.Name)})})}}};xc.default=AE;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0});const ME=ie,jE={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:r,it:a}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=e.name("valid");r.forEach((s,o)=>{if((0,ME.alwaysValidSchema)(a,s))return;const i=t.subschema({keyword:"allOf",schemaProp:o},n);t.ok(n),t.mergeEvaluated(i)})}};Ic.default=jE;var Tc={};Object.defineProperty(Tc,"__esModule",{value:!0});const Xo=Me,qf=ie,DE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>(0,Xo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Xo._)`{failingKeyword: ${t.ifClause}}`},code(t){const{gen:e,parentSchema:r,it:a}=t;r.then===void 0&&r.else===void 0&&(0,qf.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const n=Ff(a,"then"),s=Ff(a,"else");if(!n&&!s)return;const o=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),n&&s){const u=e.let("ifClause");t.setParams({ifClause:u}),e.if(i,c("then",u),c("else",u))}else n?e.if(i,c("then")):e.if((0,Xo.not)(i),c("else"));t.pass(o,()=>t.error(!0));function l(){const u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(u)}function c(u,f){return()=>{const g=t.subschema({keyword:u},i);e.assign(o,i),t.mergeValidEvaluated(g,o),f?e.assign(f,(0,Xo._)`${u}`):t.setParams({ifClause:u})}}}};function Ff(t,e){const r=t.schema[e];return r!==void 0&&!(0,qf.alwaysValidSchema)(t,r)}Tc.default=DE;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const LE=ie,zE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,LE.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Cc.default=zE,Object.defineProperty(vc,"__esModule",{value:!0});const UE=Sa,qE=yc,FE=$a,ZE=_c,VE=wc,HE=Af,BE=bc,JE=Go,GE=Ec,KE=$c,WE=Pc,QE=kc,YE=xc,XE=Ic,eS=Tc,tS=Cc;function rS(t=!1){const e=[WE.default,QE.default,YE.default,XE.default,eS.default,tS.default,BE.default,JE.default,HE.default,GE.default,KE.default];return t?e.push(qE.default,ZE.default):e.push(UE.default,FE.default),e.push(VE.default),e}vc.default=rS;var Rc={},Oc={};Object.defineProperty(Oc,"__esModule",{value:!0});const gt=Me,nS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,gt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,gt._)`{format: ${t}}`},code(t,e){const{gen:r,data:a,$data:n,schema:s,schemaCode:o,it:i}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:f}=i;if(!l.validateFormats)return;n?g():d();function g(){const m=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),v=r.const("fDef",(0,gt._)`${m}[${o}]`),h=r.let("fType"),p=r.let("format");r.if((0,gt._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>r.assign(h,(0,gt._)`${v}.type || "string"`).assign(p,(0,gt._)`${v}.validate`),()=>r.assign(h,(0,gt._)`"string"`).assign(p,v)),t.fail$data((0,gt.or)(_(),w()));function _(){return l.strictSchema===!1?gt.nil:(0,gt._)`${o} && !${p}`}function w(){const b=u.$async?(0,gt._)`(${v}.async ? await ${p}(${a}) : ${p}(${a}))`:(0,gt._)`${p}(${a})`,S=(0,gt._)`(typeof ${p} == "function" ? ${b} : ${p}.test(${a}))`;return(0,gt._)`${p} && ${p} !== true && ${h} === ${e} && !${S}`}}function d(){const m=f.formats[s];if(!m){_();return}if(m===!0)return;const[v,h,p]=w(m);v===e&&t.pass(b());function _(){if(l.strictSchema===!1){f.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function w(S){const x=S instanceof RegExp?(0,gt.regexpCode)(S):l.code.formats?(0,gt._)`${l.code.formats}${(0,gt.getProperty)(s)}`:void 0,k=r.scopeValue("formats",{key:s,ref:S,code:x});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,gt._)`${k}.validate`]:["string",S,k]}function b(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,gt._)`await ${p}(${a})`}return typeof h=="function"?(0,gt._)`${p}(${a})`:(0,gt._)`${p}.test(${a})`}}}};Oc.default=nS,Object.defineProperty(Rc,"__esModule",{value:!0});const aS=[Oc.default];Rc.default=aS;var Pa={};Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.contentVocabulary=Pa.metadataVocabulary=void 0,Pa.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Pa.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Xl,"__esModule",{value:!0});const sS=ec,oS=rc,iS=vc,lS=Rc,Zf=Pa,cS=[sS.default,oS.default,(0,iS.default)(),lS.default,Zf.metadataVocabulary,Zf.contentVocabulary];Xl.default=cS;var Nc={},ei={};Object.defineProperty(ei,"__esModule",{value:!0}),ei.DiscrError=void 0;var Vf;(function(t){t.Tag="tag",t.Mapping="mapping"})(Vf||(ei.DiscrError=Vf={})),Object.defineProperty(Nc,"__esModule",{value:!0});const ka=Me,Ac=ei,Hf=Wt,uS=ba,dS=ie,pS={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:t,tagName:e}})=>t===Ac.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ka._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},code(t){const{gen:e,data:r,schema:a,parentSchema:n,it:s}=t,{oneOf:o}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=a.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,ka._)`${r}${(0,ka.getProperty)(i)}`);e.if((0,ka._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:Ac.DiscrError.Tag,tag:c,tagName:i})),t.ok(l);function u(){const d=g();e.if(!1);for(const m in d)e.elseIf((0,ka._)`${c} === ${m}`),e.assign(l,f(d[m]));e.else(),t.error(!1,{discrError:Ac.DiscrError.Mapping,tag:c,tagName:i}),e.endIf()}function f(d){const m=e.name("valid"),v=t.subschema({keyword:"oneOf",schemaProp:d},m);return t.mergeEvaluated(v,ka.Name),m}function g(){var d;const m={},v=p(n);let h=!0;for(let b=0;b<o.length;b++){let S=o[b];if(S!=null&&S.$ref&&!(0,dS.schemaHasRulesButRef)(S,s.self.RULES)){const k=S.$ref;if(S=Hf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,k),S instanceof Hf.SchemaEnv&&(S=S.schema),S===void 0)throw new uS.default(s.opts.uriResolver,s.baseId,k)}const x=(d=S==null?void 0:S.properties)===null||d===void 0?void 0:d[i];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);h=h&&(v||p(S)),_(x,b)}if(!h)throw new Error(`discriminator: "${i}" must be required`);return m;function p({required:b}){return Array.isArray(b)&&b.includes(i)}function _(b,S){if(b.const)w(b.const,S);else if(b.enum)for(const x of b.enum)w(x,S);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function w(b,S){if(typeof b!="string"||b in m)throw new Error(`discriminator: "${i}" values must be unique strings`);m[b]=S}}}};Nc.default=pS;const fS={$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};(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=Pp,a=Xl,n=Nc,s=fS,o=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),a.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(s,o):s;this.addMetaSchema(m,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Pr;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Me;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 f=ds;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var g=ba;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return g.default}})})(Ol,Ol.exports);var hS=Ol.exports;const mS=$p(hS);var qe;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})(qe||(qe={}));var Mc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Mc||(Mc={}));const le=qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fn=t=>{switch(typeof t){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(t)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":return Array.isArray(t)?le.array:t===null?le.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?le.promise:typeof Map<"u"&&t instanceof Map?le.map:typeof Set<"u"&&t instanceof Set?le.set:typeof Date<"u"&&t instanceof Date?le.date:le.object;default:return le.unknown}},X=qe.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"]),vS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class cr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};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(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(this),a}static assert(e){if(!(e instanceof cr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,qe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}cr.create=t=>new cr(t);const xa=(t,e)=>{let r;switch(t.code){case X.invalid_type:t.received===le.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case X.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,qe.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:r=`Unrecognized key(s) in object: ${qe.joinValues(t.keys,", ")}`;break;case X.invalid_union:r="Invalid input";break;case X.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${qe.joinValues(t.options)}`;break;case X.invalid_enum_value:r=`Invalid enum value. Expected ${qe.joinValues(t.options)}, received '${t.received}'`;break;case X.invalid_arguments:r="Invalid function arguments";break;case X.invalid_return_type:r="Invalid function return type";break;case X.invalid_date:r="Invalid date";break;case X.invalid_string:typeof 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}"`:qe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case X.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 X.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 X.custom:r="Invalid input";break;case X.invalid_intersection_types:r="Intersection results could not be merged";break;case X.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case X.not_finite:r="Number must be finite";break;default:r=e.defaultError,qe.assertNever(t)}return{message:r}};let Bf=xa;function gS(t){Bf=t}function ti(){return Bf}const ri=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(c=>!!c).slice().reverse();for(const c of l)i=c(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}},yS=[];function ae(t,e){const r=ti(),a=ri({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xa?void 0:xa].filter(n=>!!n)});t.common.issues.push(a)}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 a=[];for(const n of r){if(n.status==="aborted")return be;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return Ft.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return be;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const be=Object.freeze({status:"aborted"}),Ia=t=>({status:"dirty",value:t}),Bt=t=>({status:"valid",value:t}),jc=t=>t.status==="aborted",Dc=t=>t.status==="dirty",Jn=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(he||(he={}));class Br{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Jf=(t,e)=>{if(Jn(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 cr(t.common.issues);return this._error=r,this._error}}};function Ce(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}let Oe=class{get description(){return this._def.description}_getType(e){return fn(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:fn(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:fn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(ws(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 a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fn(e)},n=this._parseSync({data:e,path:a.path,parent:a});return Jf(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fn(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return Jn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>Jn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fn(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(ws(n)?n:Promise.resolve(n));return Jf(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:X.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new Tr({schema:this,typeName:V.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 Gr.create(this,this._def)}nullable(){return kn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wn.create(this)}promise(){return Na.create(this,this._def)}or(e){return Ps.create([this,e],this._def)}and(e){return ks.create(this,e,this._def)}transform(e){return new Tr({...Ce(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Rs({...Ce(this._def),innerType:this,defaultValue:r,typeName:V.ZodDefault})}brand(){return new Uc({typeName:V.ZodBranded,type:this,...Ce(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Os({...Ce(this._def),innerType:this,catchValue:r,typeName:V.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ns.create(this,e)}readonly(){return As.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const _S=/^c[^\s-]{8,}$/i,wS=/^[0-9a-z]+$/,bS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ES=/^[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,SS=/^[a-z0-9_-]{21}$/i,$S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PS=/^[-+]?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)?)??$/,kS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Lc;const IS=/^(?:(?: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])$/,TS=/^(?:(?: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])$/,CS=/^(([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]))$/,RS=/^(([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])$/,OS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,NS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gf="((\\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])))",AS=new RegExp(`^${Gf}$`);function Kf(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 MS(t){return new RegExp(`^${Kf(t)}$`)}function Wf(t){let e=`${Gf}T${Kf(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 jS(t,e){return!!((e==="v4"||!e)&&IS.test(t)||(e==="v6"||!e)&&CS.test(t))}function DS(t,e){if(!$S.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function LS(t,e){return!!((e==="v4"||!e)&&TS.test(t)||(e==="v6"||!e)&&RS.test(t))}let Ta=class Ro extends Oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==le.string){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.string,received:s.parsedType}),be}const a=new Ft;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?ae(n,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ae(n,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")kS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"email",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Lc||(Lc=new RegExp(xS,"u")),Lc.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"emoji",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")ES.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"uuid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")SS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"nanoid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")_S.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")wS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid2",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")bS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ulid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),ae(n,{validation:"url",code:X.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"regex",code:X.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?Wf(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?AS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?MS(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?PS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"duration",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?jS(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ip",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?DS(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"jwt",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?LS(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cidr",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?OS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?NS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64url",code:X.invalid_string,message:s.message}),a.dirty()):qe.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:X.invalid_string,...he.errToObj(a)})}_addCheck(e){return new Ro({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...he.errToObj(e==null?void 0: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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...he.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...he.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...he.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...he.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...he.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...he.errToObj(r)})}nonempty(e){return this.min(1,he.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}};Ta.create=t=>new Ta({checks:[],typeName:V.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});function zS(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}let bs=class wp extends Oe{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)!==le.number){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.number,received:s.parsedType}),be}let a;const n=new Ft;for(const s of this._def.checks)s.kind==="int"?qe.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:X.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?zS(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_finite,message:s.message}),n.dirty()):qe.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,a,n){return new wp({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:he.toString(n)}]})}_addCheck(e){return new wp({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.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"&&qe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};bs.create=t=>new bs({checks:[],typeName:V.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class Pn extends Oe{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)!==le.bigint)return this._getInvalidInput(e);let a;const n=new Ft;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):qe.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return ae(r,{code:X.invalid_type,expected:le.bigint,received:r.parsedType}),be}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,a,n){return new Pn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:he.toString(n)}]})}_addCheck(e){return new Pn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.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}}Pn.create=t=>new Pn({checks:[],typeName:V.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});let Es=class extends Oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==le.boolean){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.boolean,received:a.parsedType}),be}return Bt(e.data)}};Es.create=t=>new Es({typeName:V.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class Gn extends Oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==le.date){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.date,received:s.parsedType}),be}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_date}),be}const a=new Ft;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):qe.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:he.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:he.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}}Gn.create=t=>new Gn({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:V.ZodDate,...Ce(t)});class ni extends Oe{_parse(e){if(this._getType(e)!==le.symbol){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.symbol,received:a.parsedType}),be}return Bt(e.data)}}ni.create=t=>new ni({typeName:V.ZodSymbol,...Ce(t)});class Ss extends Oe{_parse(e){if(this._getType(e)!==le.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.undefined,received:a.parsedType}),be}return Bt(e.data)}}Ss.create=t=>new Ss({typeName:V.ZodUndefined,...Ce(t)});let $s=class extends Oe{_parse(e){if(this._getType(e)!==le.null){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.null,received:a.parsedType}),be}return Bt(e.data)}};$s.create=t=>new $s({typeName:V.ZodNull,...Ce(t)});let Ca=class extends Oe{constructor(){super(...arguments),this._any=!0}_parse(e){return Bt(e.data)}};Ca.create=t=>new Ca({typeName:V.ZodAny,...Ce(t)});let Kn=class extends Oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Bt(e.data)}};Kn.create=t=>new Kn({typeName:V.ZodUnknown,...Ce(t)});let hn=class extends Oe{_parse(e){const r=this._getOrReturnCtx(e);return ae(r,{code:X.invalid_type,expected:le.never,received:r.parsedType}),be}};hn.create=t=>new hn({typeName:V.ZodNever,...Ce(t)});class ai extends Oe{_parse(e){if(this._getType(e)!==le.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.void,received:a.parsedType}),be}return Bt(e.data)}}ai.create=t=>new ai({typeName:V.ZodVoid,...Ce(t)});let Wn=class Rl extends Oe{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==le.array)return ae(r,{code:X.invalid_type,expected:le.array,received:r.parsedType}),be;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(ae(r,{code:o?X.too_big:X.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(ae(r,{code:X.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(ae(r,{code:X.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new Br(r,o,r.path,i)))).then(o=>Ft.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new Br(r,o,r.path,i)));return Ft.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new Rl({...this._def,minLength:{value:e,message:he.toString(r)}})}max(e,r){return new Rl({...this._def,maxLength:{value:e,message:he.toString(r)}})}length(e,r){return new Rl({...this._def,exactLength:{value:e,message:he.toString(r)}})}nonempty(e){return this.min(1,e)}};Wn.create=(t,e)=>new Wn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...Ce(e)});function Ra(t){if(t instanceof vr){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=Gr.create(Ra(a))}return new vr({...t._def,shape:()=>e})}else return t instanceof Wn?new Wn({...t._def,type:Ra(t.element)}):t instanceof Gr?Gr.create(Ra(t.unwrap())):t instanceof kn?kn.create(Ra(t.unwrap())):t instanceof Jr?Jr.create(t.items.map(e=>Ra(e))):t}let vr=class qr extends Oe{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=qe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==le.object){const c=this._getOrReturnCtx(e);return ae(c,{code:X.invalid_type,expected:le.object,received:c.parsedType}),be}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof hn&&this._def.unknownKeys==="strip"))for(const c in n.data)o.includes(c)||i.push(c);const l=[];for(const c of o){const u=s[c],f=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Br(n,f,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof hn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")i.length>0&&(ae(n,{code:X.unrecognized_keys,keys:i}),a.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const f=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Br(n,f,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,g=await u.value;c.push({key:f,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>Ft.mergeObjectSync(a,c)):Ft.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return he.errToObj,new qr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:he.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new qr({...this._def,unknownKeys:"strip"})}passthrough(){return new qr({...this._def,unknownKeys:"passthrough"})}extend(e){return new qr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new qr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:V.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new qr({...this._def,catchall:e})}pick(e){const r={};for(const a of qe.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new qr({...this._def,shape:()=>r})}omit(e){const r={};for(const a of qe.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new qr({...this._def,shape:()=>r})}deepPartial(){return Ra(this)}partial(e){const r={};for(const a of qe.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new qr({...this._def,shape:()=>r})}required(e){const r={};for(const a of qe.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof Gr;)s=s._def.innerType;r[a]=s}return new qr({...this._def,shape:()=>r})}keyof(){return Xf(qe.objectKeys(this.shape))}};vr.create=(t,e)=>new vr({shape:()=>t,unknownKeys:"strip",catchall:hn.create(),typeName:V.ZodObject,...Ce(e)}),vr.strictCreate=(t,e)=>new vr({shape:()=>t,unknownKeys:"strict",catchall:hn.create(),typeName:V.ZodObject,...Ce(e)}),vr.lazycreate=(t,e)=>new vr({shape:t,unknownKeys:"strip",catchall:hn.create(),typeName:V.ZodObject,...Ce(e)});let Ps=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const o=s.map(i=>new cr(i.ctx.common.issues));return ae(r,{code:X.invalid_union,unionErrors:o}),be}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new cr(l));return ae(r,{code:X.invalid_union,unionErrors:i}),be}}get options(){return this._def.options}};Ps.create=(t,e)=>new Ps({options:t,typeName:V.ZodUnion,...Ce(e)});const mn=t=>t instanceof xs?mn(t.schema):t instanceof Tr?mn(t.innerType()):t instanceof Is?[t.value]:t instanceof Ts?t.options:t instanceof Cs?qe.objectValues(t.enum):t instanceof Rs?mn(t._def.innerType):t instanceof Ss?[void 0]:t instanceof $s?[null]:t instanceof Gr?[void 0,...mn(t.unwrap())]:t instanceof kn?[null,...mn(t.unwrap())]:t instanceof Uc||t instanceof As?mn(t.unwrap()):t instanceof Os?mn(t._def.innerType):[];let Qf=class nw extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.object)return ae(r,{code:X.invalid_type,expected:le.object,received:r.parsedType}),be;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(ae(r,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=mn(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new nw({typeName:V.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...Ce(a)})}};function zc(t,e){const r=fn(t),a=fn(e);if(t===e)return{valid:!0,data:t};if(r===le.object&&a===le.object){const n=qe.objectKeys(e),s=qe.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=zc(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===le.array&&a===le.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=zc(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===le.date&&a===le.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ks=class extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(jc(s)||jc(o))return be;const i=zc(s.value,o.value);return i.valid?((Dc(s)||Dc(o))&&r.dirty(),{status:r.value,value:i.data}):(ae(a,{code:X.invalid_intersection_types}),be)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};ks.create=(t,e,r)=>new ks({left:t,right:e,typeName:V.ZodIntersection,...Ce(r)});class Jr extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.array)return ae(a,{code:X.invalid_type,expected:le.array,received:a.parsedType}),be;if(a.data.length<this._def.items.length)return ae(a,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),be;!this._def.rest&&a.data.length>this._def.items.length&&(ae(a,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Br(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>Ft.mergeArray(r,o)):Ft.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Jr({...this._def,rest:e})}}Jr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jr({items:t,typeName:V.ZodTuple,rest:null,...Ce(e)})};let Yf=class bp extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.object)return ae(a,{code:X.invalid_type,expected:le.object,received:a.parsedType}),be;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new Br(a,i,a.path,i)),value:o._parse(new Br(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Ft.mergeObjectAsync(r,n):Ft.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Oe?new bp({keyType:e,valueType:r,typeName:V.ZodRecord,...Ce(a)}):new bp({keyType:Ta.create(),valueType:e,typeName:V.ZodRecord,...Ce(r)})}};class si extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.map)return ae(a,{code:X.invalid_type,expected:le.map,received:a.parsedType}),be;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],c)=>({key:n._parse(new Br(a,i,a.path,[c,"key"])),value:s._parse(new Br(a,l,a.path,[c,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return be;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return be;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}si.create=(t,e,r)=>new si({valueType:e,keyType:t,typeName:V.ZodMap,...Ce(r)});class Qn extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.set)return ae(a,{code:X.invalid_type,expected:le.set,received:a.parsedType}),be;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(ae(a,{code:X.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(ae(a,{code:X.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return be;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...a.data.values()].map((l,c)=>s._parse(new Br(a,l,a.path,c)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new Qn({...this._def,minSize:{value:e,message:he.toString(r)}})}max(e,r){return new Qn({...this._def,maxSize:{value:e,message:he.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Qn.create=(t,e)=>new Qn({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...Ce(e)});class Oa extends Oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.function)return ae(r,{code:X.invalid_type,expected:le.function,received:r.parsedType}),be;function a(i,l){return ri({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ti(),xa].filter(c=>!!c),issueData:{code:X.invalid_arguments,argumentsError:l}})}function n(i,l){return ri({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ti(),xa].filter(c=>!!c),issueData:{code:X.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Na){const i=this;return Bt(async function(...l){const c=new cr([]),u=await i._def.args.parseAsync(l,s).catch(d=>{throw c.addIssue(a(l,d)),c}),f=await Reflect.apply(o,this,u);return await i._def.returns._def.type.parseAsync(f,s).catch(d=>{throw c.addIssue(n(f,d)),c})})}else{const i=this;return Bt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new cr([a(l,c.error)]);const u=Reflect.apply(o,this,c.data),f=i._def.returns.safeParse(u,s);if(!f.success)throw new cr([n(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Oa({...this._def,args:Jr.create(e).rest(Kn.create())})}returns(e){return new Oa({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,a){return new Oa({args:e||Jr.create([]).rest(Kn.create()),returns:r||Kn.create(),typeName:V.ZodFunction,...Ce(a)})}}let xs=class extends Oe{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})}};xs.create=(t,e)=>new xs({getter:t,typeName:V.ZodLazy,...Ce(e)});let Is=class extends Oe{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return ae(r,{received:r.data,code:X.invalid_literal,expected:this._def.value}),be}return{status:"valid",value:e.data}}get value(){return this._def.value}};Is.create=(t,e)=>new Is({value:t,typeName:V.ZodLiteral,...Ce(e)});function Xf(t,e){return new Ts({values:t,typeName:V.ZodEnum,...Ce(e)})}let Ts=class Ep extends Oe{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{expected:qe.joinValues(a),received:r.parsedType,code:X.invalid_type}),be}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{received:r.data,code:X.invalid_enum_value,options:a}),be}return Bt(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 Ep.create(e,{...this._def,...r})}exclude(e,r=this._def){return Ep.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Ts.create=Xf;class Cs extends Oe{_parse(e){const r=qe.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==le.string&&a.parsedType!==le.number){const n=qe.objectValues(r);return ae(a,{expected:qe.joinValues(n),received:a.parsedType,code:X.invalid_type}),be}if(this._cache||(this._cache=new Set(qe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=qe.objectValues(r);return ae(a,{received:a.data,code:X.invalid_enum_value,options:n}),be}return Bt(e.data)}get enum(){return this._def.values}}Cs.create=(t,e)=>new Cs({values:t,typeName:V.ZodNativeEnum,...Ce(e)});class Na extends Oe{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.promise&&r.common.async===!1)return ae(r,{code:X.invalid_type,expected:le.promise,received:r.parsedType}),be;const a=r.parsedType===le.promise?r.data:Promise.resolve(r.data);return Bt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Na.create=(t,e)=>new Na({type:t,typeName:V.ZodPromise,...Ce(e)});class Tr extends Oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{ae(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return be;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?be:l.status==="dirty"||r.value==="dirty"?Ia(l.value):l});{if(r.value==="aborted")return be;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?be:i.status==="dirty"||r.value==="dirty"?Ia(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Jn(o))return be;const i=n.transform(o.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>Jn(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):be);qe.assertNever(n)}}Tr.create=(t,e,r)=>new Tr({schema:t,typeName:V.ZodEffects,effect:e,...Ce(r)}),Tr.createWithPreprocess=(t,e,r)=>new Tr({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...Ce(r)});let Gr=class extends Oe{_parse(e){return this._getType(e)===le.undefined?Bt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gr.create=(t,e)=>new Gr({innerType:t,typeName:V.ZodOptional,...Ce(e)});let kn=class extends Oe{_parse(e){return this._getType(e)===le.null?Bt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};kn.create=(t,e)=>new kn({innerType:t,typeName:V.ZodNullable,...Ce(e)});let Rs=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===le.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Rs.create=(t,e)=>new Rs({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ce(e)});let Os=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return ws(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new cr(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new cr(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};Os.create=(t,e)=>new Os({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ce(e)});class oi extends Oe{_parse(e){if(this._getType(e)!==le.nan){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.nan,received:a.parsedType}),be}return{status:"valid",value:e.data}}}oi.create=t=>new oi({typeName:V.ZodNaN,...Ce(t)});const US=Symbol("zod_brand");class Uc extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class Ns extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?be:s.status==="dirty"?(r.dirty(),Ia(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?be:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new Ns({in:e,out:r,typeName:V.ZodPipeline})}}let As=class extends Oe{_parse(e){const r=this._def.innerType._parse(e),a=n=>(Jn(n)&&(n.value=Object.freeze(n.value)),n);return ws(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}};As.create=(t,e)=>new As({innerType:t,typeName:V.ZodReadonly,...Ce(e)});function eh(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function th(t,e={},r){return t?Ca.create().superRefine((a,n)=>{const s=t(a);if(s instanceof Promise)return s.then(o=>{if(!o){const i=eh(e,a),l=i.fatal??r??!0;n.addIssue({code:"custom",...i,fatal:l})}});if(!s){const o=eh(e,a),i=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:i})}}):Ca.create()}const qS={object:vr.lazycreate};var V;(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"})(V||(V={}));const FS=(t,e={message:`Input not instance of ${t.name}`})=>th(r=>r instanceof t,e),L=Ta.create,St=bs.create,ZS=oi.create,VS=Pn.create,yt=Es.create,HS=Gn.create,BS=ni.create,JS=Ss.create,GS=$s.create,rh=Ca.create,Aa=Kn.create,KS=hn.create,WS=ai.create,ue=Wn.create,te=vr.create,QS=vr.strictCreate,Zt=Ps.create,nh=Qf.create,YS=ks.create,XS=Jr.create,Ma=Yf.create,e$=si.create,t$=Qn.create,r$=Oa.create,n$=xs.create,xe=Is.create,Kr=Ts.create,a$=Cs.create,s$=Na.create,ah=Tr.create,Y=Gr.create,o$=kn.create,i$=Tr.createWithPreprocess,l$=Ns.create,c$=()=>L().optional(),u$=()=>St().optional(),d$=()=>yt().optional(),p$={string:t=>Ta.create({...t,coerce:!0}),number:t=>bs.create({...t,coerce:!0}),boolean:t=>Es.create({...t,coerce:!0}),bigint:t=>Pn.create({...t,coerce:!0}),date:t=>Gn.create({...t,coerce:!0})},sh=be,f$=Object.freeze(Object.defineProperty({__proto__:null,BRAND:US,DIRTY:Ia,EMPTY_PATH:yS,INVALID:be,NEVER:sh,OK:Bt,ParseStatus:Ft,Schema:Oe,ZodAny:Ca,ZodArray:Wn,ZodBigInt:Pn,ZodBoolean:Es,ZodBranded:Uc,ZodCatch:Os,ZodDate:Gn,ZodDefault:Rs,ZodDiscriminatedUnion:Qf,ZodEffects:Tr,ZodEnum:Ts,ZodError:cr,get ZodFirstPartyTypeKind(){return V},ZodFunction:Oa,ZodIntersection:ks,ZodIssueCode:X,ZodLazy:xs,ZodLiteral:Is,ZodMap:si,ZodNaN:oi,ZodNativeEnum:Cs,ZodNever:hn,ZodNull:$s,ZodNullable:kn,ZodNumber:bs,ZodObject:vr,ZodOptional:Gr,ZodParsedType:le,ZodPipeline:Ns,ZodPromise:Na,ZodReadonly:As,ZodRecord:Yf,ZodSchema:Oe,ZodSet:Qn,ZodString:Ta,ZodSymbol:ni,ZodTransformer:Tr,ZodTuple:Jr,ZodType:Oe,ZodUndefined:Ss,ZodUnion:Ps,ZodUnknown:Kn,ZodVoid:ai,addIssueToContext:ae,any:rh,array:ue,bigint:VS,boolean:yt,coerce:p$,custom:th,date:HS,datetimeRegex:Wf,defaultErrorMap:xa,discriminatedUnion:nh,effect:ah,enum:Kr,function:r$,getErrorMap:ti,getParsedType:fn,instanceof:FS,intersection:YS,isAborted:jc,isAsync:ws,isDirty:Dc,isValid:Jn,late:qS,lazy:n$,literal:xe,makeIssue:ri,map:e$,nan:ZS,nativeEnum:a$,never:KS,null:GS,nullable:o$,number:St,object:te,get objectUtil(){return Mc},oboolean:d$,onumber:u$,optional:Y,ostring:c$,pipeline:l$,preprocess:i$,promise:s$,quotelessJson:vS,record:Ma,set:t$,setErrorMap:gS,strictObject:QS,string:L,symbol:BS,transformer:ah,tuple:XS,undefined:JS,union:Zt,unknown:Aa,get util(){return qe},void:WS},Symbol.toStringTag,{value:"Module"})),Ms="2025-06-18",oh=[Ms,"2025-03-26","2024-11-05","2024-10-07"],ii="2.0",ih=Zt([L(),St().int()]),lh=L(),h$=te({progressToken:Y(ih)}).passthrough(),gr=te({_meta:Y(h$)}).passthrough(),Yt=te({method:L(),params:Y(gr)}),js=te({_meta:Y(te({}).passthrough())}).passthrough(),Wr=te({method:L(),params:Y(js)}),yr=te({_meta:Y(te({}).passthrough())}).passthrough(),li=Zt([L(),St().int()]),ch=te({jsonrpc:xe(ii),id:li}).merge(Yt).strict(),uh=t=>ch.safeParse(t).success,dh=te({jsonrpc:xe(ii)}).merge(Wr).strict(),m$=t=>dh.safeParse(t).success,ph=te({jsonrpc:xe(ii),id:li,result:yr}).strict(),qc=t=>ph.safeParse(t).success;var rt;(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"})(rt||(rt={}));const fh=te({jsonrpc:xe(ii),id:li,error:te({code:St().int(),message:L(),data:Y(Aa())})}).strict(),v$=t=>fh.safeParse(t).success,vn=Zt([ch,dh,ph,fh]),xn=yr.strict(),Fc=Wr.extend({method:xe("notifications/cancelled"),params:js.extend({requestId:li,reason:L().optional()})}),g$=te({src:L(),mimeType:Y(L()),sizes:Y(ue(L()))}).passthrough(),Ds=te({icons:ue(g$).optional()}).passthrough(),Ls=te({name:L(),title:Y(L())}).passthrough(),hh=Ls.extend({version:L(),websiteUrl:Y(L())}).merge(Ds),y$=te({experimental:Y(te({}).passthrough()),sampling:Y(te({}).passthrough()),elicitation:Y(te({}).passthrough()),roots:Y(te({listChanged:Y(yt())}).passthrough())}).passthrough(),mh=Yt.extend({method:xe("initialize"),params:gr.extend({protocolVersion:L(),capabilities:y$,clientInfo:hh})}),_$=te({experimental:Y(te({}).passthrough()),logging:Y(te({}).passthrough()),completions:Y(te({}).passthrough()),prompts:Y(te({listChanged:Y(yt())}).passthrough()),resources:Y(te({subscribe:Y(yt()),listChanged:Y(yt())}).passthrough()),tools:Y(te({listChanged:Y(yt())}).passthrough())}).passthrough(),vh=yr.extend({protocolVersion:L(),capabilities:_$,serverInfo:hh,instructions:Y(L())}),Zc=Wr.extend({method:xe("notifications/initialized")}),w$=t=>Zc.safeParse(t).success,Vc=Yt.extend({method:xe("ping")}),b$=te({progress:St(),total:Y(St()),message:Y(L())}).passthrough(),Hc=Wr.extend({method:xe("notifications/progress"),params:js.merge(b$).extend({progressToken:ih})}),ci=Yt.extend({params:gr.extend({cursor:Y(lh)}).optional()}),ui=yr.extend({nextCursor:Y(lh)}),gh=te({uri:L(),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).passthrough(),yh=gh.extend({text:L()}),Bc=L().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),_h=gh.extend({blob:Bc}),wh=Ls.extend({uri:L(),description:Y(L()),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).merge(Ds),E$=Ls.extend({uriTemplate:L(),description:Y(L()),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).merge(Ds),di=ci.extend({method:xe("resources/list")}),bh=ui.extend({resources:ue(wh)}),Jc=ci.extend({method:xe("resources/templates/list")}),Eh=ui.extend({resourceTemplates:ue(E$)}),Gc=Yt.extend({method:xe("resources/read"),params:gr.extend({uri:L()})}),Sh=yr.extend({contents:ue(Zt([yh,_h]))}),$h=Wr.extend({method:xe("notifications/resources/list_changed")}),Ph=Yt.extend({method:xe("resources/subscribe"),params:gr.extend({uri:L()})}),kh=Yt.extend({method:xe("resources/unsubscribe"),params:gr.extend({uri:L()})}),xh=Wr.extend({method:xe("notifications/resources/updated"),params:js.extend({uri:L()})}),S$=te({name:L(),description:Y(L()),required:Y(yt())}).passthrough(),$$=Ls.extend({description:Y(L()),arguments:Y(ue(S$)),_meta:Y(te({}).passthrough())}).merge(Ds),Kc=ci.extend({method:xe("prompts/list")}),Ih=ui.extend({prompts:ue($$)}),Wc=Yt.extend({method:xe("prompts/get"),params:gr.extend({name:L(),arguments:Y(Ma(L()))})}),Qc=te({type:xe("text"),text:L(),_meta:Y(te({}).passthrough())}).passthrough(),Yc=te({type:xe("image"),data:Bc,mimeType:L(),_meta:Y(te({}).passthrough())}).passthrough(),Xc=te({type:xe("audio"),data:Bc,mimeType:L(),_meta:Y(te({}).passthrough())}).passthrough(),P$=te({type:xe("resource"),resource:Zt([yh,_h]),_meta:Y(te({}).passthrough())}).passthrough(),k$=wh.extend({type:xe("resource_link")}),Th=Zt([Qc,Yc,Xc,k$,P$]),x$=te({role:Kr(["user","assistant"]),content:Th}).passthrough(),Ch=yr.extend({description:Y(L()),messages:ue(x$)}),Rh=Wr.extend({method:xe("notifications/prompts/list_changed")}),I$=te({title:Y(L()),readOnlyHint:Y(yt()),destructiveHint:Y(yt()),idempotentHint:Y(yt()),openWorldHint:Y(yt())}).passthrough(),T$=Ls.extend({description:Y(L()),inputSchema:te({type:xe("object"),properties:Y(te({}).passthrough()),required:Y(ue(L()))}).passthrough(),outputSchema:Y(te({type:xe("object"),properties:Y(te({}).passthrough()),required:Y(ue(L()))}).passthrough()),annotations:Y(I$),_meta:Y(te({}).passthrough())}).merge(Ds),eu=ci.extend({method:xe("tools/list")}),Oh=ui.extend({tools:ue(T$)}),pi=yr.extend({content:ue(Th).default([]),structuredContent:te({}).passthrough().optional(),isError:Y(yt())});pi.or(yr.extend({toolResult:Aa()}));const tu=Yt.extend({method:xe("tools/call"),params:gr.extend({name:L(),arguments:Y(Ma(Aa()))})}),Nh=Wr.extend({method:xe("notifications/tools/list_changed")}),fi=Kr(["debug","info","notice","warning","error","critical","alert","emergency"]),hi=Yt.extend({method:xe("logging/setLevel"),params:gr.extend({level:fi})}),Ah=Wr.extend({method:xe("notifications/message"),params:js.extend({level:fi,logger:Y(L()),data:Aa()})}),C$=te({name:L().optional()}).passthrough(),R$=te({hints:Y(ue(C$)),costPriority:Y(St().min(0).max(1)),speedPriority:Y(St().min(0).max(1)),intelligencePriority:Y(St().min(0).max(1))}).passthrough(),O$=te({role:Kr(["user","assistant"]),content:Zt([Qc,Yc,Xc])}).passthrough(),Mh=Yt.extend({method:xe("sampling/createMessage"),params:gr.extend({messages:ue(O$),systemPrompt:Y(L()),includeContext:Y(Kr(["none","thisServer","allServers"])),temperature:Y(St()),maxTokens:St().int(),stopSequences:Y(ue(L())),metadata:Y(te({}).passthrough()),modelPreferences:Y(R$)})}),ru=yr.extend({model:L(),stopReason:Y(Kr(["endTurn","stopSequence","maxTokens"]).or(L())),role:Kr(["user","assistant"]),content:nh("type",[Qc,Yc,Xc])}),N$=te({type:xe("boolean"),title:Y(L()),description:Y(L()),default:Y(yt())}).passthrough(),A$=te({type:xe("string"),title:Y(L()),description:Y(L()),minLength:Y(St()),maxLength:Y(St()),format:Y(Kr(["email","uri","date","date-time"]))}).passthrough(),M$=te({type:Kr(["number","integer"]),title:Y(L()),description:Y(L()),minimum:Y(St()),maximum:Y(St())}).passthrough(),j$=te({type:xe("string"),title:Y(L()),description:Y(L()),enum:ue(L()),enumNames:Y(ue(L()))}).passthrough(),D$=Zt([N$,A$,M$,j$]),jh=Yt.extend({method:xe("elicitation/create"),params:gr.extend({message:L(),requestedSchema:te({type:xe("object"),properties:Ma(L(),D$),required:Y(ue(L()))}).passthrough()})}),nu=yr.extend({action:Kr(["accept","decline","cancel"]),content:Y(Ma(L(),Aa()))}),L$=te({type:xe("ref/resource"),uri:L()}).passthrough(),z$=te({type:xe("ref/prompt"),name:L()}).passthrough(),au=Yt.extend({method:xe("completion/complete"),params:gr.extend({ref:Zt([z$,L$]),argument:te({name:L(),value:L()}).passthrough(),context:Y(te({arguments:Y(Ma(L(),L()))}))})}),Dh=yr.extend({completion:te({values:ue(L()).max(100),total:Y(St().int()),hasMore:Y(yt())}).passthrough()}),U$=te({uri:L().startsWith("file://"),name:Y(L()),_meta:Y(te({}).passthrough())}).passthrough(),Lh=Yt.extend({method:xe("roots/list")}),su=yr.extend({roots:ue(U$)}),zh=Wr.extend({method:xe("notifications/roots/list_changed")});Zt([Vc,mh,au,hi,Wc,Kc,di,Jc,Gc,Ph,kh,tu,eu]),Zt([Fc,Hc,Zc,zh]),Zt([xn,ru,nu,su]),Zt([Vc,Mh,jh,Lh]),Zt([Fc,Hc,Ah,xh,$h,Nh,Rh]),Zt([xn,vh,Dh,Ch,Ih,bh,Eh,Sh,pi,Oh]);class st extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}const q$=6e4;class Uh{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(Fc,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(Hc,r=>{this._onprogress(r)}),this.setRequestHandler(Vc,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new st(rt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});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,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,c)=>{i==null||i(l,c),qc(l)||v$(l)?this._onresponse(l):uh(l)?this._onrequest(l,c):m$(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},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 a=new st(rt.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n;const s=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler,o=this._transport;if(s===void 0){o==null||o.send({jsonrpc:"2.0",id:e.id,error:{code:rt.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const l={signal:i.signal,sessionId:o==null?void 0:o.sessionId,_meta:(n=e.params)===null||n===void 0?void 0:n._meta,sendNotification:c=>this.notification(c,{relatedRequestId:e.id}),sendRequest:(c,u,f)=>this.request(c,u,{...f,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(c=>{if(!i.signal.aborted)return o==null?void 0:o.send({result:c,jsonrpc:"2.0",id:e.id})},c=>{var u;if(!i.signal.aborted)return o==null?void 0:o.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:rt.InternalError,message:(u=c.message)!==null&&u!==void 0?u:"Internal error"}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===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),qc(e))a(e);else{const n=new st(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var c,u,f,g,d,m;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=a==null?void 0:a.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:v};a!=null&&a.onprogress&&(this._progressHandlers.set(v,a.onprogress),h.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:v}});const p=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:n,resumptionToken:s,onresumptiontoken:o}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`))),l(b)};this._responseHandlers.set(v,b=>{var S;if(!(!((S=a==null?void 0:a.signal)===null||S===void 0)&&S.aborted)){if(b instanceof Error)return l(b);try{const x=r.parse(b.result);i(x)}catch(x){l(x)}}}),(g=a==null?void 0:a.signal)===null||g===void 0||g.addEventListener("abort",()=>{var b;p((b=a==null?void 0:a.signal)===null||b===void 0?void 0:b.reason)});const _=(d=a==null?void 0:a.timeout)!==null&&d!==void 0?d:q$,w=()=>p(new st(rt.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(v,_,a==null?void 0:a.maxTotalTimeout,w,(m=a==null?void 0:a.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(h,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(b=>{this._cleanupTimeout(v),l(b)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const c={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,r).catch(u=>this._onerror(u))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}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){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function qh(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var ou={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(ss,function(r){function a(){for(var T=arguments.length,$=Array(T),C=0;C<T;C++)$[C]=arguments[C];if($.length>1){$[0]=$[0].slice(0,-1);for(var q=$.length-1,F=1;F<q;++F)$[F]=$[F].slice(1,-1);return $[q]=$[q].slice(1),$.join("")}else return $[0]}function n(T){return"(?:"+T+")"}function s(T){return T===void 0?"undefined":T===null?"null":Object.prototype.toString.call(T).split(" ").pop().split("]").shift().toLowerCase()}function o(T){return T.toUpperCase()}function i(T){return T!=null?T instanceof Array?T:typeof T.length!="number"||T.split||T.setInterval||T.call?[T]:Array.prototype.slice.call(T):[]}function l(T,$){var C=T;if($)for(var q in $)C[q]=$[q];return C}function c(T){var $="[A-Za-z]",C="[0-9]",q=a(C,"[A-Fa-f]"),F=n(n("%[EFef]"+q+"%"+q+q+"%"+q+q)+"|"+n("%[89A-Fa-f]"+q+"%"+q+q)+"|"+n("%"+q+q)),ye="[\\:\\/\\?\\#\\[\\]\\@]",_e="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Fe=a(ye,_e),it=T?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",bt=T?"[\\uE000-\\uF8FF]":"[]",Ue=a($,C,"[\\-\\.\\_\\~]",it);n($+a($,C,"[\\+\\-\\.]")+"*"),n(n(F+"|"+a(Ue,_e,"[\\:]"))+"*");var nt=n(n("25[0-5]")+"|"+n("2[0-4]"+C)+"|"+n("1"+C+C)+"|"+n("0?[1-9]"+C)+"|0?0?"+C),Et=n(nt+"\\."+nt+"\\."+nt+"\\."+nt),Ie=n(q+"{1,4}"),dt=n(n(Ie+"\\:"+Ie)+"|"+Et),It=n(n(Ie+"\\:")+"{6}"+dt),pt=n("\\:\\:"+n(Ie+"\\:")+"{5}"+dt),Un=n(n(Ie)+"?\\:\\:"+n(Ie+"\\:")+"{4}"+dt),on=n(n(n(Ie+"\\:")+"{0,1}"+Ie)+"?\\:\\:"+n(Ie+"\\:")+"{3}"+dt),ln=n(n(n(Ie+"\\:")+"{0,2}"+Ie)+"?\\:\\:"+n(Ie+"\\:")+"{2}"+dt),as=n(n(n(Ie+"\\:")+"{0,3}"+Ie)+"?\\:\\:"+Ie+"\\:"+dt),ma=n(n(n(Ie+"\\:")+"{0,4}"+Ie)+"?\\:\\:"+dt),$r=n(n(n(Ie+"\\:")+"{0,5}"+Ie)+"?\\:\\:"+Ie),cn=n(n(n(Ie+"\\:")+"{0,6}"+Ie)+"?\\:\\:"),va=n([It,pt,Un,on,ln,as,ma,$r,cn].join("|")),wn=n(n(Ue+"|"+F)+"+");n("[vV]"+q+"+\\."+a(Ue,_e,"[\\:]")+"+"),n(n(F+"|"+a(Ue,_e))+"*");var To=n(F+"|"+a(Ue,_e,"[\\:\\@]"));return n(n(F+"|"+a(Ue,_e,"[\\@]"))+"+"),n(n(To+"|"+a("[\\/\\?]",bt))+"*"),{NOT_SCHEME:new RegExp(a("[^]",$,C,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",Ue,_e),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",Ue,_e),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",Ue,_e),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",Ue,_e),"g"),NOT_QUERY:new RegExp(a("[^\\%]",Ue,_e,"[\\:\\@\\/\\?]",bt),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",Ue,_e,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",Ue,_e),"g"),UNRESERVED:new RegExp(Ue,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",Ue,Fe),"g"),PCT_ENCODED:new RegExp(F,"g"),IPV4ADDRESS:new RegExp("^("+Et+")$"),IPV6ADDRESS:new RegExp("^\\[?("+va+")"+n(n("\\%25|\\%(?!"+q+"{2})")+"("+wn+")")+"?\\]?$")}}var u=c(!1),f=c(!0),g=function(){function T($,C){var q=[],F=!0,ye=!1,_e=void 0;try{for(var Fe=$[Symbol.iterator](),it;!(F=(it=Fe.next()).done)&&(q.push(it.value),!(C&&q.length===C));F=!0);}catch(bt){ye=!0,_e=bt}finally{try{!F&&Fe.return&&Fe.return()}finally{if(ye)throw _e}}return q}return function($,C){if(Array.isArray($))return $;if(Symbol.iterator in Object($))return T($,C);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(T){if(Array.isArray(T)){for(var $=0,C=Array(T.length);$<T.length;$++)C[$]=T[$];return C}else return Array.from(T)},m=2147483647,v=36,h=1,p=26,_=38,w=700,b=72,S=128,x="-",k=/^xn--/,A=/[^\0-\x7E]/,O=/[\x2E\u3002\uFF0E\uFF61]/g,H={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},J=v-h,K=Math.floor,z=String.fromCharCode;function U(T){throw new RangeError(H[T])}function G(T,$){for(var C=[],q=T.length;q--;)C[q]=$(T[q]);return C}function se(T,$){var C=T.split("@"),q="";C.length>1&&(q=C[0]+"@",T=C[1]),T=T.replace(O,".");var F=T.split("."),ye=G(F,$).join(".");return q+ye}function ne(T){for(var $=[],C=0,q=T.length;C<q;){var F=T.charCodeAt(C++);if(F>=55296&&F<=56319&&C<q){var ye=T.charCodeAt(C++);(ye&64512)==56320?$.push(((F&1023)<<10)+(ye&1023)+65536):($.push(F),C--)}else $.push(F)}return $}var ce=function($){return String.fromCodePoint.apply(String,d($))},pe=function($){return $-48<10?$-22:$-65<26?$-65:$-97<26?$-97:v},M=function($,C){return $+22+75*($<26)-((C!=0)<<5)},R=function($,C,q){var F=0;for($=q?K($/w):$>>1,$+=K($/C);$>J*p>>1;F+=v)$=K($/J);return K(F+(J+1)*$/($+_))},D=function($){var C=[],q=$.length,F=0,ye=S,_e=b,Fe=$.lastIndexOf(x);Fe<0&&(Fe=0);for(var it=0;it<Fe;++it)$.charCodeAt(it)>=128&&U("not-basic"),C.push($.charCodeAt(it));for(var bt=Fe>0?Fe+1:0;bt<q;){for(var Ue=F,nt=1,Et=v;;Et+=v){bt>=q&&U("invalid-input");var Ie=pe($.charCodeAt(bt++));(Ie>=v||Ie>K((m-F)/nt))&&U("overflow"),F+=Ie*nt;var dt=Et<=_e?h:Et>=_e+p?p:Et-_e;if(Ie<dt)break;var It=v-dt;nt>K(m/It)&&U("overflow"),nt*=It}var pt=C.length+1;_e=R(F-Ue,pt,Ue==0),K(F/pt)>m-ye&&U("overflow"),ye+=K(F/pt),F%=pt,C.splice(F++,0,ye)}return String.fromCodePoint.apply(String,C)},N=function($){var C=[];$=ne($);var q=$.length,F=S,ye=0,_e=b,Fe=!0,it=!1,bt=void 0;try{for(var Ue=$[Symbol.iterator](),nt;!(Fe=(nt=Ue.next()).done);Fe=!0){var Et=nt.value;Et<128&&C.push(z(Et))}}catch(Co){it=!0,bt=Co}finally{try{!Fe&&Ue.return&&Ue.return()}finally{if(it)throw bt}}var Ie=C.length,dt=Ie;for(Ie&&C.push(x);dt<q;){var It=m,pt=!0,Un=!1,on=void 0;try{for(var ln=$[Symbol.iterator](),as;!(pt=(as=ln.next()).done);pt=!0){var ma=as.value;ma>=F&&ma<It&&(It=ma)}}catch(Co){Un=!0,on=Co}finally{try{!pt&&ln.return&&ln.return()}finally{if(Un)throw on}}var $r=dt+1;It-F>K((m-ye)/$r)&&U("overflow"),ye+=(It-F)*$r,F=It;var cn=!0,va=!1,wn=void 0;try{for(var To=$[Symbol.iterator](),X0;!(cn=(X0=To.next()).done);cn=!0){var ew=X0.value;if(ew<F&&++ye>m&&U("overflow"),ew==F){for(var Il=ye,Tl=v;;Tl+=v){var Cl=Tl<=_e?h:Tl>=_e+p?p:Tl-_e;if(Il<Cl)break;var tw=Il-Cl,rw=v-Cl;C.push(z(M(Cl+tw%rw,0))),Il=K(tw/rw)}C.push(z(M(Il,0))),_e=R(ye,$r,dt==Ie),ye=0,++dt}}}catch(Co){va=!0,wn=Co}finally{try{!cn&&To.return&&To.return()}finally{if(va)throw wn}}++ye,++F}return C.join("")},y=function($){return se($,function(C){return k.test(C)?D(C.slice(4).toLowerCase()):C})},P=function($){return se($,function(C){return A.test(C)?"xn--"+N(C):C})},j={version:"2.1.0",ucs2:{decode:ne,encode:ce},decode:D,encode:N,toASCII:P,toUnicode:y},Q={};function ee(T){var $=T.charCodeAt(0),C=void 0;return $<16?C="%0"+$.toString(16).toUpperCase():$<128?C="%"+$.toString(16).toUpperCase():$<2048?C="%"+($>>6|192).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase():C="%"+($>>12|224).toString(16).toUpperCase()+"%"+($>>6&63|128).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase(),C}function Se(T){for(var $="",C=0,q=T.length;C<q;){var F=parseInt(T.substr(C+1,2),16);if(F<128)$+=String.fromCharCode(F),C+=3;else if(F>=194&&F<224){if(q-C>=6){var ye=parseInt(T.substr(C+4,2),16);$+=String.fromCharCode((F&31)<<6|ye&63)}else $+=T.substr(C,6);C+=6}else if(F>=224){if(q-C>=9){var _e=parseInt(T.substr(C+4,2),16),Fe=parseInt(T.substr(C+7,2),16);$+=String.fromCharCode((F&15)<<12|(_e&63)<<6|Fe&63)}else $+=T.substr(C,9);C+=9}else $+=T.substr(C,3),C+=3}return $}function de(T,$){function C(q){var F=Se(q);return F.match($.UNRESERVED)?F:q}return T.scheme&&(T.scheme=String(T.scheme).replace($.PCT_ENCODED,C).toLowerCase().replace($.NOT_SCHEME,"")),T.userinfo!==void 0&&(T.userinfo=String(T.userinfo).replace($.PCT_ENCODED,C).replace($.NOT_USERINFO,ee).replace($.PCT_ENCODED,o)),T.host!==void 0&&(T.host=String(T.host).replace($.PCT_ENCODED,C).toLowerCase().replace($.NOT_HOST,ee).replace($.PCT_ENCODED,o)),T.path!==void 0&&(T.path=String(T.path).replace($.PCT_ENCODED,C).replace(T.scheme?$.NOT_PATH:$.NOT_PATH_NOSCHEME,ee).replace($.PCT_ENCODED,o)),T.query!==void 0&&(T.query=String(T.query).replace($.PCT_ENCODED,C).replace($.NOT_QUERY,ee).replace($.PCT_ENCODED,o)),T.fragment!==void 0&&(T.fragment=String(T.fragment).replace($.PCT_ENCODED,C).replace($.NOT_FRAGMENT,ee).replace($.PCT_ENCODED,o)),T}function ge(T){return T.replace(/^0*(.*)/,"$1")||"0"}function vt(T,$){var C=T.match($.IPV4ADDRESS)||[],q=g(C,2),F=q[1];return F?F.split(".").map(ge).join("."):T}function Te(T,$){var C=T.match($.IPV6ADDRESS)||[],q=g(C,3),F=q[1],ye=q[2];if(F){for(var _e=F.toLowerCase().split("::").reverse(),Fe=g(_e,2),it=Fe[0],bt=Fe[1],Ue=bt?bt.split(":").map(ge):[],nt=it.split(":").map(ge),Et=$.IPV4ADDRESS.test(nt[nt.length-1]),Ie=Et?7:8,dt=nt.length-Ie,It=Array(Ie),pt=0;pt<Ie;++pt)It[pt]=Ue[pt]||nt[dt+pt]||"";Et&&(It[Ie-1]=vt(It[Ie-1],$));var Un=It.reduce(function($r,cn,va){if(!cn||cn==="0"){var wn=$r[$r.length-1];wn&&wn.index+wn.length===va?wn.length++:$r.push({index:va,length:1})}return $r},[]),on=Un.sort(function($r,cn){return cn.length-$r.length})[0],ln=void 0;if(on&&on.length>1){var as=It.slice(0,on.index),ma=It.slice(on.index+on.length);ln=as.join(":")+"::"+ma.join(":")}else ln=It.join(":");return ye&&(ln+="%"+ye),ln}else return T}var me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ne="".match(/(){0}/)[1]===void 0;function Ae(T){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C={},q=$.iri!==!1?f:u;$.reference==="suffix"&&(T=($.scheme?$.scheme+":":"")+"//"+T);var F=T.match(me);if(F){Ne?(C.scheme=F[1],C.userinfo=F[3],C.host=F[4],C.port=parseInt(F[5],10),C.path=F[6]||"",C.query=F[7],C.fragment=F[8],isNaN(C.port)&&(C.port=F[5])):(C.scheme=F[1]||void 0,C.userinfo=T.indexOf("@")!==-1?F[3]:void 0,C.host=T.indexOf("//")!==-1?F[4]:void 0,C.port=parseInt(F[5],10),C.path=F[6]||"",C.query=T.indexOf("?")!==-1?F[7]:void 0,C.fragment=T.indexOf("#")!==-1?F[8]:void 0,isNaN(C.port)&&(C.port=T.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?F[4]:void 0)),C.host&&(C.host=Te(vt(C.host,q),q)),C.scheme===void 0&&C.userinfo===void 0&&C.host===void 0&&C.port===void 0&&!C.path&&C.query===void 0?C.reference="same-document":C.scheme===void 0?C.reference="relative":C.fragment===void 0?C.reference="absolute":C.reference="uri",$.reference&&$.reference!=="suffix"&&$.reference!==C.reference&&(C.error=C.error||"URI is not a "+$.reference+" reference.");var ye=Q[($.scheme||C.scheme||"").toLowerCase()];if(!$.unicodeSupport&&(!ye||!ye.unicodeSupport)){if(C.host&&($.domainHost||ye&&ye.domainHost))try{C.host=j.toASCII(C.host.replace(q.PCT_ENCODED,Se).toLowerCase())}catch(_e){C.error=C.error||"Host's domain name can not be converted to ASCII via punycode: "+_e}de(C,u)}else de(C,q);ye&&ye.parse&&ye.parse(C,$)}else C.error=C.error||"URI can not be parsed.";return C}function ke(T,$){var C=$.iri!==!1?f:u,q=[];return T.userinfo!==void 0&&(q.push(T.userinfo),q.push("@")),T.host!==void 0&&q.push(Te(vt(String(T.host),C),C).replace(C.IPV6ADDRESS,function(F,ye,_e){return"["+ye+(_e?"%25"+_e:"")+"]"})),(typeof T.port=="number"||typeof T.port=="string")&&(q.push(":"),q.push(String(T.port))),q.length?q.join(""):void 0}var tt=/^\.\.?\//,Ve=/^\/\.(\/|$)/,re=/^\/\.\.(\/|$)/,ze=/^\/?(?:.|\n)*?(?=\/|$)/;function Be(T){for(var $=[];T.length;)if(T.match(tt))T=T.replace(tt,"");else if(T.match(Ve))T=T.replace(Ve,"/");else if(T.match(re))T=T.replace(re,"/"),$.pop();else if(T==="."||T==="..")T="";else{var C=T.match(ze);if(C){var q=C[0];T=T.slice(q.length),$.push(q)}else throw new Error("Unexpected dot segment condition")}return $.join("")}function Ee(T){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C=$.iri?f:u,q=[],F=Q[($.scheme||T.scheme||"").toLowerCase()];if(F&&F.serialize&&F.serialize(T,$),T.host&&!C.IPV6ADDRESS.test(T.host)){if($.domainHost||F&&F.domainHost)try{T.host=$.iri?j.toUnicode(T.host):j.toASCII(T.host.replace(C.PCT_ENCODED,Se).toLowerCase())}catch(Fe){T.error=T.error||"Host's domain name can not be converted to "+($.iri?"Unicode":"ASCII")+" via punycode: "+Fe}}de(T,C),$.reference!=="suffix"&&T.scheme&&(q.push(T.scheme),q.push(":"));var ye=ke(T,$);if(ye!==void 0&&($.reference!=="suffix"&&q.push("//"),q.push(ye),T.path&&T.path.charAt(0)!=="/"&&q.push("/")),T.path!==void 0){var _e=T.path;!$.absolutePath&&(!F||!F.absolutePath)&&(_e=Be(_e)),ye===void 0&&(_e=_e.replace(/^\/\//,"/%2F")),q.push(_e)}return T.query!==void 0&&(q.push("?"),q.push(T.query)),T.fragment!==void 0&&(q.push("#"),q.push(T.fragment)),q.join("")}function Qe(T,$){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},q=arguments[3],F={};return q||(T=Ae(Ee(T,C),C),$=Ae(Ee($,C),C)),C=C||{},!C.tolerant&&$.scheme?(F.scheme=$.scheme,F.userinfo=$.userinfo,F.host=$.host,F.port=$.port,F.path=Be($.path||""),F.query=$.query):($.userinfo!==void 0||$.host!==void 0||$.port!==void 0?(F.userinfo=$.userinfo,F.host=$.host,F.port=$.port,F.path=Be($.path||""),F.query=$.query):($.path?($.path.charAt(0)==="/"?F.path=Be($.path):((T.userinfo!==void 0||T.host!==void 0||T.port!==void 0)&&!T.path?F.path="/"+$.path:T.path?F.path=T.path.slice(0,T.path.lastIndexOf("/")+1)+$.path:F.path=$.path,F.path=Be(F.path)),F.query=$.query):(F.path=T.path,$.query!==void 0?F.query=$.query:F.query=T.query),F.userinfo=T.userinfo,F.host=T.host,F.port=T.port),F.scheme=T.scheme),F.fragment=$.fragment,F}function or(T,$,C){var q=l({scheme:"null"},C);return Ee(Qe(Ae(T,q),Ae($,q),q,!0),q)}function At(T,$){return typeof T=="string"?T=Ee(Ae(T,$),$):s(T)==="object"&&(T=Ae(Ee(T,$),$)),T}function wt(T,$,C){return typeof T=="string"?T=Ee(Ae(T,C),C):s(T)==="object"&&(T=Ee(T,C)),typeof $=="string"?$=Ee(Ae($,C),C):s($)==="object"&&($=Ee($,C)),T===$}function ir(T,$){return T&&T.toString().replace(!$||!$.iri?u.ESCAPE:f.ESCAPE,ee)}function Mt(T,$){return T&&T.toString().replace(!$||!$.iri?u.PCT_ENCODED:f.PCT_ENCODED,Se)}var lr={scheme:"http",domainHost:!0,parse:function($,C){return $.host||($.error=$.error||"HTTP URIs must have a host."),$},serialize:function($,C){var q=String($.scheme).toLowerCase()==="https";return($.port===(q?443:80)||$.port==="")&&($.port=void 0),$.path||($.path="/"),$}},_n={scheme:"https",domainHost:lr.domainHost,parse:lr.parse,serialize:lr.serialize};function pa(T){return typeof T.secure=="boolean"?T.secure:String(T.scheme).toLowerCase()==="wss"}var ut={scheme:"ws",domainHost:!0,parse:function($,C){var q=$;return q.secure=pa(q),q.resourceName=(q.path||"/")+(q.query?"?"+q.query:""),q.path=void 0,q.query=void 0,q},serialize:function($,C){if(($.port===(pa($)?443:80)||$.port==="")&&($.port=void 0),typeof $.secure=="boolean"&&($.scheme=$.secure?"wss":"ws",$.secure=void 0),$.resourceName){var q=$.resourceName.split("?"),F=g(q,2),ye=F[0],_e=F[1];$.path=ye&&ye!=="/"?ye:void 0,$.query=_e,$.resourceName=void 0}return $.fragment=void 0,$}},br={scheme:"wss",domainHost:ut.domainHost,parse:ut.parse,serialize:ut.serialize},Ur={},So="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Er="[0-9A-Fa-f]",_p=n(n("%[EFef]"+Er+"%"+Er+Er+"%"+Er+Er)+"|"+n("%[89A-Fa-f]"+Er+"%"+Er+Er)+"|"+n("%"+Er+Er)),rs="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",$o="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Po=a($o,'[\\"\\\\]'),ko="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Ln=new RegExp(So,"g"),jt=new RegExp(_p,"g"),xo=new RegExp(a("[^]",rs,"[\\.]",'[\\"]',Po),"g"),Io=new RegExp(a("[^]",So,ko),"g"),Sr=Io;function ns(T){var $=Se(T);return $.match(Ln)?$:T}var we={scheme:"mailto",parse:function($,C){var q=$,F=q.to=q.path?q.path.split(","):[];if(q.path=void 0,q.query){for(var ye=!1,_e={},Fe=q.query.split("&"),it=0,bt=Fe.length;it<bt;++it){var Ue=Fe[it].split("=");switch(Ue[0]){case"to":for(var nt=Ue[1].split(","),Et=0,Ie=nt.length;Et<Ie;++Et)F.push(nt[Et]);break;case"subject":q.subject=Mt(Ue[1],C);break;case"body":q.body=Mt(Ue[1],C);break;default:ye=!0,_e[Mt(Ue[0],C)]=Mt(Ue[1],C);break}}ye&&(q.headers=_e)}q.query=void 0;for(var dt=0,It=F.length;dt<It;++dt){var pt=F[dt].split("@");if(pt[0]=Mt(pt[0]),C.unicodeSupport)pt[1]=Mt(pt[1],C).toLowerCase();else try{pt[1]=j.toASCII(Mt(pt[1],C).toLowerCase())}catch(Un){q.error=q.error||"Email address's domain name can not be converted to ASCII via punycode: "+Un}F[dt]=pt.join("@")}return q},serialize:function($,C){var q=$,F=i($.to);if(F){for(var ye=0,_e=F.length;ye<_e;++ye){var Fe=String(F[ye]),it=Fe.lastIndexOf("@"),bt=Fe.slice(0,it).replace(jt,ns).replace(jt,o).replace(xo,ee),Ue=Fe.slice(it+1);try{Ue=C.iri?j.toUnicode(Ue):j.toASCII(Mt(Ue,C).toLowerCase())}catch(dt){q.error=q.error||"Email address's domain name can not be converted to "+(C.iri?"Unicode":"ASCII")+" via punycode: "+dt}F[ye]=bt+"@"+Ue}q.path=F.join(",")}var nt=$.headers=$.headers||{};$.subject&&(nt.subject=$.subject),$.body&&(nt.body=$.body);var Et=[];for(var Ie in nt)nt[Ie]!==Ur[Ie]&&Et.push(Ie.replace(jt,ns).replace(jt,o).replace(Io,ee)+"="+nt[Ie].replace(jt,ns).replace(jt,o).replace(Sr,ee));return Et.length&&(q.query=Et.join("&")),q}},Ot=/^([^\:]+)\:(.*)/,zn={scheme:"urn",parse:function($,C){var q=$.path&&$.path.match(Ot),F=$;if(q){var ye=C.scheme||F.scheme||"urn",_e=q[1].toLowerCase(),Fe=q[2],it=ye+":"+(C.nid||_e),bt=Q[it];F.nid=_e,F.nss=Fe,F.path=void 0,bt&&(F=bt.parse(F,C))}else F.error=F.error||"URN can not be parsed.";return F},serialize:function($,C){var q=C.scheme||$.scheme||"urn",F=$.nid,ye=q+":"+(C.nid||F),_e=Q[ye];_e&&($=_e.serialize($,C));var Fe=$,it=$.nss;return Fe.path=(F||C.nid)+":"+it,Fe}},fa=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ha={scheme:"urn:uuid",parse:function($,C){var q=$;return q.uuid=q.nss,q.nss=void 0,!C.tolerant&&(!q.uuid||!q.uuid.match(fa))&&(q.error=q.error||"UUID is not valid."),q},serialize:function($,C){var q=$;return q.nss=($.uuid||"").toLowerCase(),q}};Q[lr.scheme]=lr,Q[_n.scheme]=_n,Q[ut.scheme]=ut,Q[br.scheme]=br,Q[we.scheme]=we,Q[zn.scheme]=zn,Q[ha.scheme]=ha,r.SCHEMES=Q,r.pctEncChar=ee,r.pctDecChars=Se,r.parse=Ae,r.removeDotSegments=Be,r.serialize=Ee,r.resolveComponents=Qe,r.resolve=or,r.normalize=At,r.equal=wt,r.escapeComponent=ir,r.unescapeComponent=Mt,Object.defineProperty(r,"__esModule",{value:!0})})})(ou,ou.exports);var F$=ou.exports,Z$=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},ja={copy:V$,checkDataType:iu,checkDataTypes:H$,coerceToTypes:B$,toHash:lu,getProperty:cu,escapeQuotes:uu,equal:ls,ucs2length:Z$,varOccurences:K$,varReplace:W$,schemaHasRules:Q$,schemaHasRulesExcept:Y$,schemaUnknownRules:X$,toQuotedString:du,getPathExpr:eP,getPath:tP,getData:aP,unescapeFragment:sP,unescapeJsonPointer:fu,escapeFragment:oP,escapeJsonPointer:pu};function V$(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function iu(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function H$(t,e,r){switch(t.length){case 1:return iu(t[0],e,r,!0);default:var a="",n=lu(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+iu(s,e,r,!0);return a}}var Fh=lu(["string","number","integer","boolean","null"]);function B$(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(Fh[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(Fh[e])return[e];if(t==="array"&&e==="array")return["array"]}}function lu(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var J$=/^[a-z$_][a-z$_0-9]*$/i,G$=/'|\\/g;function cu(t){return typeof t=="number"?"["+t+"]":J$.test(t)?"."+t:"['"+uu(t)+"']"}function uu(t){return t.replace(G$,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function K$(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function W$(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function Q$(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function Y$(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function X$(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function du(t){return"'"+uu(t)+"'"}function eP(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Zh(t,n)}function tP(t,e,r){var a=du(r?"/"+pu(e):cu(e));return Zh(t,a)}var rP=/^\/(?:[^~]|~0|~1)*$/,nP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function aP(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!rP.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(nP),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),c=0;c<l.length;c++){var u=l[c];u&&(s+=cu(fu(u)),i+=" && "+s)}return i}function Zh(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function sP(t){return fu(decodeURIComponent(t))}function oP(t){return encodeURIComponent(pu(t))}function pu(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function fu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var iP=ja,Vh=lP;function lP(t){iP.copy(t,this)}var Hh={exports:{}},In=Hh.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};mi(e,a,n,t,"",t)};In.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},In.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},In.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},In.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 mi(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var f=a[u];if(Array.isArray(f)){if(u in In.arrayKeywords)for(var g=0;g<f.length;g++)mi(t,e,r,f[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in In.propsKeywords){if(f&&typeof f=="object")for(var d in f)mi(t,e,r,f[d],n+"/"+u+"/"+cP(d),s,n,u,a,d)}else(u in In.keywords||t.allKeys&&!(u in In.skipKeywords))&&mi(t,e,r,f,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function cP(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var uP=Hh.exports,zs=F$,Bh=ls,vi=ja,gi=Vh,dP=uP,hu=Tn;Tn.normalizeId=Cn,Tn.fullPath=_i,Tn.url=wi,Tn.ids=vP,Tn.inlineRef=mu,Tn.schema=yi;function Tn(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Tn.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof gi)return mu(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=yi.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof gi?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=mu(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function yi(t,e){var r=zs.parse(e),a=Gh(r),n=_i(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=Cn(a),o=this._refs[s];if(typeof o=="string")return pP.call(this,t,o,r);if(o instanceof gi)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof gi){if(o.validate||this._compile(o),s==Cn(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=_i(this._getId(t.schema))}return Jh.call(this,r,n,t.schema,t)}function pP(t,e,r){var a=yi.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=wi(s,o)),Jh.call(this,r,s,n,t)}}var fP=vi.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Jh(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=vi.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!fP[o]&&(i=this._getId(r),i&&(e=wi(e,i)),r.$ref)){var l=wi(e,r.$ref),c=yi.call(this,a,l);c&&(r=c.schema,a=c.root,e=c.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var hP=vi.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function mu(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return vu(t);if(e)return gu(t)<=e}function vu(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!vu(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!vu(e)))return!1;return!0}function gu(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=gu(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(hP[n])e++;else if(r=t[n],typeof r=="object"&&(e+=gu(r)+1),e==1/0)return 1/0}return e}function _i(t,e){e!==!1&&(t=Cn(t));var r=zs.parse(t);return Gh(r)}function Gh(t){return zs.serialize(t).split("#")[0]+"#"}var mP=/#\/?$/;function Cn(t){return t?t.replace(mP,""):""}function wi(t,e){return e=Cn(e),zs.resolve(t,e)}function vP(t){var e=Cn(this._getId(t)),r={"":e},a={"":_i(e,!1)},n={},s=this;return dP(t,{allKeys:!0},function(o,i,l,c,u,f,g){if(i!==""){var d=s._getId(o),m=r[c],v=a[c]+"/"+u;if(g!==void 0&&(v+="/"+(typeof g=="number"?g:vi.escapeFragment(g))),typeof d=="string"){d=m=Cn(m?zs.resolve(m,d):d);var h=s._refs[d];if(typeof h=="string"&&(h=s._refs[h]),h&&h.schema){if(!Bh(o,h.schema))throw new Error('id "'+d+'" resolves to more than one schema')}else if(d!=Cn(v))if(d[0]=="#"){if(n[d]&&!Bh(o,n[d]))throw new Error('id "'+d+'" resolves to more than one schema');n[d]=o}else s._refs[d]=v}r[i]=m,a[i]=v}}),n}var yu=hu,_u={Validation:Kh(gP),MissingRef:Kh(wu)};function gP(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}wu.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function wu(t,e,r){this.message=r||wu.message(t,e),this.missingRef=yu.url(t,e),this.missingSchema=yu.normalizeId(yu.fullPath(this.missingRef))}function Kh(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Wh=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var c={key:i,value:o[i]},u={key:l,value:o[l]};return s(c,u)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var c=n.push(o)-1,u=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<u.length;i++){var f=u[i],g=s(o[f]);g&&(l&&(l+=","),l+=JSON.stringify(f)+":"+g)}return n.splice(c,1),"{"+l+"}"}}(t)},Qh=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var c="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(c);else throw new Error(c)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",u=e.level,f=e.dataLevel,g=e.schema[r],d=e.schemaPath+e.util.getProperty(r),m=e.errSchemaPath+"/"+r,S=!e.opts.allErrors,A,v="data"+(f||""),b="valid"+u;if(e.schema===!1){e.isTop?S=!0:n+=" var "+b+" = false; ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=h.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+b+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var _=e.isTop,u=e.level=0,f=e.dataLevel=0,v="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var w="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var u=e.level,f=e.dataLevel,v="data"+(f||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+u+" = errors;"}var b="valid"+u,S=!e.opts.allErrors,x="",k="",A,O=e.schema.type,H=Array.isArray(O);if(O&&e.opts.nullable&&e.schema.nullable===!0&&(H?O.indexOf("null")==-1&&(O=O.concat("null")):O!="null"&&(O=[O,"null"],H=!0)),H&&O.length==1&&(O=O[0],H=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),O){if(e.opts.coerceTypes)var J=e.util.coerceToTypes(e.opts.coerceTypes,O);var K=e.RULES.types[O];if(J||H||K===!0||K&&!Ve(K)){var d=e.schemaPath+".type",m=e.errSchemaPath+"/type",d=e.schemaPath+".type",m=e.errSchemaPath+"/type",z=H?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[z](O,v,e.opts.strictNumbers,!0)+") { ",J){var U="dataType"+u,G="coerced"+u;n+=" var "+U+" = typeof "+v+"; var "+G+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+U+" == 'object' && Array.isArray("+v+") && "+v+".length == 1) { "+v+" = "+v+"[0]; "+U+" = typeof "+v+"; if ("+e.util.checkDataType(e.schema.type,v,e.opts.strictNumbers)+") "+G+" = "+v+"; } "),n+=" if ("+G+" !== undefined) ; ";var se=J;if(se)for(var ne,ce=-1,pe=se.length-1;ce<pe;)ne=se[ce+=1],ne=="string"?n+=" else if ("+U+" == 'number' || "+U+" == 'boolean') "+G+" = '' + "+v+"; else if ("+v+" === null) "+G+" = ''; ":ne=="number"||ne=="integer"?(n+=" else if ("+U+" == 'boolean' || "+v+" === null || ("+U+" == 'string' && "+v+" && "+v+" == +"+v+" ",ne=="integer"&&(n+=" && !("+v+" % 1)"),n+=")) "+G+" = +"+v+"; "):ne=="boolean"?n+=" else if ("+v+" === 'false' || "+v+" === 0 || "+v+" === null) "+G+" = false; else if ("+v+" === 'true' || "+v+" === 1) "+G+" = true; ":ne=="null"?n+=" else if ("+v+" === '' || "+v+" === 0 || "+v+" === false) "+G+" = null; ":e.opts.coerceTypes=="array"&&ne=="array"&&(n+=" else if ("+U+" == 'string' || "+U+" == 'number' || "+U+" == 'boolean' || "+v+" == null) "+G+" = ["+v+"]; ");n+=" else { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=h.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+G+" !== undefined) { ";var M=f?"data"+(f-1||""):"parentData",R=f?e.dataPathArr[f]:"parentDataProperty";n+=" "+v+" = "+G+"; ",f||(n+="if ("+M+" !== undefined)"),n+=" "+M+"["+R+"] = "+G+"; } "}else{var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=h.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",S&&(n+=" } if (errors === ",_?n+="0":n+="errs_"+u,n+=") { ",k+="}");else{var D=e.RULES;if(D){for(var K,N=-1,y=D.length-1;N<y;)if(K=D[N+=1],Ve(K)){if(K.type&&(n+=" if ("+e.util.checkDataType(K.type,v,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(K.type=="object"&&e.schema.properties){var g=e.schema.properties,P=Object.keys(g),j=P;if(j)for(var Q,ee=-1,Se=j.length-1;ee<Se;){Q=j[ee+=1];var de=g[Q];if(de.default!==void 0){var ge=v+e.util.getProperty(Q);if(e.compositeRule){if(e.opts.strictDefaults){var w="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(de.default)+" ":n+=" "+JSON.stringify(de.default)+" ",n+="; "}}}else if(K.type=="array"&&Array.isArray(e.schema.items)){var vt=e.schema.items;if(vt){for(var de,ce=-1,Te=vt.length-1;ce<Te;)if(de=vt[ce+=1],de.default!==void 0){var ge=v+"["+ce+"]";if(e.compositeRule){if(e.opts.strictDefaults){var w="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(de.default)+" ":n+=" "+JSON.stringify(de.default)+" ",n+="; "}}}}var me=K.rules;if(me){for(var Ne,Ae=-1,ke=me.length-1;Ae<ke;)if(Ne=me[Ae+=1],re(Ne)){var tt=Ne.code(e,Ne.keyword,K.type);tt&&(n+=" "+tt+" ",S&&(x+="}"))}}if(S&&(n+=" "+x+" ",x=""),K.type&&(n+=" } ",O&&O===K.type&&!J)){n+=" else { ";var d=e.schemaPath+".type",m=e.errSchemaPath+"/type",h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(m)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=h.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}S&&(n+=" if (errors === ",_?n+="0":n+="errs_"+u,n+=") { ",k+="}")}}}S&&(n+=" "+k+" "),_?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+b+" = errors === errs_"+u+";";function Ve(Be){for(var Ee=Be.rules,Qe=0;Qe<Ee.length;Qe++)if(re(Ee[Qe]))return!0}function re(Be){return e.schema[Be.keyword]!==void 0||Be.implements&&ze(Be)}function ze(Be){for(var Ee=Be.implements,Qe=0;Qe<Ee.length;Qe++)if(e.schema[Ee[Qe]]!==void 0)return!0}return n},bi=hu,Ei=ja,Yh=_u,yP=Wh,Xh=Qh,_P=Ei.ucs2length,wP=ls,bP=Yh.Validation,EP=bu;function bu(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],c={},u=[],f={},g=[];e=e||{schema:t,refVal:o,refs:i};var d=SP.call(this,t,e,a),m=this._compilations[d.index];if(d.compiling)return m.callValidate=w;var v=this._formats,h=this.RULES;try{var p=b(t,e,r,a);m.validate=p;var _=m.callValidate;return _&&(_.schema=p.schema,_.errors=null,_.refs=p.refs,_.refVal=p.refVal,_.root=p.root,_.$async=p.$async,s.sourceCode&&(_.source=p.source)),p}finally{$P.call(this,t,e,a)}function w(){var z=m.validate,U=z.apply(this,arguments);return w.errors=z.errors,U}function b(z,U,G,se){var ne=!U||U&&U.schema==z;if(U.schema!=e.schema)return bu.call(n,z,U,G,se);var ce=z.$async===!0,pe=Xh({isTop:!0,schema:z,isRoot:ne,baseId:se,root:U,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Yh.MissingRef,RULES:h,validate:Xh,util:Ei,resolve:bi,resolveRef:S,usePattern:H,useDefault:J,useCustomRule:K,opts:s,formats:v,logger:n.logger,self:n});pe=Si(o,xP)+Si(l,PP)+Si(u,kP)+Si(g,IP)+pe,s.processCode&&(pe=s.processCode(pe,z));var M;try{var R=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",pe);M=R(n,h,v,e,o,u,g,wP,_P,bP),o[0]=M}catch(D){throw n.logger.error("Error compiling schema, function code:",pe),D}return M.schema=z,M.errors=null,M.refs=i,M.refVal=o,M.root=ne?M:U,ce&&(M.$async=!0),s.sourceCode===!0&&(M.source={code:pe,patterns:l,defaults:u}),M}function S(z,U,G){U=bi.url(z,U);var se=i[U],ne,ce;if(se!==void 0)return ne=o[se],ce="refVal["+se+"]",O(ne,ce);if(!G&&e.refs){var pe=e.refs[U];if(pe!==void 0)return ne=e.refVal[pe],ce=x(U,ne),O(ne,ce)}ce=x(U);var M=bi.call(n,b,e,U);if(M===void 0){var R=r&&r[U];R&&(M=bi.inlineRef(R,s.inlineRefs)?R:bu.call(n,R,e,r,z))}if(M===void 0)k(U);else return A(U,M),O(M,ce)}function x(z,U){var G=o.length;return o[G]=U,i[z]=G,"refVal"+G}function k(z){delete i[z]}function A(z,U){var G=i[z];o[G]=U}function O(z,U){return typeof z=="object"||typeof z=="boolean"?{code:U,schema:z,inline:!0}:{code:U,$async:z&&!!z.$async}}function H(z){var U=c[z];return U===void 0&&(U=c[z]=l.length,l[U]=z),"pattern"+U}function J(z){switch(typeof z){case"boolean":case"number":return""+z;case"string":return Ei.toQuotedString(z);case"object":if(z===null)return"null";var U=yP(z),G=f[U];return G===void 0&&(G=f[U]=u.length,u[G]=z),"default"+G}}function K(z,U,G,se){if(n._opts.validateSchema!==!1){var ne=z.definition.dependencies;if(ne&&!ne.every(function(j){return Object.prototype.hasOwnProperty.call(G,j)}))throw new Error("parent schema must have all required keywords: "+ne.join(","));var ce=z.definition.validateSchema;if(ce){var pe=ce(U);if(!pe){var M="keyword schema is invalid: "+n.errorsText(ce.errors);if(n._opts.validateSchema=="log")n.logger.error(M);else throw new Error(M)}}}var R=z.definition.compile,D=z.definition.inline,N=z.definition.macro,y;if(R)y=R.call(n,U,G,se);else if(N)y=N.call(n,U,G,se),s.validateSchema!==!1&&n.validateSchema(y,!0);else if(D)y=D.call(n,se,z.keyword,U,G);else if(y=z.definition.validate,!y)return;if(y===void 0)throw new Error('custom keyword "'+z.keyword+'"failed to compile');var P=g.length;return g[P]=y,{code:"customRule"+P,validate:y}}}function SP(t,e,r){var a=em.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function $P(t,e,r){var a=em.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function em(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function PP(t,e){return"var pattern"+t+" = new RegExp("+Ei.toQuotedString(e[t])+");"}function kP(t){return"var default"+t+" = defaults["+t+"];"}function xP(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function IP(t){return"var customRule"+t+" = customRules["+t+"];"}function Si(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var tm={exports:{}},$i=tm.exports=function(){this._cache={}};$i.prototype.put=function(e,r){this._cache[e]=r},$i.prototype.get=function(e){return this._cache[e]},$i.prototype.del=function(e){delete this._cache[e]},$i.prototype.clear=function(){this._cache={}};var TP=tm.exports,CP=ja,RP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,OP=[0,31,28,31,30,31,30,31,31,30,31,30,31],NP=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,rm=/^(?=.{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,AP=/^(?:[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,MP=/^(?:[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,nm=/^(?:(?:[^\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,am=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,sm=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,om=/^(?:\/(?:[^~/]|~0|~1)*)*$/,im=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,lm=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,jP=Pi;function Pi(t){return t=t=="full"?"full":"fast",CP.copy(Pi[t])}Pi.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":nm,url:am,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,hostname:rm,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:dm,uuid:sm,"json-pointer":om,"json-pointer-uri-fragment":im,"relative-json-pointer":lm},Pi.full={date:cm,time:um,"date-time":zP,uri:qP,"uri-reference":MP,"uri-template":nm,url:am,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:rm,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:dm,uuid:sm,"json-pointer":om,"json-pointer-uri-fragment":im,"relative-json-pointer":lm};function DP(t){return t%4===0&&(t%100!==0||t%400===0)}function cm(t){var e=t.match(RP);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&DP(r)?29:OP[a])}function um(t,e){var r=t.match(NP);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var LP=/t|\s/i;function zP(t){var e=t.split(LP);return e.length==2&&cm(e[0])&&um(e[1],!0)}var UP=/\/|:/;function qP(t){return UP.test(t)&&AP.test(t)}var FP=/[^\\]\\Z/;function dm(t){if(FP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var ZP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(o||""),f="valid"+s,g,d;if(i=="#"||i=="#/")e.isRoot?(g=e.async,d="validate"):(g=e.root.schema.$async===!0,d="root.refVal[0]");else{var m=e.resolveRef(e.baseId,i,e.isRoot);if(m===void 0){var v=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(v);var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),n+=" } "):n+=" {} ";var p=n;n=h.pop(),!e.compositeRule&&c?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(v),c&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,v)}else if(m.inline){var _=e.util.copy(e);_.level++;var w="valid"+_.level;_.schema=m.schema,_.schemaPath="",_.errSchemaPath=i;var b=e.validate(_).replace(/validate\.schema/g,m.code);n+=" "+b+" ",c&&(n+=" if ("+w+") { ")}else g=m.$async===!0||e.async&&m.$async!==!1,d=m.code}if(d){var h=h||[];h.push(n),n="",e.opts.passContext?n+=" "+d+".call(this, ":n+=" "+d+"( ",n+=" "+u+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var S=o?"data"+(o-1||""):"parentData",x=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+S+" , "+x+", rootData) ";var k=n;if(n=h.pop(),g){if(!e.async)throw new Error("async schema referenced by sync schema");c&&(n+=" var "+f+"; "),n+=" try { await "+k+"; ",c&&(n+=" "+f+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",c&&(n+=" "+f+" = false; "),n+=" } ",c&&(n+=" if ("+f+") { ")}else n+=" if (!"+k+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",c&&(n+=" else { ")}return n},VP=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c=e.util.copy(e),u="";c.level++;var f="valid"+c.level,g=c.baseId,d=!0,m=s;if(m)for(var v,h=-1,p=m.length-1;h<p;)v=m[h+=1],(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all))&&(d=!1,c.schema=v,c.schemaPath=o+"["+h+"]",c.errSchemaPath=i+"/"+h,n+=" "+e.validate(c)+" ",c.baseId=g,l&&(n+=" if ("+f+") { ",u+="}"));return l&&(d?n+=" if (true) { ":n+=" "+u.slice(0,-1)+" "),n},HP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,m=e.util.copy(e),v="";m.level++;var h="valid"+m.level,p=i.every(function(A){return e.opts.strictKeywords?typeof A=="object"&&Object.keys(A).length>0||A===!1:e.util.schemaHasRules(A,e.RULES.all)});if(p){var _=m.baseId;n+=" var "+d+" = errors; var "+g+" = false; ";var w=e.compositeRule;e.compositeRule=m.compositeRule=!0;var b=i;if(b)for(var S,x=-1,k=b.length-1;x<k;)S=b[x+=1],m.schema=S,m.schemaPath=l+"["+x+"]",m.errSchemaPath=c+"/"+x,n+=" "+e.validate(m)+" ",m.baseId=_,n+=" "+g+" = "+g+" || "+h+"; if (!"+g+") { ",v+="}";e.compositeRule=m.compositeRule=w,n+=" "+v+" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else u&&(n+=" if (true) { ");return n},BP=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},JP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),d||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+g+" = equal("+f+", schema"+s+"); if (!"+g+") { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},GP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,m=e.util.copy(e),v="";m.level++;var h="valid"+m.level,p="i"+s,_=m.dataLevel=e.dataLevel+1,w="data"+_,b=e.baseId,S=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+d+" = errors;var "+g+";",S){var x=e.compositeRule;e.compositeRule=m.compositeRule=!0,m.schema=i,m.schemaPath=l,m.errSchemaPath=c,n+=" var "+h+" = false; for (var "+p+" = 0; "+p+" < "+f+".length; "+p+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var k=f+"["+p+"]";m.dataPathArr[_]=p;var A=e.validate(m);m.baseId=b,e.util.varOccurences(A,w)<2?n+=" "+e.util.varReplace(A,w,k)+" ":n+=" var "+w+" = "+k+"; "+A+" ",n+=" if ("+h+") break; } ",e.compositeRule=m.compositeRule=x,n+=" "+v+" if (!"+h+") {"}else n+=" if ("+f+".length == 0) {";var O=O||[];O.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var H=n;return n=O.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+H+"]); ":n+=" validate.errors = ["+H+"]; return false; ":n+=" var err = "+H+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",S&&(n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},KP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),m="";d.level++;var v="valid"+d.level,h={},p={},_=e.opts.ownProperties;for(x in i)if(x!="__proto__"){var w=i[x],b=Array.isArray(w)?p:h;b[x]=w}n+="var "+g+" = errors;";var S=e.errorPath;n+="var missing"+s+";";for(var x in p)if(b=p[x],b.length){if(n+=" if ( "+f+e.util.getProperty(x)+" !== undefined ",_&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(x)+"') "),u){n+=" && ( ";var k=b;if(k)for(var A,O=-1,H=k.length-1;O<H;){A=k[O+=1],O&&(n+=" || ");var J=e.util.getProperty(A),K=f+J;n+=" ( ( "+K+" === undefined ",_&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(A)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:J)+") ) "}n+=")) { ";var z="missing"+s,U="' + "+z+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,z,!0):S+" + "+z);var G=G||[];G.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(x)+"', missingProperty: '"+U+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(b.length==1?b[0]:b.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",b.length==1?n+="property "+e.util.escapeQuotes(b[0]):n+="properties "+e.util.escapeQuotes(b.join(", ")),n+=" when property "+e.util.escapeQuotes(x)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var se=n;n=G.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+se+"]); ":n+=" validate.errors = ["+se+"]; return false; ":n+=" var err = "+se+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var ne=b;if(ne)for(var A,ce=-1,pe=ne.length-1;ce<pe;){A=ne[ce+=1];var J=e.util.getProperty(A),U=e.util.escapeQuotes(A),K=f+J;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,A,e.opts.jsonPointers)),n+=" if ( "+K+" === undefined ",_&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(A)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(x)+"', missingProperty: '"+U+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(b.length==1?b[0]:b.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",b.length==1?n+="property "+e.util.escapeQuotes(b[0]):n+="properties "+e.util.escapeQuotes(b.join(", ")),n+=" when property "+e.util.escapeQuotes(x)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",u&&(m+="}",n+=" else { ")}e.errorPath=S;var M=d.baseId;for(var x in h){var w=h[x];(e.opts.strictKeywords?typeof w=="object"&&Object.keys(w).length>0||w===!1:e.util.schemaHasRules(w,e.RULES.all))&&(n+=" "+v+" = true; if ( "+f+e.util.getProperty(x)+" !== undefined ",_&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(x)+"') "),n+=") { ",d.schema=w,d.schemaPath=l+e.util.getProperty(x),d.errSchemaPath=c+"/"+e.util.escapeFragment(x),n+=" "+e.validate(d)+" ",d.baseId=M,n+=" } ",u&&(n+=" if ("+v+") { ",m+="}"))}return u&&(n+=" "+m+" if ("+g+" == errors) {"),n},WP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var m="i"+s,v="schema"+s;d||(n+=" var "+v+" = validate.schema"+l+";"),n+="var "+g+";",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=""+g+" = false;for (var "+m+"=0; "+m+"<"+v+".length; "+m+"++) if (equal("+f+", "+v+"["+m+"])) { "+g+" = true; break; }",d&&(n+=" } "),n+=" if (!"+g+") { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},QP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||"");if(e.opts.format===!1)return u&&(n+=" if (true) { "),n;var g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var m=e.opts.unknownFormats,v=Array.isArray(m);if(g){var h="format"+s,p="isObject"+s,_="formatType"+s;n+=" var "+h+" = formats["+d+"]; var "+p+" = typeof "+h+" == 'object' && !("+h+" instanceof RegExp) && "+h+".validate; var "+_+" = "+p+" && "+h+".type || 'string'; if ("+p+") { ",e.async&&(n+=" var async"+s+" = "+h+".async; "),n+=" "+h+" = "+h+".validate; } if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" (",m!="ignore"&&(n+=" ("+d+" && !"+h+" ",v&&(n+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),n+=") || "),n+=" ("+h+" && "+_+" == '"+a+"' && !(typeof "+h+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+h+"("+f+") : "+h+"("+f+")) ":n+=" "+h+"("+f+") ",n+=" : "+h+".test("+f+"))))) {"}else{var h=e.formats[i];if(!h){if(m=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),u&&(n+=" if (true) { "),n;if(v&&m.indexOf(i)>=0)return u&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var p=typeof h=="object"&&!(h instanceof RegExp)&&h.validate,_=p&&h.type||"string";if(p){var w=h.async===!0;h=h.validate}if(_!=a)return u&&(n+=" if (true) { "),n;if(w){if(!e.async)throw new Error("async format in sync schema");var b="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+b+"("+f+"))) { "}else{n+=" if (! ";var b="formats"+e.util.getProperty(i);p&&(b+=".validate"),typeof h=="function"?n+=" "+b+"("+f+") ":n+=" "+b+".test("+f+") ",n+=") { "}}var S=S||[];S.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var x=n;return n=S.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+x+"]); ":n+=" validate.errors = ["+x+"]; return false; ":n+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},YP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,m=e.util.copy(e);m.level++;var v="valid"+m.level,h=e.schema.then,p=e.schema.else,_=h!==void 0&&(e.opts.strictKeywords?typeof h=="object"&&Object.keys(h).length>0||h===!1:e.util.schemaHasRules(h,e.RULES.all)),w=p!==void 0&&(e.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===!1:e.util.schemaHasRules(p,e.RULES.all)),b=m.baseId;if(_||w){var S;m.createErrors=!1,m.schema=i,m.schemaPath=l,m.errSchemaPath=c,n+=" var "+d+" = errors; var "+g+" = true; ";var x=e.compositeRule;e.compositeRule=m.compositeRule=!0,n+=" "+e.validate(m)+" ",m.baseId=b,m.createErrors=!0,n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=m.compositeRule=x,_?(n+=" if ("+v+") { ",m.schema=e.schema.then,m.schemaPath=e.schemaPath+".then",m.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(m)+" ",m.baseId=b,n+=" "+g+" = "+v+"; ",_&&w?(S="ifClause"+s,n+=" var "+S+" = 'then'; "):S="'then'",n+=" } ",w&&(n+=" else { ")):n+=" if (!"+v+") { ",w&&(m.schema=e.schema.else,m.schemaPath=e.schemaPath+".else",m.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(m)+" ",m.baseId=b,n+=" "+g+" = "+v+"; ",_&&w?(S="ifClause"+s,n+=" var "+S+" = 'else'; "):S="'else'",n+=" } "),n+=" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+S+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+S+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},XP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,m=e.util.copy(e),v="";m.level++;var h="valid"+m.level,p="i"+s,_=m.dataLevel=e.dataLevel+1,w="data"+_,b=e.baseId;if(n+="var "+d+" = errors;var "+g+";",Array.isArray(i)){var S=e.schema.additionalItems;if(S===!1){n+=" "+g+" = "+f+".length <= "+i.length+"; ";var x=c;c=e.errSchemaPath+"/additionalItems",n+=" if (!"+g+") { ";var k=k||[];k.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var A=n;n=k.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+A+"]); ":n+=" validate.errors = ["+A+"]; return false; ":n+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",c=x,u&&(v+="}",n+=" else { ")}var O=i;if(O){for(var H,J=-1,K=O.length-1;J<K;)if(H=O[J+=1],e.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:e.util.schemaHasRules(H,e.RULES.all)){n+=" "+h+" = true; if ("+f+".length > "+J+") { ";var z=f+"["+J+"]";m.schema=H,m.schemaPath=l+"["+J+"]",m.errSchemaPath=c+"/"+J,m.errorPath=e.util.getPathExpr(e.errorPath,J,e.opts.jsonPointers,!0),m.dataPathArr[_]=J;var U=e.validate(m);m.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",n+=" } ",u&&(n+=" if ("+h+") { ",v+="}")}}if(typeof S=="object"&&(e.opts.strictKeywords?typeof S=="object"&&Object.keys(S).length>0||S===!1:e.util.schemaHasRules(S,e.RULES.all))){m.schema=S,m.schemaPath=e.schemaPath+".additionalItems",m.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+h+" = true; if ("+f+".length > "+i.length+") { for (var "+p+" = "+i.length+"; "+p+" < "+f+".length; "+p+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var z=f+"["+p+"]";m.dataPathArr[_]=p;var U=e.validate(m);m.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",u&&(n+=" if (!"+h+") break; "),n+=" } } ",u&&(n+=" if ("+h+") { ",v+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){m.schema=i,m.schemaPath=l,m.errSchemaPath=c,n+=" for (var "+p+" = 0; "+p+" < "+f+".length; "+p+"++) { ",m.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var z=f+"["+p+"]";m.dataPathArr[_]=p;var U=e.validate(m);m.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",u&&(n+=" if (!"+h+") break; "),n+=" }"}return u&&(n+=" "+v+" if ("+d+" == errors) {"),n},pm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,b,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var m=r=="maximum",v=m?"exclusiveMaximum":"exclusiveMinimum",h=e.schema[v],p=e.opts.$data&&h&&h.$data,_=m?"<":">",w=m?">":"<",b=void 0;if(!(g||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(p||h===void 0||typeof h=="number"||typeof h=="boolean"))throw new Error(v+" must be number or boolean");if(p){var S=e.util.getData(h.$data,o,e.dataPathArr),x="exclusive"+s,k="exclType"+s,A="exclIsNumber"+s,O="op"+s,H="' + "+O+" + '";n+=" var schemaExcl"+s+" = "+S+"; ",S="schemaExcl"+s,n+=" var "+x+"; var "+k+" = typeof "+S+"; if ("+k+" != 'boolean' && "+k+" != 'undefined' && "+k+" != 'number') { ";var b=v,J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(b||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+v+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+k+" == 'number' ? ( ("+x+" = "+d+" === undefined || "+S+" "+_+"= "+d+") ? "+f+" "+w+"= "+S+" : "+f+" "+w+" "+d+" ) : ( ("+x+" = "+S+" === true) ? "+f+" "+w+"= "+d+" : "+f+" "+w+" "+d+" ) || "+f+" !== "+f+") { var op"+s+" = "+x+" ? '"+_+"' : '"+_+"='; ",i===void 0&&(b=v,c=e.errSchemaPath+"/"+v,d=S,g=p)}else{var A=typeof h=="number",H=_;if(A&&g){var O="'"+H+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" ( "+d+" === undefined || "+h+" "+_+"= "+d+" ? "+f+" "+w+"= "+h+" : "+f+" "+w+" "+d+" ) || "+f+" !== "+f+") { "}else{A&&i===void 0?(x=!0,b=v,c=e.errSchemaPath+"/"+v,d=h,w+="="):(A&&(d=Math[m?"min":"max"](h,i)),h===(A?d:!0)?(x=!0,b=v,c=e.errSchemaPath+"/"+v,w+="="):(x=!1,H+="="));var O="'"+H+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+f+" "+w+" "+d+" || "+f+" !== "+f+") { "}}b=b||r;var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(b||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { comparison: "+O+", limit: "+d+", exclusive: "+x+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+H+" ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;return n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},fm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var m=r=="maxItems"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+f+".length "+m+" "+d+") { ";var v=r,h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},hm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var m=r=="maxLength"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?n+=" "+f+".length ":n+=" ucs2length("+f+") ",n+=" "+m+" "+d+") { ";var v=r,h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},mm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var m=r=="maxProperties"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" Object.keys("+f+").length "+m+" "+d+") { ";var v=r,h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},ek=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",g&&(n+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),n+=" (division"+s+" = "+f+" / "+d+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",g&&(n+=" ) "),n+=" ) { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},tk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e);d.level++;var m="valid"+d.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c,n+=" var "+g+" = errors; ";var v=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var h;d.opts.allErrors&&(h=d.opts.allErrors,d.opts.allErrors=!1),n+=" "+e.validate(d)+" ",d.createErrors=!0,h&&(d.opts.allErrors=h),e.compositeRule=d.compositeRule=v,n+=" if ("+m+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var _=n;n=p.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+_+"]); ":n+=" validate.errors = ["+_+"]; return false; ":n+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+g+"; if (vErrors !== null) { if ("+g+") vErrors.length = "+g+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ");return n},rk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,m=e.util.copy(e),v="";m.level++;var h="valid"+m.level,p=m.baseId,_="prevValid"+s,w="passingSchemas"+s;n+="var "+d+" = errors , "+_+" = false , "+g+" = false , "+w+" = null; ";var b=e.compositeRule;e.compositeRule=m.compositeRule=!0;var S=i;if(S)for(var x,k=-1,A=S.length-1;k<A;)x=S[k+=1],(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))?(m.schema=x,m.schemaPath=l+"["+k+"]",m.errSchemaPath=c+"/"+k,n+=" "+e.validate(m)+" ",m.baseId=p):n+=" var "+h+" = true; ",k&&(n+=" if ("+h+" && "+_+") { "+g+" = false; "+w+" = ["+w+", "+k+"]; } else { ",v+="}"),n+=" if ("+h+") { "+g+" = "+_+" = true; "+w+" = "+k+"; }";return e.compositeRule=m.compositeRule=b,n+=""+v+"if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+w+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},nk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var m=g?"(new RegExp("+d+"))":e.usePattern(i);n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" !"+m+".test("+f+") ) { ";var v=v||[];v.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { pattern: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var h=n;return n=v.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+h+"]); ":n+=" validate.errors = ["+h+"]; return false; ":n+=" var err = "+h+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},ak=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),m="";d.level++;var v="valid"+d.level,h="key"+s,p="idx"+s,_=d.dataLevel=e.dataLevel+1,w="data"+_,b="dataProperties"+s,S=Object.keys(i||{}).filter(ce),x=e.schema.patternProperties||{},k=Object.keys(x).filter(ce),A=e.schema.additionalProperties,O=S.length||k.length,H=A===!1,J=typeof A=="object"&&Object.keys(A).length,K=e.opts.removeAdditional,z=H||J||K,U=e.opts.ownProperties,G=e.baseId,se=e.schema.required;if(se&&!(e.opts.$data&&se.$data)&&se.length<e.opts.loopRequired)var ne=e.util.toHash(se);function ce(wt){return wt!=="__proto__"}if(n+="var "+g+" = errors;var "+v+" = true;",U&&(n+=" var "+b+" = undefined;"),z){if(U?n+=" "+b+" = "+b+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+b+".length; "+p+"++) { var "+h+" = "+b+"["+p+"]; ":n+=" for (var "+h+" in "+f+") { ",O){if(n+=" var isAdditional"+s+" = !(false ",S.length)if(S.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+h+") ";else{var pe=S;if(pe)for(var M,R=-1,D=pe.length-1;R<D;)M=pe[R+=1],n+=" || "+h+" == "+e.util.toQuotedString(M)+" "}if(k.length){var N=k;if(N)for(var y,P=-1,j=N.length-1;P<j;)y=N[P+=1],n+=" || "+e.usePattern(y)+".test("+h+") "}n+=" ); if (isAdditional"+s+") { "}if(K=="all")n+=" delete "+f+"["+h+"]; ";else{var Q=e.errorPath,ee="' + "+h+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,h,e.opts.jsonPointers)),H)if(K)n+=" delete "+f+"["+h+"]; ";else{n+=" "+v+" = false; ";var Se=c;c=e.errSchemaPath+"/additionalProperties";var de=de||[];de.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+ee+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var ge=n;n=de.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=Se,u&&(n+=" break; ")}else if(J)if(K=="failing"){n+=" var "+g+" = errors; ";var vt=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.schema=A,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,h,e.opts.jsonPointers);var Te=f+"["+h+"]";d.dataPathArr[_]=h;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",n+=" if (!"+v+") { errors = "+g+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+f+"["+h+"]; } ",e.compositeRule=d.compositeRule=vt}else{d.schema=A,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,h,e.opts.jsonPointers);var Te=f+"["+h+"]";d.dataPathArr[_]=h;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",u&&(n+=" if (!"+v+") break; ")}e.errorPath=Q}O&&(n+=" } "),n+=" } ",u&&(n+=" if ("+v+") { ",m+="}")}var Ne=e.opts.useDefaults&&!e.compositeRule;if(S.length){var Ae=S;if(Ae)for(var M,ke=-1,tt=Ae.length-1;ke<tt;){M=Ae[ke+=1];var Ve=i[M];if(e.opts.strictKeywords?typeof Ve=="object"&&Object.keys(Ve).length>0||Ve===!1:e.util.schemaHasRules(Ve,e.RULES.all)){var re=e.util.getProperty(M),Te=f+re,ze=Ne&&Ve.default!==void 0;d.schema=Ve,d.schemaPath=l+re,d.errSchemaPath=c+"/"+e.util.escapeFragment(M),d.errorPath=e.util.getPath(e.errorPath,M,e.opts.jsonPointers),d.dataPathArr[_]=e.util.toQuotedString(M);var me=e.validate(d);if(d.baseId=G,e.util.varOccurences(me,w)<2){me=e.util.varReplace(me,w,Te);var Be=Te}else{var Be=w;n+=" var "+w+" = "+Te+"; "}if(ze)n+=" "+me+" ";else{if(ne&&ne[M]){n+=" if ( "+Be+" === undefined ",U&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=") { "+v+" = false; ";var Q=e.errorPath,Se=c,Ee=e.util.escapeQuotes(M);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(Q,M,e.opts.jsonPointers)),c=e.errSchemaPath+"/required";var de=de||[];de.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+Ee+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+Ee+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var ge=n;n=de.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=Se,e.errorPath=Q,n+=" } else { "}else u?(n+=" if ( "+Be+" === undefined ",U&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=") { "+v+" = true; } else { "):(n+=" if ("+Be+" !== undefined ",U&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=" ) { ");n+=" "+me+" } "}}u&&(n+=" if ("+v+") { ",m+="}")}}if(k.length){var Qe=k;if(Qe)for(var y,or=-1,At=Qe.length-1;or<At;){y=Qe[or+=1];var Ve=x[y];if(e.opts.strictKeywords?typeof Ve=="object"&&Object.keys(Ve).length>0||Ve===!1:e.util.schemaHasRules(Ve,e.RULES.all)){d.schema=Ve,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(y),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(y),U?n+=" "+b+" = "+b+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+b+".length; "+p+"++) { var "+h+" = "+b+"["+p+"]; ":n+=" for (var "+h+" in "+f+") { ",n+=" if ("+e.usePattern(y)+".test("+h+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,h,e.opts.jsonPointers);var Te=f+"["+h+"]";d.dataPathArr[_]=h;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",u&&(n+=" if (!"+v+") break; "),n+=" } ",u&&(n+=" else "+v+" = true; "),n+=" } ",u&&(n+=" if ("+v+") { ",m+="}")}}}return u&&(n+=" "+m+" if ("+g+" == errors) {"),n},sk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),m="";d.level++;var v="valid"+d.level;if(n+="var "+g+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c;var h="key"+s,p="idx"+s,_="i"+s,w="' + "+h+" + '",b=d.dataLevel=e.dataLevel+1,S="data"+b,x="dataProperties"+s,k=e.opts.ownProperties,A=e.baseId;k&&(n+=" var "+x+" = undefined; "),k?n+=" "+x+" = "+x+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+x+".length; "+p+"++) { var "+h+" = "+x+"["+p+"]; ":n+=" for (var "+h+" in "+f+") { ",n+=" var startErrs"+s+" = errors; ";var O=h,H=e.compositeRule;e.compositeRule=d.compositeRule=!0;var J=e.validate(d);d.baseId=A,e.util.varOccurences(J,S)<2?n+=" "+e.util.varReplace(J,S,O)+" ":n+=" var "+S+" = "+O+"; "+J+" ",e.compositeRule=d.compositeRule=H,n+=" if (!"+v+") { for (var "+_+"=startErrs"+s+"; "+_+"<errors; "+_+"++) { vErrors["+_+"].propertyName = "+h+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+w+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+w+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),u&&(n+=" break; "),n+=" } }"}return u&&(n+=" "+m+" if ("+g+" == errors) {"),n},ok=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var m="schema"+s;if(!d)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var v=[],h=i;if(h)for(var p,_=-1,w=h.length-1;_<w;){p=h[_+=1];var b=e.schema.properties[p];b&&(e.opts.strictKeywords?typeof b=="object"&&Object.keys(b).length>0||b===!1:e.util.schemaHasRules(b,e.RULES.all))||(v[v.length]=p)}}else var v=i;if(d||v.length){var S=e.errorPath,x=d||v.length>=e.opts.loopRequired,k=e.opts.ownProperties;if(u)if(n+=" var missing"+s+"; ",x){d||(n+=" var "+m+" = validate.schema"+l+"; ");var A="i"+s,O="schema"+s+"["+A+"]",H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,O,e.opts.jsonPointers)),n+=" var "+g+" = true; ",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=" for (var "+A+" = 0; "+A+" < "+m+".length; "+A+"++) { "+g+" = "+f+"["+m+"["+A+"]] !== undefined ",k&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", "+m+"["+A+"]) "),n+="; if (!"+g+") break; } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var z=v;if(z)for(var U,A=-1,G=z.length-1;A<G;){U=z[A+=1],A&&(n+=" || ");var se=e.util.getProperty(U),ne=f+se;n+=" ( ( "+ne+" === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?U:se)+") ) "}n+=") { ";var O="missing"+s,H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,O,!0):S+" + "+O);var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(x){d||(n+=" var "+m+" = validate.schema"+l+"; ");var A="i"+s,O="schema"+s+"["+A+"]",H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,O,e.opts.jsonPointers)),d&&(n+=" if ("+m+" && !Array.isArray("+m+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+m+" !== undefined) { "),n+=" for (var "+A+" = 0; "+A+" < "+m+".length; "+A+"++) { if ("+f+"["+m+"["+A+"]] === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", "+m+"["+A+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(n+=" } ")}else{var ce=v;if(ce)for(var U,pe=-1,M=ce.length-1;pe<M;){U=ce[pe+=1];var se=e.util.getProperty(U),H=e.util.escapeQuotes(U),ne=f+se;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,U,e.opts.jsonPointers)),n+=" if ( "+ne+" === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=S}else u&&(n+=" if (true) {");return n},ik=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data,m;if(d?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+s):m=i,(i||d)&&e.opts.uniqueItems!==!1){d&&(n+=" var "+g+"; if ("+m+" === false || "+m+" === undefined) "+g+" = true; else if (typeof "+m+" != 'boolean') "+g+" = false; else { "),n+=" var i = "+f+".length , "+g+" = true , j; if (i > 1) { ";var v=e.schema.items&&e.schema.items.type,h=Array.isArray(v);if(!v||v=="object"||v=="array"||h&&(v.indexOf("object")>=0||v.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+f+"[i], "+f+"[j])) { "+g+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+f+"[i]; ";var p="checkDataType"+(h?"s":"");n+=" if ("+e.util[p](v,"item",e.opts.strictNumbers,!0)+") continue; ",h&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+g+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var _=_||[];_.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",d?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var w=n;n=_.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},lk={$ref:ZP,allOf:VP,anyOf:HP,$comment:BP,const:JP,contains:GP,dependencies:KP,enum:WP,format:QP,if:YP,items:XP,maximum:pm,minimum:pm,maxItems:fm,minItems:fm,maxLength:hm,minLength:hm,maxProperties:mm,minProperties:mm,multipleOf:ek,not:tk,oneOf:rk,pattern:nk,properties:ak,propertyNames:sk,required:ok,uniqueItems:ik,validate:Qh},vm=lk,Eu=ja.toHash,ck=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=Eu(r),e.types=Eu(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(u){r.push(u),e.all[u]=!0})}r.push(o);var c=e.all[o]={keyword:o,code:vm[o],implements:i};return c}),e.all.$comment={keyword:"$comment",code:vm.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=Eu(r.concat(a)),e.custom={},e},gm=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],uk=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<gm.length;s++){var o=gm[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},dk=_u.MissingRef,pk=ym;function ym(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?ym.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(c){if(c instanceof dk)return l(c);throw c}function l(c){var u=c.missingSchema;if(d(u))throw new Error("Schema "+u+" is loaded but "+c.missingRef+" cannot be resolved");var f=a._loadingSchemas[u];return f||(f=a._loadingSchemas[u]=a._opts.loadSchema(u),f.then(g,g)),f.then(function(m){if(!d(u))return s(m).then(function(){d(u)||a.addSchema(m,u,void 0,e)})}).then(function(){return o(i)});function g(){delete a._loadingSchemas[u]}function d(m){return a._refs[m]||a._schemas[m]}}}}var fk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f,g="data"+(o||""),d="valid"+s,m="errs__"+s,v=e.opts.$data&&i&&i.$data,h;v?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",h="schema"+s):h=i;var p=this,_="definition"+s,w=p.definition,b="",S,x,k,A,O;if(v&&w.$data){O="keywordValidate"+s;var H=w.validateSchema;n+=" var "+_+" = RULES.custom['"+r+"'].definition; var "+O+" = "+_+".validate;"}else{if(A=e.useCustomRule(p,i,e.schema,e),!A)return;h="validate.schema"+l,O=A.code,S=w.compile,x=w.inline,k=w.macro}var J=O+".errors",K="i"+s,z="ruleErr"+s,U=w.async;if(U&&!e.async)throw new Error("async keyword in sync schema");if(x||k||(n+=""+J+" = null;"),n+="var "+m+" = errors;var "+d+";",v&&w.$data&&(b+="}",n+=" if ("+h+" === undefined) { "+d+" = true; } else { ",H&&(b+="}",n+=" "+d+" = "+_+".validateSchema("+h+"); if ("+d+") { ")),x)w.statements?n+=" "+A.validate+" ":n+=" "+d+" = "+A.validate+"; ";else if(k){var G=e.util.copy(e),b="";G.level++;var se="valid"+G.level;G.schema=A.validate,G.schemaPath="";var ne=e.compositeRule;e.compositeRule=G.compositeRule=!0;var ce=e.validate(G).replace(/validate\.schema/g,O);e.compositeRule=G.compositeRule=ne,n+=" "+ce}else{var pe=pe||[];pe.push(n),n="",n+=" "+O+".call( ",e.opts.passContext?n+="this":n+="self",S||w.schema===!1?n+=" , "+g+" ":n+=" , "+h+" , "+g+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var M=o?"data"+(o-1||""):"parentData",R=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+M+" , "+R+" , rootData ) ";var D=n;n=pe.pop(),w.errors===!1?(n+=" "+d+" = ",U&&(n+="await "),n+=""+D+"; "):U?(J="customErrors"+s,n+=" var "+J+" = null; try { "+d+" = await "+D+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+J+" = e.errors; else throw e; } "):n+=" "+J+" = null; "+d+" = "+D+"; "}if(w.modifying&&(n+=" if ("+M+") "+g+" = "+M+"["+R+"];"),n+=""+b,w.valid)u&&(n+=" if (true) { ");else{n+=" if ( ",w.valid===void 0?(n+=" !",k?n+=""+se:n+=""+d):n+=" "+!w.valid+" ",n+=") { ",f=p.keyword;var pe=pe||[];pe.push(n),n="";var pe=pe||[];pe.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var N=n;n=pe.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+N+"]); ":n+=" validate.errors = ["+N+"]; return false; ":n+=" var err = "+N+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var y=n;n=pe.pop(),x?w.errors?w.errors!="full"&&(n+=" for (var "+K+"="+m+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+z+".schemaPath === undefined) { "+z+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+z+".schema = "+h+"; "+z+".data = "+g+"; "),n+=" } "):w.errors===!1?n+=" "+y+" ":(n+=" if ("+m+" == errors) { "+y+" } else { for (var "+K+"="+m+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+z+".schemaPath === undefined) { "+z+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+z+".schema = "+h+"; "+z+".data = "+g+"; "),n+=" } } "):k?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):w.errors===!1?n+=" "+y+" ":(n+=" if (Array.isArray("+J+")) { if (vErrors === null) vErrors = "+J+"; else vErrors = vErrors.concat("+J+"); errors = vErrors.length; for (var "+K+"="+m+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; "+z+'.schemaPath = "'+c+'"; ',e.opts.verbose&&(n+=" "+z+".schema = "+h+"; "+z+".data = "+g+"; "),n+=" } } else { "+y+" } "),n+=" } ",u&&(n+=" else { ")}return n};const _m={$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 wm=_m,hk={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:wm.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:wm.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},mk=/^[a-z_$][a-z0-9_$-]*$/i,vk=fk,gk=hk,yk={add:_k,get:wk,remove:bk,validate:Su};function _k(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!mk.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,c){for(var u,f=0;f<r.length;f++){var g=r[f];if(g.type==l){u=g;break}}u||(u={type:l,rules:[]},r.push(u));var d={keyword:i,definition:c,custom:!0,code:vk,implements:c.implements};u.rules.push(d),r.custom[i]=d}return this}function wk(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function bk(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function Su(t,e){Su.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(gk,!0);if(r(t))return!0;if(Su.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const Ek={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var bm=EP,Yn=hu,Sk=TP,Em=Vh,$k=Wh,Pk=jP,kk=ck,Sm=uk,$m=ja,xk=mt;mt.prototype.validate=Tk,mt.prototype.compile=Ck,mt.prototype.addSchema=Rk,mt.prototype.addMetaSchema=Ok,mt.prototype.validateSchema=Nk,mt.prototype.getSchema=Mk,mt.prototype.removeSchema=Dk,mt.prototype.addFormat=Hk,mt.prototype.errorsText=Vk,mt.prototype._addSchema=Lk,mt.prototype._compile=zk,mt.prototype.compileAsync=pk;var ki=yk;mt.prototype.addKeyword=ki.add,mt.prototype.getKeyword=ki.get,mt.prototype.removeKeyword=ki.remove,mt.prototype.validateKeyword=ki.validate;var Pm=_u;mt.ValidationError=Pm.Validation,mt.MissingRefError=Pm.MissingRef,mt.$dataMetaSchema=Sm;var xi="http://json-schema.org/draft-07/schema",km=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],Ik=["/properties"];function mt(t){if(!(this instanceof mt))return new mt(t);t=this._opts=$m.copy(t)||{},Qk(this),this._schemas={},this._refs={},this._fragments={},this._formats=Pk(t.format),this._cache=t.cache||new Sk,this._loadingSchemas={},this._compilations=[],this.RULES=kk(),this._getId=Uk(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=$k),this._metaOpts=Wk(this),t.formats&&Gk(this),t.keywords&&Kk(this),Bk(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),Jk(this)}function Tk(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function Ck(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function Rk(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=Yn.normalizeId(e||s),Im(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function Ok(t,e,r){return this.addSchema(t,e,r,!0),this}function Nk(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||Ak(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function Ak(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(xi)?xi:void 0,t._opts.defaultMeta}function Mk(t){var e=xm(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return jk(this,t)}}function jk(t,e){var r=Yn.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=bm.call(t,a,n,void 0,s);return t._fragments[e]=new Em({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function xm(t,e){return e=Yn.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function Dk(t){if(t instanceof RegExp)return Ii(this,this._schemas,t),Ii(this,this._refs,t),this;switch(typeof t){case"undefined":return Ii(this,this._schemas),Ii(this,this._refs),this._cache.clear(),this;case"string":var e=xm(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=Yn.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function Ii(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function Lk(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=Yn.normalizeId(this._getId(t));i&&a&&Im(this,i);var l=this._opts.validateSchema!==!1&&!e,c;l&&!(c=i&&i==Yn.normalizeId(t.$schema))&&this.validateSchema(t,!0);var u=Yn.ids.call(this,t),f=new Em({id:i,schema:t,localRefs:u,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=f),this._cache.put(s,f),l&&c&&this.validateSchema(t,!0),f}function zk(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=bm.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function Uk(t){switch(t.schemaId){case"auto":return Zk;case"id":return qk;default:return Fk}}function qk(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function Fk(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function Zk(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function Vk(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function Hk(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function Bk(t){var e;if(t._opts.$data&&(e=Ek,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=_m;t._opts.$data&&(r=Sm(r,Ik)),t.addMetaSchema(r,xi,!0),t._refs["http://json-schema.org/schema"]=xi}}function Jk(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function Gk(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function Kk(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function Im(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function Wk(t){for(var e=$m.copy(t._opts),r=0;r<km.length;r++)delete e[km[r]];return e}function Qk(t){var e=t._opts.logger;if(e===!1)t.logger={log:$u,warn:$u,error:$u};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function $u(){}const Tm=$p(xk);class Us extends Uh{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Tm}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qh(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[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 a=await this.request({method:"initialize",params:{protocolVersion:Ms,capabilities:this._capabilities,clientInfo:this._clientInfo}},vh,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!oh.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;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(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.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(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.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(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.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},Dh,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},Ch,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Ih,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},Eh,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},xn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},xn,r)}async callTool(e,r=pi,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new st(rt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new st(rt.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof st?o:new st(rt.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Oh,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Cm 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 Pu(t){}function Rm(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=Pu,onError:r=Pu,onRetry:a=Pu,onComment:n}=t;let s="",o=!0,i,l="",c="";function u(v){const h=o?v.replace(/^\xEF\xBB\xBF/,""):v,[p,_]=Yk(`${s}${h}`);for(const w of p)f(w);s=_,o=!1}function f(v){if(v===""){d();return}if(v.startsWith(":")){n&&n(v.slice(v.startsWith(": ")?2:1));return}const h=v.indexOf(":");if(h!==-1){const p=v.slice(0,h),_=v[h+1]===" "?2:1,w=v.slice(h+_);g(p,w,v);return}g(v,"",v)}function g(v,h,p){switch(v){case"event":c=h;break;case"data":l=`${l}${h}
9
- `;break;case"id":i=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?a(parseInt(h,10)):r(new Cm(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:p}));break;default:r(new Cm(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:h,line:p}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
10
- `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function m(v={}){s&&v.consume&&f(s),o=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:m}}function Yk(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
11
- `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
12
- `&&a++}}return[e,r]}class Om extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(Nm(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Nm(this),r)}}function Xk(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function ku(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(ku).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${ku(t.cause)}`:t.message:`${t}`}function Nm(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Am=t=>{throw TypeError(t)},xu=(t,e,r)=>e.has(t)||Am("Cannot "+r),Le=(t,e,r)=>(xu(t,e,"read from private field"),r?r.call(t):e.get(t)),Ct=(t,e,r)=>e.has(t)?Am("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),lt=(t,e,r,a)=>(xu(t,e,"write to private field"),e.set(t,r),r),gn=(t,e,r)=>(xu(t,e,"access private method"),r),Xt,Xn,Da,Ti,Ci,qs,La,Fs,Rn,za,Ua,qa,Zs,Cr,Iu,Tu,Cu,Mm,Ru,Ou,Vs,Nu,Au;class Ri extends EventTarget{constructor(e,r){var a,n;super(),Ct(this,Cr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ct(this,Xt),Ct(this,Xn),Ct(this,Da),Ct(this,Ti),Ct(this,Ci),Ct(this,qs),Ct(this,La),Ct(this,Fs,null),Ct(this,Rn),Ct(this,za),Ct(this,Ua,null),Ct(this,qa,null),Ct(this,Zs,null),Ct(this,Tu,async s=>{var o;Le(this,za).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){gn(this,Cr,Vs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?lt(this,Da,new URL(s.url)):lt(this,Da,void 0),c!==200){gn(this,Cr,Vs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){gn(this,Cr,Vs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Le(this,Xt)===this.CLOSED)return;lt(this,Xt,this.OPEN);const f=new Event("open");if((o=Le(this,Zs))==null||o.call(this,f),this.dispatchEvent(f),typeof i!="object"||!i||!("getReader"in i)){gn(this,Cr,Vs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const g=new TextDecoder,d=i.getReader();let m=!0;do{const{done:v,value:h}=await d.read();h&&Le(this,za).feed(g.decode(h,{stream:!v})),v&&(m=!1,Le(this,za).reset(),gn(this,Cr,Nu).call(this))}while(m)}),Ct(this,Cu,s=>{lt(this,Rn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&gn(this,Cr,Nu).call(this,ku(s))}),Ct(this,Ru,s=>{typeof s.id=="string"&&lt(this,Fs,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:Le(this,Da)?Le(this,Da).origin:Le(this,Xn).origin,lastEventId:s.id||""});Le(this,qa)&&(!s.event||s.event==="message")&&Le(this,qa).call(this,o),this.dispatchEvent(o)}),Ct(this,Ou,s=>{lt(this,qs,s)}),Ct(this,Au,()=>{lt(this,La,void 0),Le(this,Xt)===this.CONNECTING&&gn(this,Cr,Iu).call(this)});try{if(e instanceof URL)lt(this,Xn,e);else if(typeof e=="string")lt(this,Xn,new URL(e,ex()));else throw new Error("Invalid URL")}catch{throw Xk("An invalid or illegal string was specified")}lt(this,za,Rm({onEvent:Le(this,Ru),onRetry:Le(this,Ou)})),lt(this,Xt,this.CONNECTING),lt(this,qs,3e3),lt(this,Ci,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),lt(this,Ti,(n=r==null?void 0:r.withCredentials)!=null?n:!1),gn(this,Cr,Iu).call(this)}get readyState(){return Le(this,Xt)}get url(){return Le(this,Xn).href}get withCredentials(){return Le(this,Ti)}get onerror(){return Le(this,Ua)}set onerror(e){lt(this,Ua,e)}get onmessage(){return Le(this,qa)}set onmessage(e){lt(this,qa,e)}get onopen(){return Le(this,Zs)}set onopen(e){lt(this,Zs,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){Le(this,La)&&clearTimeout(Le(this,La)),Le(this,Xt)!==this.CLOSED&&(Le(this,Rn)&&Le(this,Rn).abort(),lt(this,Xt,this.CLOSED),lt(this,Rn,void 0))}}Xt=new WeakMap,Xn=new WeakMap,Da=new WeakMap,Ti=new WeakMap,Ci=new WeakMap,qs=new WeakMap,La=new WeakMap,Fs=new WeakMap,Rn=new WeakMap,za=new WeakMap,Ua=new WeakMap,qa=new WeakMap,Zs=new WeakMap,Cr=new WeakSet,Iu=function(){lt(this,Xt,this.CONNECTING),lt(this,Rn,new AbortController),Le(this,Ci)(Le(this,Xn),gn(this,Cr,Mm).call(this)).then(Le(this,Tu)).catch(Le(this,Cu))},Tu=new WeakMap,Cu=new WeakMap,Mm=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Le(this,Fs)?{"Last-Event-ID":Le(this,Fs)}:void 0},cache:"no-store",signal:(t=Le(this,Rn))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Ru=new WeakMap,Ou=new WeakMap,Vs=function(t,e){var r;Le(this,Xt)!==this.CLOSED&&lt(this,Xt,this.CLOSED);const a=new Om("error",{code:e,message:t});(r=Le(this,Ua))==null||r.call(this,a),this.dispatchEvent(a)},Nu=function(t,e){var r;if(Le(this,Xt)===this.CLOSED)return;lt(this,Xt,this.CONNECTING);const a=new Om("error",{code:e,message:t});(r=Le(this,Ua))==null||r.call(this,a),this.dispatchEvent(a),lt(this,La,setTimeout(Le(this,Au),Le(this,qs)))},Au=new WeakMap,Ri.CONNECTING=0,Ri.OPEN=1,Ri.CLOSED=2;function ex(){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}let Mu;Mu=globalThis.crypto;async function tx(t){return(await Mu).getRandomValues(new Uint8Array(t))}async function rx(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await tx(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function nx(t){return await rx(t)}async function ax(t){const e=await(await Mu).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function sx(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await nx(t),r=await ax(e);return{code_verifier:e,code_challenge:r}}const zt=L().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:X.custom,message:"URL must be parseable",fatal:!0}),sh}).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"}),ox=te({resource:L().url(),authorization_servers:ue(zt).optional(),jwks_uri:L().url().optional(),scopes_supported:ue(L()).optional(),bearer_methods_supported:ue(L()).optional(),resource_signing_alg_values_supported:ue(L()).optional(),resource_name:L().optional(),resource_documentation:L().optional(),resource_policy_uri:L().url().optional(),resource_tos_uri:L().url().optional(),tls_client_certificate_bound_access_tokens:yt().optional(),authorization_details_types_supported:ue(L()).optional(),dpop_signing_alg_values_supported:ue(L()).optional(),dpop_bound_access_tokens_required:yt().optional()}).passthrough(),jm=te({issuer:L(),authorization_endpoint:zt,token_endpoint:zt,registration_endpoint:zt.optional(),scopes_supported:ue(L()).optional(),response_types_supported:ue(L()),response_modes_supported:ue(L()).optional(),grant_types_supported:ue(L()).optional(),token_endpoint_auth_methods_supported:ue(L()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),service_documentation:zt.optional(),revocation_endpoint:zt.optional(),revocation_endpoint_auth_methods_supported:ue(L()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),introspection_endpoint:L().optional(),introspection_endpoint_auth_methods_supported:ue(L()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),code_challenge_methods_supported:ue(L()).optional()}).passthrough(),ix=te({issuer:L(),authorization_endpoint:zt,token_endpoint:zt,userinfo_endpoint:zt.optional(),jwks_uri:zt,registration_endpoint:zt.optional(),scopes_supported:ue(L()).optional(),response_types_supported:ue(L()),response_modes_supported:ue(L()).optional(),grant_types_supported:ue(L()).optional(),acr_values_supported:ue(L()).optional(),subject_types_supported:ue(L()),id_token_signing_alg_values_supported:ue(L()),id_token_encryption_alg_values_supported:ue(L()).optional(),id_token_encryption_enc_values_supported:ue(L()).optional(),userinfo_signing_alg_values_supported:ue(L()).optional(),userinfo_encryption_alg_values_supported:ue(L()).optional(),userinfo_encryption_enc_values_supported:ue(L()).optional(),request_object_signing_alg_values_supported:ue(L()).optional(),request_object_encryption_alg_values_supported:ue(L()).optional(),request_object_encryption_enc_values_supported:ue(L()).optional(),token_endpoint_auth_methods_supported:ue(L()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),display_values_supported:ue(L()).optional(),claim_types_supported:ue(L()).optional(),claims_supported:ue(L()).optional(),service_documentation:L().optional(),claims_locales_supported:ue(L()).optional(),ui_locales_supported:ue(L()).optional(),claims_parameter_supported:yt().optional(),request_parameter_supported:yt().optional(),request_uri_parameter_supported:yt().optional(),require_request_uri_registration:yt().optional(),op_policy_uri:zt.optional(),op_tos_uri:zt.optional()}).passthrough().merge(jm.pick({code_challenge_methods_supported:!0})),Dm=te({access_token:L(),id_token:L().optional(),token_type:L(),expires_in:St().optional(),scope:L().optional(),refresh_token:L().optional()}).strip(),lx=te({error:L(),error_description:L().optional(),error_uri:L().optional()}),Lm=zt.optional().or(xe("").transform(()=>{})),cx=te({redirect_uris:ue(zt),token_endpoint_auth_method:L().optional(),grant_types:ue(L()).optional(),response_types:ue(L()).optional(),client_name:L().optional(),client_uri:zt.optional(),logo_uri:Lm,scope:L().optional(),contacts:ue(L()).optional(),tos_uri:Lm,policy_uri:L().optional(),jwks_uri:zt.optional(),jwks:rh().optional(),software_id:L().optional(),software_version:L().optional(),software_statement:L().optional()}).strip(),ux=te({client_id:L(),client_secret:L().optional(),client_id_issued_at:St().optional(),client_secret_expires_at:St().optional()}).strip(),dx=cx.merge(ux);te({error:L(),error_description:L().optional()}).strip(),te({token:L(),token_type_hint:L().optional()}).strip();function px(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function fx({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class Ut 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 ju extends Ut{}ju.errorCode="invalid_request";class Oi extends Ut{}Oi.errorCode="invalid_client";class Ni extends Ut{}Ni.errorCode="invalid_grant";class Ai extends Ut{}Ai.errorCode="unauthorized_client";class Du extends Ut{}Du.errorCode="unsupported_grant_type";class Lu extends Ut{}Lu.errorCode="invalid_scope";class zu extends Ut{}zu.errorCode="access_denied";class Fa extends Ut{}Fa.errorCode="server_error";class Uu extends Ut{}Uu.errorCode="temporarily_unavailable";class qu extends Ut{}qu.errorCode="unsupported_response_type";class Fu extends Ut{}Fu.errorCode="unsupported_token_type";class Zu extends Ut{}Zu.errorCode="invalid_token";class Vu extends Ut{}Vu.errorCode="method_not_allowed";class Hu extends Ut{}Hu.errorCode="too_many_requests";class Bu extends Ut{}Bu.errorCode="invalid_client_metadata";class Ju extends Ut{}Ju.errorCode="insufficient_scope";const hx={[ju.errorCode]:ju,[Oi.errorCode]:Oi,[Ni.errorCode]:Ni,[Ai.errorCode]:Ai,[Du.errorCode]:Du,[Lu.errorCode]:Lu,[zu.errorCode]:zu,[Fa.errorCode]:Fa,[Uu.errorCode]:Uu,[qu.errorCode]:qu,[Fu.errorCode]:Fu,[Zu.errorCode]:Zu,[Vu.errorCode]:Vu,[Hu.errorCode]:Hu,[Bu.errorCode]:Bu,[Ju.errorCode]:Ju};class Rr extends Error{constructor(e){super(e??"Unauthorized")}}const Gu="code",Ku="S256";function zm(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 Um(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":mx(n,s,r);return;case"client_secret_post":vx(n,s,a);return;case"none":gx(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function mx(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function vx(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function gx(t,e){e.set("client_id",t)}async function Wu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=lx.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=hx[n]||Fa;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new Fa(n)}}async function Za(t,e){var r,a;try{return await Qu(t,e)}catch(n){if(n instanceof Oi||n instanceof Ai)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Qu(t,e);if(n instanceof Ni)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Qu(t,e);throw n}}async function Qu(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await _x(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await yx(e,t,o),c=await $x(i,{fetchFn:s});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 Ix(i,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),h=await kx(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(h),"AUTHORIZED"}const f=await t.tokens();if(f!=null&&f.refresh_token)try{const v=await xx(i,{metadata:c,clientInformation:u,refreshToken:f.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Ut)||v instanceof Fa))throw v}const g=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:m}=await Px(i,{metadata:c,clientInformation:u,state:g,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(d),"REDIRECT"}async function yx(t,e,r){const a=px(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!fx({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function Yu(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function _x(t,e,r=fetch){const a=await Ex(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return ox.parse(await a.json())}async function Xu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?Xu(t,void 0,r):void 0;throw a}}function wx(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function qm(t,e,r=fetch){return await Xu(t,{"MCP-Protocol-Version":e},r)}function bx(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Ex(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:Ms;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const u=wx(e,o.pathname);l=new URL(u,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let c=await qm(l,i,r);if(!(a!=null&&a.metadataUrl)&&bx(c,o.pathname)){const u=new URL(`/.well-known/${e}`,o);c=await qm(u,i,r)}return c}function Sx(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function $x(t,{fetchFn:e=fetch,protocolVersion:r=Ms}={}){const a={"MCP-Protocol-Version":r,Accept:"application/json"},n=Sx(t);for(const{url:s,type:o}of n){const i=await Xu(s,a,e);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${o==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return o==="oauth"?jm.parse(await i.json()):ix.parse(await i.json())}}}async function Px(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Gu))throw new Error(`Incompatible auth server: does not support response type ${Gu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ku))throw new Error(`Incompatible auth server: does not support code challenge method ${Ku}`)}else i=new URL("/authorize",t);const l=await sx(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Gu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Ku),i.searchParams.set("redirect_uri",String(a)),s&&i.searchParams.set("state",s),n&&i.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&i.searchParams.append("prompt","consent"),o&&i.searchParams.set("resource",o.href),{authorizationUrl:i,codeVerifier:c}}async function kx(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",f=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(g,d,t,e);else{const v=(c=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],h=zm(r,v);Um(h,r,g,d)}o&&d.set("resource",o.href);const m=await(l??fetch)(f,{method:"POST",headers:g,body:d});if(!m.ok)throw await Wu(m);return Dm.parse(await m.json())}async function xx(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(u,f,t,e);else{const d=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],m=zm(r,d);Um(m,r,u,f)}n&&f.set("resource",n.href);const g=await(o??fetch)(c,{method:"POST",headers:u,body:f});if(!g.ok)throw await Wu(g);return Dm.parse({refresh_token:a,...await g.json()})}async function Ix(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Wu(s);return dx.parse(await s.json())}class Tx extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class Hs{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Za(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Rr;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.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,a;const n=(a=(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&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new Ri(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await n(i,{...l,headers:c});return u.status===401&&u.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Yu(u)),u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const c=new Tx(i.code,i.message,i);o(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){o(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let f;try{f=vn.parse(JSON.parse(u.data))}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g);return}(c=this.onmessage)===null||c===void 0||c.call(this,f)}})}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 Rr("No auth provider");if(await Za(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Yu(i),await Za(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}class Fm extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=Rm({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}const Cx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Mi extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Bs{constructor(e,r){var a;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:Cx}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Za(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Rr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Mi(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,c,u,f;try{const g=e.pipeThrough(new TextDecoderStream).pipeThrough(new Fm).getReader();for(;;){const{value:d,done:m}=await g.read();if(m)break;if(d.id&&(o=d.id,n==null||n(d.id)),!d.event||d.event==="message")try{const v=vn.parse(JSON.parse(d.data));s!==void 0&&qc(v)&&(v.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,v)}catch(v){(c=this.onerror)===null||c===void 0||c.call(this,v)}}}catch(g){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${g}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(d){(f=this.onerror)===null||f===void 0||f.call(this,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 Rr("No auth provider");if(await Za(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr("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 a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:uh(e)?e.id:void 0}).catch(h=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,h)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},f=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,u),g=f.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Mi(401,"Server returned 401 after successful authentication");if(this._resourceMetadataUrl=Yu(f),await Za(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr;return this._hasCompletedAuthFlow=!0,this.send(e)}const h=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${h}`)}if(this._hasCompletedAuthFlow=!1,f.status===202){w$(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,h)});return}const m=(Array.isArray(e)?e:[e]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,v=f.headers.get("content-type");if(m)if(v!=null&&v.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:l},!1);else if(v!=null&&v.includes("application/json")){const h=await f.json(),p=Array.isArray(h)?h.map(_=>vn.parse(_)):[vn.parse(h)];for(const _ of p)(s=this.onmessage)===null||s===void 0||s.call(this,_)}else throw new Mi(-1,`Unexpected content type: ${v}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new Mi(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const Rx="mcp";class Zm{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,Rx),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=vn.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function ji(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return ji=function(){return t},ji()}(function(t,e){const r=$t,a=$t,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ji,650197);const Vm=()=>{const t=$t,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},Ox=(t,e,r)=>{const a=$t,n=$t,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)},Nx=(t,e)=>{const r=$t,a=$t,n={};n.MbsGh="addEventListener",n.PPniK=function(o,i){return o===i},n[r(419)]=a(412),n[a(404)]="onmessage",n[r(397)]="undefined";const s=n;s.MbsGh in t&&s.PPniK(typeof t[r(427)],s.wRKyh)?t[r(427)](r(400),e):s.thraG in t&&typeof t[a(413)]!==s[a(397)]&&(t.onmessage=e)};class Js{constructor(e){const r=$t;this[r(406)]=e}async start(){const e=$t,r=$t;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=vn[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=$t,l=$t;try{const c={};c[i(403)]=r==null?void 0:r[i(403)];const u={};u[l(400)]=e,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),a.lEyuq(n)}catch(c){const u=c instanceof Error?c:new Error(a.YihNw(String,c));(o=this[l(408)])==null||o.call(this,u),s(u)}})}async close(){var e,r;const a=$t,n=$t;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class ed extends Js{constructor(e,r=Vm()){const a=$t,n=$t,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](Ox,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}class td extends Js{constructor(e,r=Vm()){const a=$t,n={mOWMr:function(s,o){return s===o},kgkem:function(s,o,i){return s(o,i)}};super(),this._endpoint=e,this._globalObject=r,this[a(432)]=new Promise(s=>{const o=a,i=a;n[o(392)](Nx,this[i(401)],l=>{const c=i,u=i;l.data&&n[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],s())})})}async listen(){return this[$t(432)]}}function $t(t,e){const r=ji();return $t=function(a,n){return a=a-(17*-491+-669+9407),r[a]},$t(t,e)}const Ax=()=>{const t=new MessageChannel;return[new Js(t.port1),new Js(t.port2)]};(function(t,e){const r=Xe,a=Xe,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Di,-763475+-52067*10+1724410);const Mx=async(t,e,r)=>{var a;const n=Xe,s=Xe,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:c,params:u}=r;let f={};switch(c){case i[s(345)]:f=await e.listTools(u);break;case i.rqstG:f=await e.callTool(u);break;case i[n(334)]:f=await e[n(350)](u);break;case i[s(329)]:f=await e.listResourceTemplates(u);break;case n(372):f=await e[n(383)](u);break;case i.HgYgW:f=await e.subscribeResource(u);break;case i.ookoz:f=await e.unsubscribeResource(u);break;case i[n(385)]:f=await e.getPrompt(u);break;case i.VTIWq:f=await e.listPrompts(u);break;case i[n(344)]:f=await e[n(376)]();break;case i.QUtUV:f=await e.complete(u);break;case n(390):f=await e[n(336)](u==null?void 0:u.level);break}const g={};g[n(361)]=f,g[n(394)]=i[n(364)],g.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](g))},jx=async(t,e,r)=>{var a;const n=Xe,s=Xe,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:c,params:u}=r;let f={};switch(c){case n(368):const d={};d.method=c,d[s(367)]=u,f=await e.request(d,su);break;case i[s(391)]:const m={};m.method=c,m[s(367)]=u,f=await e[s(381)](m,ru);break;case i.EZqgC:const v={};v.method=c,v.params=u,f=await e.request(v,nu);break;case i[s(370)]:const h={};h.method=c,f=await e[s(381)](h,xn);break}const g={};return g[s(361)]=f,g.jsonrpc=i[s(387)],g.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(g)),f},Dx=(t,e)=>{const r=Xe,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,c,u,f;const g=r,d=r,{id:m,method:v}=s;try{a[g(333)](v,a.oegpC)?await n[g(386)](t,s,o):await a.lZOUC(Mx,t,e,s)}catch(h){const{code:p,message:_,data:w}=h;try{if(p){const b={};b.code=p,b.message=_,b.data=w;const S={};S.error=b,S[g(394)]=a[d(331)],S.id=m,await((i=t==null?void 0:t.transport)==null?void 0:i.send(S))}else(c=(l=t==null?void 0:t[d(371)])==null?void 0:l.onerror)==null||c.call(l,h)}catch(b){(f=(u=t==null?void 0:t[g(371)])==null?void 0:u.onerror)==null||f.call(u,b)}}}},Lx=(t,e)=>{const r=Xe,a=Xe,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const c=r,u=a,{method:f,params:g}=o;if(s[c(363)](f,s[u(398)])&&(s[c(363)](f,s.hzhyg)||g!=null&&g.forward))try{await e.notification(o)}catch(d){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},zx=(t,e)=>async r=>{var a,n,s,o,i;const l=Xe,c=Xe,u={};u.SEmWX=l(332);const f=u;try{return await jx(t,e,r)}catch(g){const{code:d,message:m,data:v}=g;try{if(d){const h={};h[c(377)]=d,h.message=m,h.data=v;const p={};p[c(348)]=h,p.jsonrpc=f[l(338)],p.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[c(392)](p))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[c(339)])==null||s.call(n,g)}catch(h){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[c(339)])==null||i.call(o,h)}}},Ux=(t,e)=>async r=>{var a,n,s;const o=Xe,i=Xe,l={};l.dtUgZ=function(g,d){return g!==d},l.jgCIb=o(353),l.uUjKY="2.0";const c=l,{method:u,params:f}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==o(400)||f!=null&&f.forward))try{const g={...r};g[o(394)]=c[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](g))}catch(g){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,g)}};function Xe(t,e){const r=Di();return Xe=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},Xe(t,e)}const qx=(t,e)=>async r=>{var a,n,s,o,i,l;const c=Xe,u=Xe,f={};f[c(401)]=u(332);const g=f;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(d){const{code:m,message:v,data:h}=d;try{if(m){const p={};p.code=m,p[c(399)]=v,p.data=h;const _={};_[c(348)]=p,_[c(394)]=g.OhJjz,_.id=r.id,await((n=t==null?void 0:t[c(371)])==null?void 0:n.send(_))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[u(339)])==null||o.call(s,d)}catch(p){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,p)}}},rd=()=>{const t=Xe,e=Xe,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},a=[],n=(c,u)=>{const f=Xe,g=Xe;if(u){const d=[];for(const m of a)try{d.push(m(c,u))}catch{}for(const m of d)if(r[f(379)](m,null))return m}else for(const d of a)try{r[g(343)](d,c)}catch{}},s=c=>{const u=Xe;r[u(384)](typeof c,u(369))&&!a.includes(c)&&a.push(c)},o=c=>{const u=a.indexOf(c);u!==-1&&a.splice(u,1*-6854+8*-33+7119)},i=()=>{const c=Xe;a[c(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},Fx=t=>{const e=Xe,r=Xe,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)](rd);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)](rd);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)](rd);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function Di(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Di=function(){return t},Di()}const Zx=(t,{beforeInit:e,afterInit:r}={})=>{const a=Xe,n=Xe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](Fx,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,c=o.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},Vx=Qr,Hx=Qr;(function(t,e){const r=Qr,a=Qr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Li,-1*-881393+2*180895+1*-644809);function Qr(t,e){const r=Li();return Qr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},Qr(t,e)}function Li(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Li=function(){return t},Li()}const Bx=()=>{const t=Qr,e=Qr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},Jx=t=>{const e=Qr,r=Qr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},On={};On[Vx(391)]=Bx,On[Hx(396)]=Jx;const ur=Yr;(function(t,e){const r=Yr,a=Yr,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(zi,1472653*1+-2*-897917+-2275789);const Gx=(t,e)=>{const r=Yr,a=Yr,n={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};Dx(t,e),Lx(t,e);const s=zx(e,t),o=n[r(510)](qx,e,t),i=n[a(549)](Ux,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},nd=(t,e,r)=>{const a=Yr,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=a;n.pMiva(r,Hs)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),Gx(t,e)},o={};o.afterInit=s,n.fyZbd(Zx,e,o)},Hm=(t,e=On.randomUUID())=>{const r=Yr,a=Yr,n={OfssH:function(u,f,g){return u(f,g)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,f){const g=r,d=a,m=new Headers((f==null?void 0:f[g(558)])||{});Object.entries(o)[d(498)](([h,p])=>{m[d(527)](h,p)});const v={...f};return v[d(558)]=m,n.OfssH(fetch,u,v)},withCredentials:!0}};return t&&(c.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),c},Bm=(t,e=On[ur(517)]())=>{const r=ur,a=ur,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const c=l;return t&&(c.requestInit.headers[a(552)]=a(533)+t),c},ad=async(t,e,r)=>{const a=ur,n=ur,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof Rr){const l=await e();return await o[n(505)](l),await s[a(525)](ad,t,e,r)}else throw i}};function Yr(t,e){const r=zi();return Yr=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},Yr(t,e)}const Jm=(t,e)=>{const r=ur,a=ur,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},Kx=async t=>{const e=ur,r=ur,a={TFSRn:function(O,H,J){return O(H,J)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(O){return O()},WIVYl:function(O,H,J,K){return O(H,J,K)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=t,g={};g.authProvider=l,g.requestInit=c,g.eventSourceInit=u;const d=g,m=i||On.randomUUID(),v=a[e(506)](Hm,o,m);if(c){const O={...v.requestInit,...c};O.headers={...v[e(544)].headers,...c.headers},d.requestInit=O}else d[r(544)]=v.requestInit;if(u){const O={...v[e(559)],...u};d.eventSourceInit=O}else d.eventSourceInit=v.eventSourceInit;const h={};h.listChanged=!0;const p={};p.roots=h,p.sampling={},p[e(511)]={};const _=p,w={};w[r(536)]=a.HwvVa,w.version=e(526);const b={};b.capabilities=_;const S=new Us(w,b),x=()=>new Hs(new URL(s),d);let k=a[r(504)](x);if(l){const O=a[e(506)](Jm,l,f);k=await a[r(513)](ad,S,O,x)}else await S[e(538)](k);a[r(513)](nd,S,n,k),k[r(557)]=k[r(542)].searchParams[r(532)](a.jniGY);const A={};return A.transport=k,A.sessionId=k[e(557)],A};function zi(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return zi=function(){return t},zi()}const Wx=async t=>{const e=ur,r=ur,a={Vajmx:e(500),biJOc:function(O){return O()},zXcpO:function(O,H,J){return O(H,J)},zDnjZ:function(O,H,J,K){return O(H,J,K)},FQMAh:function(O,H,J,K){return O(H,J,K)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=t,g={};g.authProvider=l,g.requestInit=c,g.reconnectionOptions=u;const d=g,m=i||On.randomUUID(),v=Bm(o,m);if(c){const O={...v.requestInit,...c};O.headers={...v.requestInit.headers,...c.headers},d[e(544)]=O}else d.requestInit=v.requestInit;const h={};h.listChanged=!0;const p={};p[r(550)]=h,p.sampling={},p.elicitation={};const _=p,w={};w[e(536)]=a[r(508)],w[e(555)]="1.0.0";const b={};b.capabilities=_;const S=new Us(w,b),x=()=>new Bs(new URL(s),d);let k=a[e(503)](x);if(l){const O=a[e(501)](Jm,l,f);k=await a.zDnjZ(ad,S,O,x)}else await S.connect(k);a.FQMAh(nd,S,n,k);const A={};return A.transport=k,A[r(557)]=k.sessionId,A},Qx=async t=>{const e=ur,r=ur,a={QgzDy:e(540),jkaVB:function(p,_,w,b){return p(_,w,b)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const c={};c[e(550)]=l,c[e(515)]={},c[r(511)]={};const u=c,f={};f.name=a[r(548)],f[r(555)]=r(526);const g={};g.capabilities=u;const d=new Us(f,g),m=i||On[r(517)](),v=new Zm(new URL(s+e(522)+m+r(554)+o));await d.connect(v),a.jkaVB(nd,d,n,v);const h={};return h[e(512)]=v,h[r(557)]=m,h},Gs=er,Ui=er;function er(t,e){const r=qi();return er=function(a,n){return a=a-(-16761+51*337),r[a]},er(t,e)}(function(t,e){const r=er,a=er,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(qi,-220880+1*-333337+-2*-384996);function qi(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return qi=function(){return t},qi()}const Yx=()=>On.randomBytes(3485*1+-261+-3184);class Xx{constructor(e){const r=er,a=er;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||Yx(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=er,c=er,u={qITTp:function(m,v,h){return m(v,h)},qcFPW:l(452)},f=await u.qITTp(fetch,e,{method:u[l(453)]});!f.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,c(446)+f.statusText));const g=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!g.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+g.statusText);return}const d=await g[l(431)]();(i=(o=this[c(433)])[l(456)])==null||i.call(o,d[l(432)])}async getAuthCodeByStateFunction(e,r){const a=er,n=er,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=er,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[er(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Gs(447)](){return this[Gs(444)]}[Ui(435)](e){const r=Gs;this[r(444)]=e}[Ui(457)](){return this[Ui(439)]}saveTokens(e){this._tokens=e}[Ui(450)](e){this[Gs(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Gs(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=Zi,a=Zi,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Fi,-73523*-3+1*-407717+530518);function Fi(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return Fi=function(){return t},Fi()}function Zi(t,e){var r=Fi();return Zi=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},Zi(t,e)}class eI extends Uh{constructor(e,r){var a;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(fi.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=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._instructions=r==null?void 0:r.instructions,this.setRequestHandler(mh,n=>this._oninitialize(n)),this.setNotificationHandler(Zc,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)}),this._capabilities.logging&&this.setRequestHandler(hi,async(n,s)=>{var o;const i=s.sessionId||((o=s.requestInfo)===null||o===void 0?void 0:o.headers["mcp-session-id"])||void 0,{level:l}=n.params,c=fi.safeParse(l);return c.success&&this._loggingLevels.set(i,c.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qh(this._capabilities,e)}assertCapabilityForMethod(e){var r,a,n;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(!(!((a=this._clientCapabilities)===null||a===void 0)&&a.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.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}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (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:oh.includes(r)?r:Ms,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},xn)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},ru,r)}async elicitInput(e,r){const a=await this.request({method:"elicitation/create",params:e},nu,r);if(a.action==="accept"&&a.content)try{const n=new Tm,s=n.compile(e.requestedSchema);if(!s(a.content))throw new st(rt.InvalidParams,`Elicitation response content does not match requested schema: ${n.errorsText(s.errors)}`)}catch(n){throw n instanceof st?n:new st(rt.InternalError,`Error validating elicitation response: ${n}`)}return a}async listRoots(e,r){return this.request({method:"roots/list",params:e},su,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 tI=Symbol("Let zodToJsonSchema decide on which parser to use"),Gm={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"},rI=t=>typeof t=="string"?{...Gm,name:t}:{...Gm,...t},nI=t=>{const e=rI(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(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Km(t,e,r,a){a!=null&&a.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ke(t,e,r,a,n){t[e]=r,Km(t,e,a,n)}const Wm=(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 tr(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Wm(e,t.currentPath):e.join("/")}}function aI(t,e){var a,n,s;const r={type:"array"};return(a=t.type)!=null&&a._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==V.ZodAny&&(r.items=Je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ke(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ke(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ke(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ke(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function sI(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?Ke(r,"minimum",a.value,a.message,e):Ke(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ke(r,"maximum",a.value,a.message,e):Ke(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ke(r,"multipleOf",a.value,a.message,e);break}return r}function oI(){return{type:"boolean"}}function Qm(t,e){return Je(t.type._def,e)}const iI=(t,e)=>Je(t.innerType._def,e);function Ym(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Ym(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return lI(t,e)}}const lI=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const a of t.checks)switch(a.kind){case"min":Ke(r,"minimum",a.value,a.message,e);break;case"max":Ke(r,"maximum",a.value,a.message,e);break}return r};function cI(t,e){return{...Je(t.innerType._def,e),default:t.defaultValue()}}function uI(t,e){return e.effectStrategy==="input"?Je(t.schema._def,e):tr(e)}function dI(t){return{type:"string",enum:Array.from(t.values)}}const pI=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function fI(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(s=>!!s);let a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach(s=>{if(pI(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(a=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;o=l}else a=void 0;n.push(o)}}),n.length?{allOf:n,...a}:void 0}function hI(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 sd;const Or={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(sd===void 0&&(sd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),sd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Xm(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e);break;case"max":Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Nr(r,"email",a.message,e);break;case"format:idn-email":Nr(r,"idn-email",a.message,e);break;case"pattern:zod":Jt(r,Or.email,a.message,e);break}break;case"url":Nr(r,"uri",a.message,e);break;case"uuid":Nr(r,"uuid",a.message,e);break;case"regex":Jt(r,a.regex,a.message,e);break;case"cuid":Jt(r,Or.cuid,a.message,e);break;case"cuid2":Jt(r,Or.cuid2,a.message,e);break;case"startsWith":Jt(r,RegExp(`^${od(a.value,e)}`),a.message,e);break;case"endsWith":Jt(r,RegExp(`${od(a.value,e)}$`),a.message,e);break;case"datetime":Nr(r,"date-time",a.message,e);break;case"date":Nr(r,"date",a.message,e);break;case"time":Nr(r,"time",a.message,e);break;case"duration":Nr(r,"duration",a.message,e);break;case"length":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e),Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"includes":{Jt(r,RegExp(od(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Nr(r,"ipv4",a.message,e),a.version!=="v4"&&Nr(r,"ipv6",a.message,e);break}case"base64url":Jt(r,Or.base64url,a.message,e);break;case"jwt":Jt(r,Or.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Jt(r,Or.ipv4Cidr,a.message,e),a.version!=="v4"&&Jt(r,Or.ipv6Cidr,a.message,e);break}case"emoji":Jt(r,Or.emoji(),a.message,e);break;case"ulid":{Jt(r,Or.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Nr(r,"binary",a.message,e);break}case"contentEncoding:base64":{Ke(r,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{Jt(r,Or.base64,a.message,e);break}}break}case"nanoid":Jt(r,Or.nanoid,a.message,e)}return r}function od(t,e){return e.patternStrategy==="escape"?vI(t):t}const mI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vI(t){let e="";for(let r=0;r<t.length;r++)mI.has(t[r])||(e+="\\"),e+=t[r];return e}function Nr(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&a.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&&a.errorMessages&&{errorMessage:{format:r}}})):Ke(t,"format",e,r,a)}function Jt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&a.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:ev(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):Ke(t,"pattern",ev(e,a),r,a)}function ev(t,e){var l;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")},a=r.i?t.source.toLowerCase():t.source;let n="",s=!1,o=!1,i=!1;for(let c=0;c<a.length;c++){if(s){n+=a[c],s=!1;continue}if(r.i){if(o){if(a[c].match(/[a-z]/)){i?(n+=a[c],n+=`${a[c-2]}-${a[c]}`.toUpperCase(),i=!1):a[c+1]==="-"&&((l=a[c+2])!=null&&l.match(/[a-z]/))?(n+=a[c],i=!0):n+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){n+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){n+=`(^|(?<=[\r
13
- ]))`;continue}else if(a[c]==="$"){n+=`($|(?=[\r
14
- ]))`;continue}}if(r.s&&a[c]==="."){n+=o?`${a[c]}\r
15
- `:`[${a[c]}\r
16
- ]`;continue}n+=a[c],a[c]==="\\"?s=!0:o&&a[c]==="]"?o=!1:!o&&a[c]==="["&&(o=!0)}try{new RegExp(n)}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 n}function tv(t,e){var a,n,s,o,i,l;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"&&((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,u)=>({...c,[u]:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??tr(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(((n=t.keyType)==null?void 0:n._def.typeName)===V.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=Xm(t.keyType._def,e);return{...r,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((i=t.keyType)==null?void 0:i._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...u}=Qm(t.keyType._def,e);return{...r,propertyNames:u}}}return r}function gI(t,e){if(e.mapStrategy==="record")return tv(t,e);const r=Je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||tr(e),a=Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||tr(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function yI(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function _I(t){return t.target==="openAi"?void 0:{not:tr({...t,currentPath:[...t.currentPath,"not"]})}}function wI(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Vi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bI(t,e){if(e.target==="openApi3")return rv(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Vi&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Vi[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return rv(t,e)}const rv=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>Je(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function EI(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:Vi[t.innerType._def.typeName],nullable:!0}:{type:[Vi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const a=Je(t.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}const r=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function SI(t,e){const r={type:"number"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"int":r.type="integer",Km(r,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?Ke(r,"minimum",a.value,a.message,e):Ke(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ke(r,"maximum",a.value,a.message,e):Ke(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ke(r,"multipleOf",a.value,a.message,e);break}return r}function $I(t,e){const r=e.target==="openAi",a={type:"object",properties:{}},n=[],s=t.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=kI(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Je(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(a.properties[i]=u,c||n.push(i))}n.length&&(a.required=n);const o=PI(t,e);return o!==void 0&&(a.additionalProperties=o),a}function PI(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 kI(t){try{return t.isOptional()}catch{return!0}}const xI=(t,e)=>{var a;if(e.currentPath.toString()===((a=e.propertyPath)==null?void 0:a.toString()))return Je(t.innerType._def,e);const r=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:tr(e)},r]}:tr(e)},II=(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"]}),a=Je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function TI(t,e){return Je(t.type._def,e)}function CI(t,e){const a={type:"array",uniqueItems:!0,items:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ke(a,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ke(a,"maxItems",t.maxSize.value,t.maxSize.message,e),a}function RI(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>Je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),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,a)=>Je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function OI(t){return{not:tr(t)}}function NI(t){return tr(t)}const AI=(t,e)=>Je(t.innerType._def,e),MI=(t,e,r)=>{switch(e){case V.ZodString:return Xm(t,r);case V.ZodNumber:return SI(t,r);case V.ZodObject:return $I(t,r);case V.ZodBigInt:return sI(t,r);case V.ZodBoolean:return oI();case V.ZodDate:return Ym(t,r);case V.ZodUndefined:return OI(r);case V.ZodNull:return wI(r);case V.ZodArray:return aI(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return bI(t,r);case V.ZodIntersection:return fI(t,r);case V.ZodTuple:return RI(t,r);case V.ZodRecord:return tv(t,r);case V.ZodLiteral:return hI(t,r);case V.ZodEnum:return dI(t);case V.ZodNativeEnum:return yI(t);case V.ZodNullable:return EI(t,r);case V.ZodOptional:return xI(t,r);case V.ZodMap:return gI(t,r);case V.ZodSet:return CI(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return TI(t,r);case V.ZodNaN:case V.ZodNever:return _I(r);case V.ZodEffects:return uI(t,r);case V.ZodAny:return tr(r);case V.ZodUnknown:return NI(r);case V.ZodDefault:return cI(t,r);case V.ZodBranded:return Qm(t,r);case V.ZodReadonly:return AI(t,r);case V.ZodCatch:return iI(t,r);case V.ZodPipeline:return II(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function Je(t,e,r=!1){var i;const a=e.seen.get(t);if(e.override){const l=(i=e.override)==null?void 0:i.call(e,t,e,a,r);if(l!==tI)return l}if(a&&!r){const l=jI(a,e);if(l!==void 0)return l}const n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);const s=MI(t,t.typeName,e),o=typeof s=="function"?Je(s(),e):s;if(o&&DI(t,e,o),e.postProcess){const l=e.postProcess(o,t,e);return n.jsonSchema=o,l}return n.jsonSchema=o,o}const jI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Wm(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),tr(e)):e.$refStrategy==="seen"?tr(e):void 0}},DI=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),nv=(t,e)=>{const r=nI(e);let a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Je(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??tr(r)}),{}):void 0;const n=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=Je(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??tr(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[r.openAiAnyTypeName]||(a[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=n===void 0?a?{...s,[r.definitionPath]:a}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var id;(function(t){t.Completable="McpCompletable"})(id||(id={}));class Hi extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}Hi.create=(t,e)=>new Hi({type:t,typeName:id.Completable,complete:e.complete,...zI(e)});function LI(t,e){return Hi.create(t,{...t._def,complete:e})}function zI(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{var l,c;const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??i.defaultError}:typeof i.data>"u"?{message:(l=u??a)!==null&&l!==void 0?l:i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:(c=u??r)!==null&&c!==void 0?c:i.defaultError}},description:n}}const av=1e6,ld=1e6,sv=1e4,UI=1e6;class yn{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,a){if(e.length>r)throw new Error(`${a} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){yn.validateLength(e,av,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let a="",n=0,s=0;for(;n<e.length;)if(e[n]==="{"){a&&(r.push(a),a="");const o=e.indexOf("}",n);if(o===-1)throw new Error("Unclosed template expression");if(s++,s>sv)throw new Error(`Template contains too many expressions (max ${sv})`);const i=e.slice(n+1,o),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),f=u[0];for(const g of u)yn.validateLength(g,ld,"Variable name");r.push({name:f,operator:l,names:u,exploded:c}),n=o+1}else a+=e[n],n++;return a&&r.push(a),r}getOperator(e){return["+","#",".","/","?","&"].find(a=>e.startsWith(a))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(a=>a.replace("*","").trim()).filter(a=>a.length>0)}encodeValue(e,r){return yn.validateLength(e,ld,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const o=e.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(f=>this.encodeValue(f,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${l}=${u}`}).filter(l=>l.length>0);return o.length===0?"":(e.operator==="?"?"?":"&")+o.join("&")}if(e.names.length>1){const o=e.names.map(i=>r[i]).filter(i=>i!==void 0);return o.length===0?"":o.map(i=>Array.isArray(i)?i[0]:i).join(",")}const a=r[e.name];if(a===void 0)return"";const s=(Array.isArray(a)?a:[a]).map(o=>this.encodeValue(o,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",a=!1;for(const n of this.parts){if(typeof n=="string"){r+=n;continue}const s=this.expandPart(n,e);s&&((n.operator==="?"||n.operator==="&")&&a?r+=s.replace("?","&"):r+=s,(n.operator==="?"||n.operator==="&")&&(a=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const s of e.names)yn.validateLength(s,ld,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){const o=e.names[s],i=s===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(o)+"=([^&]+)",name:o})}return r}let a;const n=e.name;switch(e.operator){case"":a=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":a="(.+)";break;case".":a="\\.([^/,]+)";break;case"/":a="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:a="([^/]+)"}return r.push({pattern:a,name:n}),r}match(e){yn.validateLength(e,av,"URI");let r="^";const a=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)r+=c,a.push({name:u,exploded:i.exploded})}r+="$",yn.validateLength(r,UI,"Generated regex pattern");const n=new RegExp(r),s=e.match(n);if(!s)return null;const o={};for(let i=0;i<a.length;i++){const{name:l,exploded:c}=a[i],u=s[i+1],f=l.replace("*","");c&&u.includes(",")?o[f]=u.split(","):o[f]=u}return o}}class ov{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 eI(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(eu.shape.method.value),this.server.assertCanSetRequestHandler(tu.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(eu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const a={name:e,title:r.title,description:r.description,inputSchema:r.inputSchema?nv(r.inputSchema,{strictUnions:!0}):FI,annotations:r.annotations,_meta:r._meta};return r.outputSchema&&(a.outputSchema=nv(r.outputSchema,{strictUnions:!0})),a})})),this.server.setRequestHandler(tu,async(e,r)=>{const a=this._registeredTools[e.params.name];if(!a)throw new st(rt.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Tool ${e.params.name} disabled`);let n;if(a.inputSchema){const s=await a.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new st(rt.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const o=s.data,i=a.callback;try{n=await Promise.resolve(i(o,r))}catch(l){n={content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}else{const s=a.callback;try{n=await Promise.resolve(s(r))}catch(o){n={content:[{type:"text",text:o instanceof Error?o.message:String(o)}],isError:!0}}}if(a.outputSchema&&!n.isError){if(!n.structuredContent)throw new st(rt.InvalidParams,`Tool ${e.params.name} has an output schema but no structured content was provided`);const s=await a.outputSchema.safeParseAsync(n.structuredContent);if(!s.success)throw new st(rt.InvalidParams,`Invalid structured content for tool ${e.params.name}: ${s.error.message}`)}return n}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(au.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(au,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new st(rt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const a=this._registeredPrompts[r.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${r.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${r.name} disabled`);if(!a.argsSchema)return Bi;const n=a.argsSchema.shape[e.params.argument.name];if(!(n instanceof Hi))return Bi;const o=await n._def.complete(e.params.argument.value,e.params.context);return lv(o)}async handleResourceCompletion(e,r){const a=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!a){if(this._registeredResources[r.uri])return Bi;throw new st(rt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=a.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Bi;const s=await n(e.params.argument.value,e.params.context);return lv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(di.shape.method.value),this.server.assertCanSetRequestHandler(Jc.shape.method.value),this.server.assertCanSetRequestHandler(Gc.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(di,async(e,r)=>{const a=Object.entries(this._registeredResources).filter(([s,o])=>o.enabled).map(([s,o])=>({uri:s,name:o.name,...o.metadata})),n=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const o=await s.resourceTemplate.listCallback(r);for(const i of o.resources)n.push({...s.metadata,...i})}return{resources:[...a,...n]}}),this.server.setRequestHandler(Jc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,a])=>({name:r,uriTemplate:a.resourceTemplate.uriTemplate.toString(),...a.metadata}))})),this.server.setRequestHandler(Gc,async(e,r)=>{const a=new URL(e.params.uri),n=this._registeredResources[a.toString()];if(n){if(!n.enabled)throw new st(rt.InvalidParams,`Resource ${a} disabled`);return n.readCallback(a,r)}for(const s of Object.values(this._registeredResourceTemplates)){const o=s.resourceTemplate.uriTemplate.match(a.toString());if(o)return s.readCallback(a,o,r)}throw new st(rt.InvalidParams,`Resource ${a} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Kc.shape.method.value),this.server.assertCanSetRequestHandler(Wc.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Kc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?VI(r.argsSchema):void 0}))})),this.server.setRequestHandler(Wc,async(e,r)=>{const a=this._registeredPrompts[e.params.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){const n=await a.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new st(rt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);const s=n.data,o=a.callback;return await Promise.resolve(o(s,r))}else{const n=a.callback;return await Promise.resolve(n(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...a){let n;typeof a[0]=="object"&&(n=a.shift());const s=a[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,void 0,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,void 0,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,a,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,a,n,s){const o={name:e,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==a&&(delete this._registeredResources[a],i.uri&&(this._registeredResources[i.uri]=o)),typeof i.name<"u"&&(o.name=i.name),typeof i.title<"u"&&(o.title=i.title),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=o,o}_createRegisteredResourceTemplate(e,r,a,n,s){const o={resourceTemplate:a,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.template<"u"&&(o.resourceTemplate=i.template),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=o,o}_createRegisteredPrompt(e,r,a,n,s){const o={title:r,description:a,argsSchema:n===void 0?void 0:te(n),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.description<"u"&&(o.description=i.description),typeof i.argsSchema<"u"&&(o.argsSchema=te(i.argsSchema)),typeof i.callback<"u"&&(o.callback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,o}_createRegisteredTool(e,r,a,n,s,o,i,l){const c={title:r,description:a,inputSchema:n===void 0?void 0:te(n),outputSchema:s===void 0?void 0:te(s),annotations:o,_meta:i,callback:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredTools[e],u.name&&(this._registeredTools[u.name]=c)),typeof u.title<"u"&&(c.title=u.title),typeof u.description<"u"&&(c.description=u.description),typeof u.paramsSchema<"u"&&(c.inputSchema=te(u.paramsSchema)),typeof u.callback<"u"&&(c.callback=u.callback),typeof u.annotations<"u"&&(c.annotations=u.annotations),typeof u._meta<"u"&&(c._meta=u._meta),typeof u.enabled<"u"&&(c.enabled=u.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let a,n,s,o;if(typeof r[0]=="string"&&(a=r.shift()),r.length>1){const l=r[0];iv(l)?(n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!iv(r[0])&&(o=r.shift())):typeof l=="object"&&l!==null&&(o=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,a,n,s,o,void 0,i)}registerTool(e,r,a){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:s,inputSchema:o,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(e,n,s,o,i,l,c,a)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let a;typeof r[0]=="string"&&(a=r.shift());let n;r.length>1&&(n=r.shift());const s=r[0],o=this._createRegisteredPrompt(e,void 0,a,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,a){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:s,argsSchema:o}=r,i=this._createRegisteredPrompt(e,n,s,o,a);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 qI{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new yn(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 FI={type:"object",properties:{}};function iv(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(ZI)}function ZI(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function VI(t){return Object.entries(t.shape).map(([e,r])=>({name:e,description:r.description,required:!r.isOptional()}))}function lv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const Bi={completion:{values:[],hasMore:!1}};function HI(t){var e;if(t.title!==void 0&&t.title!=="")return t.title;if("annotations"in t){const r=t;if(!((e=r.annotations)===null||e===void 0)&&e.title)return r.annotations.title}return t.name}class Ks{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new Ks,r=new Ks;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==null?void 0: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==null?void 0:r.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r==null?void 0:r.authInfo}})}}class BI{constructor(e,r){const a={name:"web-mcp-server",version:"1.0.0"},n={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new ov(e||a,r||{capabilities:n}),this.server.server.oninitialized=()=>{var s;(s=this.oninitialized)==null||s.call(this)},this.server.server.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.server.server.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)},this.server.server.setRequestHandler(hi,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 td(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,a){return this.server.registerTool(e,r,a)}registerPrompt(e,r,a){return this.server.registerPrompt(e,r,a)}registerResource(e,r,a,n){return typeof r=="string"?this.server.registerResource(e,r,a,n):this.server.registerResource(e,r,a,n)}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,a){return this.server.server.request(e,r,a)}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(Ph,e)}onUnsubscribe(e){this.server.server.setRequestHandler(kh,e)}onSetLogLevel(e){this.server.server.setRequestHandler(hi,e)}onListResources(e){this.server.server.setRequestHandler(di,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(zh,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const JI=(t,e)=>new td(t,e),GI=()=>Ax(),KI=t=>t instanceof td,WI=t=>t instanceof ov;class cv{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Us(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}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:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const u={client:this.client,url:r,token:a,sessionId:n};let f;return await(async()=>{const{transport:d,sessionId:m}=s==="sse"?await Kx(u):s==="socket"?await Qx(u):await Wx(u);d.onerror=async v=>{i==null||i(v)},f={transport:d,sessionId:m}})(),f}const l=new URL(r);let c;if(s==="channel"&&(c=new ed(r),await this.client.connect(c)),s==="sse"){const u=Hm(a,n);c=new Hs(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Zm(new URL(`${r}?sessionId=${n}&token=${a}`)),c.sessionId=n,await this.client.connect(c)),typeof c>"u"){const u=Bm(a,n);c=new Bs(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(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,pi,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}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(jh,e)}onCreateMessage(e){this.client.setRequestHandler(Mh,e)}onListRoots(e){this.client.setRequestHandler(Lh,e)}onToolListChanged(e){this.client.setNotificationHandler(Nh,e)}onPromptListChanged(e){this.client.setNotificationHandler(Rh,e)}onResourceListChanged(e){this.client.setNotificationHandler($h,e)}onResourceUpdated(e){this.client.setNotificationHandler(xh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Ah,e)}async onPagehide(e){e.persisted||(uv(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const QI=(t,e)=>new Hs(t,e),YI=(t,e)=>new Bs(t,e),XI=(t,e)=>new ed(t,e),eT=t=>t instanceof Hs,uv=t=>t instanceof Bs,tT=t=>t instanceof ed,rT=t=>t instanceof Us,Va=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},dv=(t,e,r)=>{const a=async function(n){n.source===window&&n.data.type===t&&n.data.direction===r&&await e(n.data.data)};return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},cd=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},ud=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r&&(!a||a&&s.tabId===a)){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class pv{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=ud("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=vn.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}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 a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];cd("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,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 fv=()=>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 nT{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||fv(),this.tabId=r,this._messageListener1=dv("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.error("【Page Svr Transport】 notifyRegistration失败:",a)})},"content->page"),this._messageListener2=dv("mcp-client-to-server-to-page",a=>{var o,i,l;if(a.sessionId!==this.sessionId||a.tabId!==this.tabId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",a.mcpMessage);const n=vn.parse(a.mcpMessage);(o=this.onmessage)==null||o.call(this,n),((i=a.mcpMessage.params)==null?void 0:i.name)&&Va("update-page-app-message",{status:"run",message:(l=a.mcpMessage.params)==null?void 0:l.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Va("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&((a=e.result)!=null&&a.content)&&Va("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Va("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 aT{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||fv(),this.tabId=r,ud("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.log("【Content Svr Transport】 notifyRegistration 失败",a)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");ud("mcp-client-to-server",e=>{var r,a,n;if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const s=vn.parse(e.mcpMessage);(r=this.onmessage)==null||r.call(this,s),((a=e.mcpMessage.params)==null?void 0:a.name)&&Va("update-page-app-message",{status:"run",message:(n=e.mcpMessage.params)==null?void 0:n.name},"page->content")}catch(s){console.log("【Content Svr Transport】 处理消息时发生错误:",s)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),cd("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&((a=e.result)!=null&&a.content)&&Va("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,cd("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 Ha={},sT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},hv={},dr={};let dd;const oT=[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];dr.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},dr.getSymbolTotalCodewords=function(e){return oT[e]},dr.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},dr.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');dd=e},dr.isKanjiModeEnabled=function(){return typeof dd<"u"},dr.toSJIS=function(e){return dd(e)};var Ji={};(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(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(Ji);function mv(){this.buffer=[],this.length=0}mv.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var iT=mv;function Ws(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Ws.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},Ws.prototype.get=function(t,e){return this.data[t*this.size+e]},Ws.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},Ws.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var lT=Ws,vv={};(function(t){const e=dr.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(vv);var gv={};const cT=dr.getSymbolSize,yv=7;gv.getPositions=function(e){const r=cT(e);return[[0,0],[r-yv,0],[0,r-yv]]};var _v={};(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(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,c=null,u=null;for(let f=0;f<s;f++){i=l=0,c=u=null;for(let g=0;g<s;g++){let d=n.get(f,g);d===c?i++:(i>=5&&(o+=e.N1+(i-5)),c=d,i=1),d=n.get(g,f),d===u?l++:(l>=5&&(o+=e.N1+(l-5)),u=d,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(c===4||c===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|n.get(c,u),u>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(u,c),u>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let c=0;c<o;c++){s(c),t.applyMask(c,n);const u=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(c,n),u<l&&(l=u,i=c)}return i}})(_v);var Gi={};const Nn=Ji,Ki=[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],Wi=[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];Gi.getBlocksCount=function(e,r){switch(r){case Nn.L:return Ki[(e-1)*4+0];case Nn.M:return Ki[(e-1)*4+1];case Nn.Q:return Ki[(e-1)*4+2];case Nn.H:return Ki[(e-1)*4+3];default:return}},Gi.getTotalCodewordsCount=function(e,r){switch(r){case Nn.L:return Wi[(e-1)*4+0];case Nn.M:return Wi[(e-1)*4+1];case Nn.Q:return Wi[(e-1)*4+2];case Nn.H:return Wi[(e-1)*4+3];default:return}};var wv={},Qi={};const Qs=new Uint8Array(512),Yi=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Qs[r]=e,Yi[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Qs[r]=Qs[r-255]})(),Qi.log=function(e){if(e<1)throw new Error("log("+e+")");return Yi[e]},Qi.exp=function(e){return Qs[e]},Qi.mul=function(e,r){return e===0||r===0?0:Qs[Yi[e]+Yi[r]]},function(t){const e=Qi;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(wv);const bv=wv;function pd(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}pd.prototype.initialize=function(e){this.degree=e,this.genPoly=bv.generateECPolynomial(this.degree)},pd.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=bv.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var uT=pd,Ev={},An={},fd={};fd.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var Xr={};const Sv="[0-9]+",dT="[A-Z $%*+\\-./:]+";let Ys="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ys=Ys.replace(/u/g,"\\u");const pT="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ys+`)(?:.|[\r
17
- ]))+`;Xr.KANJI=new RegExp(Ys,"g"),Xr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Xr.BYTE=new RegExp(pT,"g"),Xr.NUMERIC=new RegExp(Sv,"g"),Xr.ALPHANUMERIC=new RegExp(dT,"g");const fT=new RegExp("^"+Ys+"$"),hT=new RegExp("^"+Sv+"$"),mT=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Xr.testKanji=function(e){return fT.test(e)},Xr.testNumeric=function(e){return hT.test(e)},Xr.testAlphanumeric=function(e){return mT.test(e)},function(t){const e=fd,r=Xr;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(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.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: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(An),function(t){const e=dr,r=Gi,a=Ji,n=An,s=fd,o=7973,i=e.getBCHDigit(o);function l(g,d,m){for(let v=1;v<=40;v++)if(d<=t.getCapacity(v,m,g))return v}function c(g,d){return n.getCharCountIndicator(g,d)+4}function u(g,d){let m=0;return g.forEach(function(v){const h=c(v.mode,d);m+=h+v.getBitsLength()}),m}function f(g,d){for(let m=1;m<=40;m++)if(u(g,m)<=t.getCapacity(m,d,n.MIXED))return m}t.from=function(d,m){return s.isValid(d)?parseInt(d,10):m},t.getCapacity=function(d,m,v){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=n.BYTE);const h=e.getSymbolTotalCodewords(d),p=r.getTotalCodewordsCount(d,m),_=(h-p)*8;if(v===n.MIXED)return _;const w=_-c(v,d);switch(v){case n.NUMERIC:return Math.floor(w/10*3);case n.ALPHANUMERIC:return Math.floor(w/11*2);case n.KANJI:return Math.floor(w/13);case n.BYTE:default:return Math.floor(w/8)}},t.getBestVersionForData=function(d,m){let v;const h=a.from(m,a.M);if(Array.isArray(d)){if(d.length>1)return f(d,h);if(d.length===0)return 1;v=d[0]}else v=d;return l(v.mode,v.getLength(),h)},t.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let m=d<<12;for(;e.getBCHDigit(m)-i>=0;)m^=o<<e.getBCHDigit(m)-i;return d<<12|m}}(Ev);var $v={};const hd=dr,Pv=1335,vT=21522,kv=hd.getBCHDigit(Pv);$v.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;hd.getBCHDigit(n)-kv>=0;)n^=Pv<<hd.getBCHDigit(n)-kv;return(a<<10|n)^vT};var xv={};const gT=An;function Ba(t){this.mode=gT.NUMERIC,this.data=t.toString()}Ba.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},Ba.prototype.getLength=function(){return this.data.length},Ba.prototype.getBitsLength=function(){return Ba.getBitsLength(this.data.length)},Ba.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var yT=Ba;const _T=An,md=["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 Ja(t){this.mode=_T.ALPHANUMERIC,this.data=t}Ja.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},Ja.prototype.getLength=function(){return this.data.length},Ja.prototype.getBitsLength=function(){return Ja.getBitsLength(this.data.length)},Ja.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=md.indexOf(this.data[r])*45;a+=md.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(md.indexOf(this.data[r]),6)};var wT=Ja;const bT=An;function Ga(t){this.mode=bT.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ga.getBitsLength=function(e){return e*8},Ga.prototype.getLength=function(){return this.data.length},Ga.prototype.getBitsLength=function(){return Ga.getBitsLength(this.data.length)},Ga.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var ET=Ga;const ST=An,$T=dr;function Ka(t){this.mode=ST.KANJI,this.data=t}Ka.getBitsLength=function(e){return e*13},Ka.prototype.getLength=function(){return this.data.length},Ka.prototype.getBitsLength=function(){return Ka.getBitsLength(this.data.length)},Ka.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=$T.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
18
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var PT=Ka,Iv={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,c,u,f,g,d,m,v,h;!i.empty();){l=i.pop(),c=l.value,f=l.cost,g=r[c]||{};for(u in g)g.hasOwnProperty(u)&&(d=g[u],m=f+d,v=o[u],h=typeof o[u]>"u",(h||v>m)&&(o[u]=m,i.push(u,m),s[u]=c))}if(typeof n<"u"&&typeof o[n]>"u"){var p=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Iv);var kT=Iv.exports;(function(t){const e=An,r=yT,a=wT,n=ET,s=PT,o=Xr,i=dr,l=kT;function c(p){return unescape(encodeURIComponent(p)).length}function u(p,_,w){const b=[];let S;for(;(S=p.exec(w))!==null;)b.push({data:S[0],index:S.index,mode:_,length:S[0].length});return b}function f(p){const _=u(o.NUMERIC,e.NUMERIC,p),w=u(o.ALPHANUMERIC,e.ALPHANUMERIC,p);let b,S;return i.isKanjiModeEnabled()?(b=u(o.BYTE,e.BYTE,p),S=u(o.KANJI,e.KANJI,p)):(b=u(o.BYTE_KANJI,e.BYTE,p),S=[]),_.concat(w,b,S).sort(function(k,A){return k.index-A.index}).map(function(k){return{data:k.data,mode:k.mode,length:k.length}})}function g(p,_){switch(_){case e.NUMERIC:return r.getBitsLength(p);case e.ALPHANUMERIC:return a.getBitsLength(p);case e.KANJI:return s.getBitsLength(p);case e.BYTE:return n.getBitsLength(p)}}function d(p){return p.reduce(function(_,w){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===w.mode?(_[_.length-1].data+=w.data,_):(_.push(w),_)},[])}function m(p){const _=[];for(let w=0;w<p.length;w++){const b=p[w];switch(b.mode){case e.NUMERIC:_.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:_.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:_.push([b,{data:b.data,mode:e.BYTE,length:c(b.data)}]);break;case e.BYTE:_.push([{data:b.data,mode:e.BYTE,length:c(b.data)}])}}return _}function v(p,_){const w={},b={start:{}};let S=["start"];for(let x=0;x<p.length;x++){const k=p[x],A=[];for(let O=0;O<k.length;O++){const H=k[O],J=""+x+O;A.push(J),w[J]={node:H,lastCount:0},b[J]={};for(let K=0;K<S.length;K++){const z=S[K];w[z]&&w[z].node.mode===H.mode?(b[z][J]=g(w[z].lastCount+H.length,H.mode)-g(w[z].lastCount,H.mode),w[z].lastCount+=H.length):(w[z]&&(w[z].lastCount=H.length),b[z][J]=g(H.length,H.mode)+4+e.getCharCountIndicator(H.mode,_))}}S=A}for(let x=0;x<S.length;x++)b[S[x]].end=0;return{map:b,table:w}}function h(p,_){let w;const b=e.getBestModeForData(p);if(w=e.from(_,b),w!==e.BYTE&&w.bit<b.bit)throw new Error('"'+p+'" cannot be encoded with mode '+e.toString(w)+`.
19
- Suggested mode is: `+e.toString(b));switch(w===e.KANJI&&!i.isKanjiModeEnabled()&&(w=e.BYTE),w){case e.NUMERIC:return new r(p);case e.ALPHANUMERIC:return new a(p);case e.KANJI:return new s(p);case e.BYTE:return new n(p)}}t.fromArray=function(_){return _.reduce(function(w,b){return typeof b=="string"?w.push(h(b,null)):b.data&&w.push(h(b.data,b.mode)),w},[])},t.fromString=function(_,w){const b=f(_,i.isKanjiModeEnabled()),S=m(b),x=v(S,w),k=l.find_path(x.map,"start","end"),A=[];for(let O=1;O<k.length-1;O++)A.push(x.table[k[O]].node);return t.fromArray(d(A))},t.rawSplit=function(_){return t.fromArray(f(_,i.isKanjiModeEnabled()))}})(xv);const Xi=dr,vd=Ji,xT=iT,IT=lT,TT=vv,CT=gv,gd=_v,yd=Gi,RT=uT,el=Ev,OT=$v,NT=An,_d=xv;function AT(t,e){const r=t.size,a=CT.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function MT(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function jT(t,e){const r=TT.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function DT(t,e){const r=t.size,a=el.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function wd(t,e,r){const a=t.size,n=OT.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function LT(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(n,i-l,c),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function zT(t,e,r){const a=new xT;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),NT.getCharCountIndicator(l.mode,t)),l.write(a)});const n=Xi.getSymbolTotalCodewords(t),s=yd.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return UT(a,t,e)}function UT(t,e,r){const a=Xi.getSymbolTotalCodewords(e),n=yd.getTotalCodewordsCount(e,r),s=a-n,o=yd.getBlocksCount(e,r),i=a%o,l=o-i,c=Math.floor(a/o),u=Math.floor(s/o),f=u+1,g=c-u,d=new RT(g);let m=0;const v=new Array(o),h=new Array(o);let p=0;const _=new Uint8Array(t.buffer);for(let k=0;k<o;k++){const A=k<l?u:f;v[k]=_.slice(m,m+A),h[k]=d.encode(v[k]),m+=A,p=Math.max(p,A)}const w=new Uint8Array(a);let b=0,S,x;for(S=0;S<p;S++)for(x=0;x<o;x++)S<v[x].length&&(w[b++]=v[x][S]);for(S=0;S<g;S++)for(x=0;x<o;x++)w[b++]=h[x][S];return w}function qT(t,e,r,a){let n;if(Array.isArray(t))n=_d.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){const u=_d.rawSplit(t);c=el.getBestVersionForData(u,r)}n=_d.fromString(t,c||40)}else throw new Error("Invalid data");const s=el.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
8
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const y=Array.isArray(l[h])?c:u;y[h]=l[h]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:h,it:y}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const m=(0,r.propertyInData)(u,h,g,y.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),y.allErrors?u.if(m,()=>{for(const d of v)(0,r.checkReportMissingProp)(l,d)}):(u.if((0,t._)`${m} && (${(0,r.checkMissingProp)(l,v,f)})`),(0,r.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:h,keyword:y,it:f}=l,g=u.name("valid");for(const v in c)(0,n.alwaysValidSchema)(f,c[v])||(u.if((0,r.propertyInData)(u,h,v,f.opts.ownProperties),()=>{const m=l.subschema({keyword:y,schemaProp:v},g);l.mergeValidEvaluated(m,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=i,e.default=o})(Hp);var Pl={};Object.defineProperty(Pl,"__esModule",{value:!0});const Jp=me,xw=K,Ew={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>(0,Jp._)`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,xw.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,a=>{e.setParams({propertyName:a}),e.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},s),t.if((0,Jp.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Pl.default=Ew;var fa={};Object.defineProperty(fa,"__esModule",{value:!0});const ha=_e,en=me,Iw=yn,ma=K,Pw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>(0,en._)`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:l}=a;if(a.props=!0,l.removeAdditional!=="all"&&(0,ma.alwaysValidSchema)(a,n))return;const c=(0,ha.allSchemaProperties)(r.properties),u=(0,ha.allSchemaProperties)(r.patternProperties);h(),e.ok((0,en._)`${s} === ${Iw.default.errors}`);function h(){t.forIn("key",o,m=>{!c.length&&!u.length?g(m):t.if(y(m),()=>g(m))})}function y(m){let d;if(c.length>8){const w=(0,ma.schemaRefOrVal)(a,r.properties,"properties");d=(0,ha.isOwnProperty)(t,w,m)}else c.length?d=(0,en.or)(...c.map(w=>(0,en._)`${m} === ${w}`)):d=en.nil;return u.length&&(d=(0,en.or)(d,...u.map(w=>(0,en._)`${(0,ha.usePattern)(e,w)}.test(${m})`))),(0,en.not)(d)}function f(m){t.code((0,en._)`delete ${o}[${m}]`)}function g(m){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){f(m);return}if(n===!1){e.setParams({additionalProperty:m}),e.error(),i||t.break();return}if(typeof n=="object"&&!(0,ma.alwaysValidSchema)(a,n)){const d=t.name("valid");l.removeAdditional==="failing"?(v(m,d,!1),t.if((0,en.not)(d),()=>{e.reset(),f(m)})):(v(m,d),i||t.if((0,en.not)(d),()=>t.break()))}}function v(m,d,w){const _={keyword:"additionalProperties",dataProp:m,dataPropType:ma.Type.Str};w===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(_,d)}}};fa.default=Pw;var Rl={};Object.defineProperty(Rl,"__esModule",{value:!0});const Rw=Yt,Wp=_e,Ol=K,Gp=fa,Ow={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Gp.default.code(new Rw.KeywordCxt(s,Gp.default,"additionalProperties"));const a=(0,Wp.allSchemaProperties)(n);for(const h of a)s.definedProperties.add(h);s.opts.unevaluated&&a.length&&s.props!==!0&&(s.props=Ol.mergeEvaluated.props(t,(0,Ol.toHash)(a),s.props));const i=a.filter(h=>!(0,Ol.alwaysValidSchema)(s,n[h]));if(i.length===0)return;const l=t.name("valid");for(const h of i)c(h)?u(h):(t.if((0,Wp.propertyInData)(t,o,h,s.opts.ownProperties)),u(h),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(h),e.ok(l);function c(h){return s.opts.useDefaults&&!s.compositeRule&&n[h].default!==void 0}function u(h){e.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};Rl.default=Ow;var Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const Kp=_e,ga=me,Yp=K,Qp=K,Nw={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:a}=s,i=(0,Kp.allSchemaProperties)(n),l=i.filter(v=>(0,Yp.alwaysValidSchema)(s,n[v]));if(i.length===0||l.length===i.length&&(!s.opts.unevaluated||s.props===!0))return;const c=a.strictSchema&&!a.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof ga.Name)&&(s.props=(0,Qp.evaluatedPropsToName)(t,s.props));const{props:h}=s;y();function y(){for(const v of i)c&&f(v),s.allErrors?g(v):(t.var(u,!0),g(v),t.if(u))}function f(v){for(const m in c)new RegExp(v).test(m)&&(0,Yp.checkStrictMode)(s,`property ${m} matches pattern ${v} (use allowMatchingProperties)`)}function g(v){t.forIn("key",r,m=>{t.if((0,ga._)`${(0,Kp.usePattern)(e,v)}.test(${m})`,()=>{const d=l.includes(v);d||e.subschema({keyword:"patternProperties",schemaProp:v,dataProp:m,dataPropType:Qp.Type.Str},u),s.opts.unevaluated&&h!==!0?t.assign((0,ga._)`${h}[${m}]`,!0):!d&&!s.allErrors&&t.if((0,ga.not)(u),()=>t.break())})})}}};Nl.default=Nw;var Al={};Object.defineProperty(Al,"__esModule",{value:!0});const Aw=K,Mw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,Aw.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Al.default=Mw;var Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const jw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_e.validateUnion,error:{message:"must match a schema in anyOf"}};Ml.default=jw;var jl={};Object.defineProperty(jl,"__esModule",{value:!0});const ya=me,Lw=K,zw={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ya._)`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,a=t.let("valid",!1),i=t.let("passing",null),l=t.name("_valid");e.setParams({passing:i}),t.block(c),e.result(a,()=>e.reset(),()=>e.error(!0));function c(){s.forEach((u,h)=>{let y;(0,Lw.alwaysValidSchema)(o,u)?t.var(l,!0):y=e.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&t.if((0,ya._)`${l} && ${a}`).assign(a,!1).assign(i,(0,ya._)`[${i}, ${h}]`).else(),t.if(l,()=>{t.assign(a,!0),t.assign(i,h),y&&e.mergeEvaluated(y,ya.Name)})})}}};jl.default=zw;var Ll={};Object.defineProperty(Ll,"__esModule",{value:!0});const Dw=K,Zw={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,a)=>{if((0,Dw.alwaysValidSchema)(r,s))return;const i=e.subschema({keyword:"allOf",schemaProp:a},o);e.ok(o),e.mergeEvaluated(i)})}};Ll.default=Zw;var zl={};Object.defineProperty(zl,"__esModule",{value:!0});const va=me,Xp=K,Uw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>(0,va.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,va._)`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Xp.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=ef(r,"then"),s=ef(r,"else");if(!o&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(l(),e.reset(),o&&s){const u=t.let("ifClause");e.setParams({ifClause:u}),t.if(i,c("then",u),c("else",u))}else o?t.if(i,c("then")):t.if((0,va.not)(i),c("else"));e.pass(a,()=>e.error(!0));function l(){const u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(u)}function c(u,h){return()=>{const y=e.subschema({keyword:u},i);t.assign(a,i),e.mergeValidEvaluated(y,a),h?t.assign(h,(0,va._)`${u}`):e.setParams({ifClause:u})}}}};function ef(e,t){const n=e.schema[t];return n!==void 0&&!(0,Xp.alwaysValidSchema)(e,n)}zl.default=Uw;var Dl={};Object.defineProperty(Dl,"__esModule",{value:!0});const qw=K,Vw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,qw.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};Dl.default=Vw,Object.defineProperty(kl,"__esModule",{value:!0});const Fw=Jr,Bw=xl,Hw=Wr,Jw=El,Ww=Il,Gw=Hp,Kw=Pl,Yw=fa,Qw=Rl,Xw=Nl,eb=Al,tb=Ml,nb=jl,rb=Ll,ob=zl,sb=Dl;function ab(e=!1){const t=[eb.default,tb.default,nb.default,rb.default,ob.default,sb.default,Kw.default,Yw.default,Gw.default,Qw.default,Xw.default];return e?t.push(Bw.default,Jw.default):t.push(Fw.default,Hw.default),t.push(Ww.default),t}kl.default=ab;var Zl={},Ul={};Object.defineProperty(Ul,"__esModule",{value:!0});const Ye=me,ib={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>(0,Ye.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Ye._)`{format: ${e}}`},code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:a,it:i}=e,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=i;if(!l.validateFormats)return;o?y():f();function y(){const g=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),v=n.const("fDef",(0,Ye._)`${g}[${a}]`),m=n.let("fType"),d=n.let("format");n.if((0,Ye._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>n.assign(m,(0,Ye._)`${v}.type || "string"`).assign(d,(0,Ye._)`${v}.validate`),()=>n.assign(m,(0,Ye._)`"string"`).assign(d,v)),e.fail$data((0,Ye.or)(w(),_()));function w(){return l.strictSchema===!1?Ye.nil:(0,Ye._)`${a} && !${d}`}function _(){const b=u.$async?(0,Ye._)`(${v}.async ? await ${d}(${r}) : ${d}(${r}))`:(0,Ye._)`${d}(${r})`,T=(0,Ye._)`(typeof ${d} == "function" ? ${b} : ${d}.test(${r}))`;return(0,Ye._)`${d} && ${d} !== true && ${m} === ${t} && !${T}`}}function f(){const g=h.formats[s];if(!g){w();return}if(g===!0)return;const[v,m,d]=_(g);v===t&&e.pass(b());function w(){if(l.strictSchema===!1){h.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function _(T){const P=T instanceof RegExp?(0,Ye.regexpCode)(T):l.code.formats?(0,Ye._)`${l.code.formats}${(0,Ye.getProperty)(s)}`:void 0,E=n.scopeValue("formats",{key:s,ref:T,code:P});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Ye._)`${E}.validate`]:["string",T,E]}function b(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ye._)`await ${d}(${r})`}return typeof m=="function"?(0,Ye._)`${d}(${r})`:(0,Ye._)`${d}.test(${r})`}}}};Ul.default=ib,Object.defineProperty(Zl,"__esModule",{value:!0});const lb=[Ul.default];Zl.default=lb;var Gr={};Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.contentVocabulary=Gr.metadataVocabulary=void 0,Gr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Gr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(ll,"__esModule",{value:!0});const cb=cl,ub=dl,db=kl,pb=Zl,tf=Gr,fb=[cb.default,ub.default,(0,db.default)(),pb.default,tf.metadataVocabulary,tf.contentVocabulary];ll.default=fb;var ql={},_a={};Object.defineProperty(_a,"__esModule",{value:!0}),_a.DiscrError=void 0;var nf;(function(e){e.Tag="tag",e.Mapping="mapping"})(nf||(_a.DiscrError=nf={})),Object.defineProperty(ql,"__esModule",{value:!0});const Kr=me,Vl=_a,rf=$t,hb=Br,mb=K,gb={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===Vl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Kr._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:a}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=r.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const l=t.let("valid",!1),c=t.const("tag",(0,Kr._)`${n}${(0,Kr.getProperty)(i)}`);t.if((0,Kr._)`typeof ${c} == "string"`,()=>u(),()=>e.error(!1,{discrError:Vl.DiscrError.Tag,tag:c,tagName:i})),e.ok(l);function u(){const f=y();t.if(!1);for(const g in f)t.elseIf((0,Kr._)`${c} === ${g}`),t.assign(l,h(f[g]));t.else(),e.error(!1,{discrError:Vl.DiscrError.Mapping,tag:c,tagName:i}),t.endIf()}function h(f){const g=t.name("valid"),v=e.subschema({keyword:"oneOf",schemaProp:f},g);return e.mergeEvaluated(v,Kr.Name),g}function y(){var f;const g={},v=d(o);let m=!0;for(let b=0;b<a.length;b++){let T=a[b];if(T!=null&&T.$ref&&!(0,mb.schemaHasRulesButRef)(T,s.self.RULES)){const E=T.$ref;if(T=rf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,E),T instanceof rf.SchemaEnv&&(T=T.schema),T===void 0)throw new hb.default(s.opts.uriResolver,s.baseId,E)}const P=(f=T==null?void 0:T.properties)===null||f===void 0?void 0:f[i];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);m=m&&(v||d(T)),w(P,b)}if(!m)throw new Error(`discriminator: "${i}" must be required`);return g;function d({required:b}){return Array.isArray(b)&&b.includes(i)}function w(b,T){if(b.const)_(b.const,T);else if(b.enum)for(const P of b.enum)_(P,T);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function _(b,T){if(typeof b!="string"||b in g)throw new Error(`discriminator: "${i}" values must be unique strings`);g[b]=T}}}};ql.default=gb;const yb={$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};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=Ld,r=ll,o=ql,s=yb,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const g=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(g,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Yt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=me;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=Po;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var y=Br;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return y.default}})})(Ui,Ui.exports);var Fl=Ui.exports;const vb=Zr(Fl);var ke;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ke||(ke={}));var Bl;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Bl||(Bl={}));const Y=ke.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zn=e=>{switch(typeof e){case"undefined":return Y.undefined;case"string":return Y.string;case"number":return Number.isNaN(e)?Y.nan:Y.number;case"boolean":return Y.boolean;case"function":return Y.function;case"bigint":return Y.bigint;case"symbol":return Y.symbol;case"object":return Array.isArray(e)?Y.array:e===null?Y.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Y.promise:typeof Map<"u"&&e instanceof Map?Y.map:typeof Set<"u"&&e instanceof Set?Y.set:typeof Date<"u"&&e instanceof Date?Y.date:Y.object;default:return Y.unknown}},q=ke.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"]),_b=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class At extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let i=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(n(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof At))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ke.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}At.create=e=>new At(e);const Yr=(e,t)=>{let n;switch(e.code){case q.invalid_type:e.received===Y.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ke.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:n=`Unrecognized key(s) in object: ${ke.joinValues(e.keys,", ")}`;break;case q.invalid_union:n="Invalid input";break;case q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ke.joinValues(e.options)}`;break;case q.invalid_enum_value:n=`Invalid enum value. Expected ${ke.joinValues(e.options)}, received '${e.received}'`;break;case q.invalid_arguments:n="Invalid function arguments";break;case q.invalid_return_type:n="Invalid function return type";break;case q.invalid_date:n="Invalid date";break;case q.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ke.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case q.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case q.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case q.custom:n="Invalid input";break;case q.invalid_intersection_types:n="Intersection results could not be merged";break;case q.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case q.not_finite:n="Number must be finite";break;default:n=t.defaultError,ke.assertNever(e)}return{message:n}};let of=Yr;function wb(e){of=e}function wa(){return of}const ba=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}},bb=[];function F(e,t){const n=wa(),r=ba({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Yr?void 0:Yr].filter(o=>!!o)});e.common.issues.push(r)}class ht{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return re;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return ht.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return re;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const re=Object.freeze({status:"aborted"}),Qr=e=>({status:"dirty",value:e}),yt=e=>({status:"valid",value:e}),Hl=e=>e.status==="aborted",Jl=e=>e.status==="dirty",br=e=>e.status==="valid",Do=e=>typeof Promise<"u"&&e instanceof Promise;var X;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(X||(X={}));class bn{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const sf=(e,t)=>{if(br(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new At(e.common.issues);return this._error=n,this._error}}};function de(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:o}}let ge=class{get description(){return this._def.description}_getType(t){return zn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:zn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ht,ctx:{common:t.parent.common,data:t.data,parsedType:zn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Do(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zn(t)},o=this._parseSync({data:t,path:r.path,parent:r});return sf(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return br(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(o=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>br(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Do(o)?o:Promise.resolve(o));return sf(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:q.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new tn({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Cn.create(this,this._def)}nullable(){return Xn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $r.create(this)}promise(){return ro.create(this,this._def)}or(t){return Fo.create([this,t],this._def)}and(t){return Bo.create(this,t,this._def)}transform(t){return new tn({...de(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Ko({...de(this._def),innerType:this,defaultValue:n,typeName:I.ZodDefault})}brand(){return new Kl({typeName:I.ZodBranded,type:this,...de(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Yo({...de(this._def),innerType:this,catchValue:n,typeName:I.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Qo.create(this,t)}readonly(){return Xo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Sb=/^c[^\s-]{8,}$/i,Cb=/^[0-9a-z]+$/,$b=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kb=/^[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,Tb=/^[a-z0-9_-]{21}$/i,xb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Eb=/^[-+]?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)?)??$/,Ib=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Wl;const Rb=/^(?:(?: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])$/,Ob=/^(?:(?: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])$/,Nb=/^(([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]))$/,Ab=/^(([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])$/,Mb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,af="((\\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])))",Lb=new RegExp(`^${af}$`);function lf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function zb(e){return new RegExp(`^${lf(e)}$`)}function cf(e){let t=`${af}T${lf(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Db(e,t){return!!((t==="v4"||!t)&&Rb.test(e)||(t==="v6"||!t)&&Nb.test(e))}function Zb(e,t){if(!xb.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Ub(e,t){return!!((t==="v4"||!t)&&Ob.test(e)||(t==="v6"||!t)&&Ab.test(e))}let Xr=class Ks extends ge{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Y.string){const s=this._getOrReturnCtx(t);return F(s,{code:q.invalid_type,expected:Y.string,received:s.parsedType}),re}const r=new ht;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),F(o,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),F(o,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?F(o,{code:q.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&F(o,{code:q.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ib.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"email",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Wl||(Wl=new RegExp(Pb,"u")),Wl.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"emoji",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")kb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"uuid",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Tb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"nanoid",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Sb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"cuid",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Cb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"cuid2",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")$b.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"ulid",code:q.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),F(o,{validation:"url",code:q.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"regex",code:q.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?cf(s).test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Lb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?zb(s).test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{code:q.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Eb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"duration",code:q.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Db(t.data,s.version)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"ip",code:q.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Zb(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"jwt",code:q.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Ub(t.data,s.version)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"cidr",code:q.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Mb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"base64",code:q.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?jb.test(t.data)||(o=this._getOrReturnCtx(t,o),F(o,{validation:"base64url",code:q.invalid_string,message:s.message}),r.dirty()):ke.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:q.invalid_string,...X.errToObj(r)})}_addCheck(t){return new Ks({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...X.errToObj(t)})}url(t){return this._addCheck({kind:"url",...X.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...X.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...X.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...X.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...X.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...X.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...X.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...X.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...X.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...X.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...X.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...X.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...X.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...X.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...X.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...X.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...X.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...X.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...X.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...X.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...X.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...X.errToObj(n)})}nonempty(t){return this.min(1,X.errToObj(t))}trim(){return new Ks({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ks({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ks({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Xr.create=e=>new Xr({checks:[],typeName:I.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...de(e)});function qb(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}let Zo=class Nd extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Y.number){const s=this._getOrReturnCtx(t);return F(s,{code:q.invalid_type,expected:Y.number,received:s.parsedType}),re}let r;const o=new ht;for(const s of this._def.checks)s.kind==="int"?ke.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:q.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?qb(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),F(r,{code:q.not_finite,message:s.message}),o.dirty()):ke.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,X.toString(n))}gt(t,n){return this.setLimit("min",t,!1,X.toString(n))}lte(t,n){return this.setLimit("max",t,!0,X.toString(n))}lt(t,n){return this.setLimit("max",t,!1,X.toString(n))}setLimit(t,n,r,o){return new Nd({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:X.toString(o)}]})}_addCheck(t){return new Nd({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:X.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:X.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:X.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ke.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Zo.create=e=>new Zo({checks:[],typeName:I.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...de(e)});class Qn extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Y.bigint)return this._getInvalidInput(t);let r;const o=new ht;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),F(r,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ke.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return F(n,{code:q.invalid_type,expected:Y.bigint,received:n.parsedType}),re}gte(t,n){return this.setLimit("min",t,!0,X.toString(n))}gt(t,n){return this.setLimit("min",t,!1,X.toString(n))}lte(t,n){return this.setLimit("max",t,!0,X.toString(n))}lt(t,n){return this.setLimit("max",t,!1,X.toString(n))}setLimit(t,n,r,o){return new Qn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:X.toString(o)}]})}_addCheck(t){return new Qn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:X.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Qn.create=e=>new Qn({checks:[],typeName:I.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...de(e)});let Uo=class extends ge{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Y.boolean){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.boolean,received:r.parsedType}),re}return yt(t.data)}};Uo.create=e=>new Uo({typeName:I.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...de(e)});class Sr extends ge{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Y.date){const s=this._getOrReturnCtx(t);return F(s,{code:q.invalid_type,expected:Y.date,received:s.parsedType}),re}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return F(s,{code:q.invalid_date}),re}const r=new ht;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),F(o,{code:q.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),F(o,{code:q.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ke.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Sr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:X.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:X.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Sr.create=e=>new Sr({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:I.ZodDate,...de(e)});class Sa extends ge{_parse(t){if(this._getType(t)!==Y.symbol){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.symbol,received:r.parsedType}),re}return yt(t.data)}}Sa.create=e=>new Sa({typeName:I.ZodSymbol,...de(e)});class qo extends ge{_parse(t){if(this._getType(t)!==Y.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.undefined,received:r.parsedType}),re}return yt(t.data)}}qo.create=e=>new qo({typeName:I.ZodUndefined,...de(e)});let Vo=class extends ge{_parse(t){if(this._getType(t)!==Y.null){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.null,received:r.parsedType}),re}return yt(t.data)}};Vo.create=e=>new Vo({typeName:I.ZodNull,...de(e)});let eo=class extends ge{constructor(){super(...arguments),this._any=!0}_parse(t){return yt(t.data)}};eo.create=e=>new eo({typeName:I.ZodAny,...de(e)});let Cr=class extends ge{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yt(t.data)}};Cr.create=e=>new Cr({typeName:I.ZodUnknown,...de(e)});let Dn=class extends ge{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:q.invalid_type,expected:Y.never,received:n.parsedType}),re}};Dn.create=e=>new Dn({typeName:I.ZodNever,...de(e)});class Ca extends ge{_parse(t){if(this._getType(t)!==Y.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.void,received:r.parsedType}),re}return yt(t.data)}}Ca.create=e=>new Ca({typeName:I.ZodVoid,...de(e)});let $r=class Zi extends ge{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==Y.array)return F(n,{code:q.invalid_type,expected:Y.array,received:n.parsedType}),re;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,i=n.data.length<o.exactLength.value;(a||i)&&(F(n,{code:a?q.too_big:q.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(F(n,{code:q.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(F(n,{code:q.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,i)=>o.type._parseAsync(new bn(n,a,n.path,i)))).then(a=>ht.mergeArray(r,a));const s=[...n.data].map((a,i)=>o.type._parseSync(new bn(n,a,n.path,i)));return ht.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Zi({...this._def,minLength:{value:t,message:X.toString(n)}})}max(t,n){return new Zi({...this._def,maxLength:{value:t,message:X.toString(n)}})}length(t,n){return new Zi({...this._def,exactLength:{value:t,message:X.toString(n)}})}nonempty(t){return this.min(1,t)}};$r.create=(e,t)=>new $r({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...de(t)});function to(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cn.create(to(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof $r?new $r({...e._def,type:to(e.element)}):e instanceof Cn?Cn.create(to(e.unwrap())):e instanceof Xn?Xn.create(to(e.unwrap())):e instanceof Sn?Sn.create(e.items.map(t=>to(t))):e}let Vt=class gn extends ge{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ke.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==Y.object){const c=this._getOrReturnCtx(t);return F(c,{code:q.invalid_type,expected:Y.object,received:c.parsedType}),re}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Dn&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],h=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new bn(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Dn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(F(o,{code:q.unrecognized_keys,keys:i}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const h=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new bn(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,y=await u.value;c.push({key:h,value:y,alwaysSet:u.alwaysSet})}return c}).then(c=>ht.mergeObjectSync(r,c)):ht.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return X.errToObj,new gn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,a;const o=((a=(s=this._def).errorMap)==null?void 0:a.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:X.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new gn({...this._def,unknownKeys:"strip"})}passthrough(){return new gn({...this._def,unknownKeys:"passthrough"})}extend(t){return new gn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new gn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:I.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new gn({...this._def,catchall:t})}pick(t){const n={};for(const r of ke.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new gn({...this._def,shape:()=>n})}omit(t){const n={};for(const r of ke.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new gn({...this._def,shape:()=>n})}deepPartial(){return to(this)}partial(t){const n={};for(const r of ke.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new gn({...this._def,shape:()=>n})}required(t){const n={};for(const r of ke.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Cn;)s=s._def.innerType;n[r]=s}return new gn({...this._def,shape:()=>n})}keyof(){return pf(ke.objectKeys(this.shape))}};Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Dn.create(),typeName:I.ZodObject,...de(t)}),Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Dn.create(),typeName:I.ZodObject,...de(t)}),Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Dn.create(),typeName:I.ZodObject,...de(t)});let Fo=class extends ge{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new At(i.ctx.common.issues));return F(n,{code:q.invalid_union,unionErrors:a}),re}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new At(l));return F(n,{code:q.invalid_union,unionErrors:i}),re}}get options(){return this._def.options}};Fo.create=(e,t)=>new Fo({options:e,typeName:I.ZodUnion,...de(t)});const Zn=e=>e instanceof Ho?Zn(e.schema):e instanceof tn?Zn(e.innerType()):e instanceof Jo?[e.value]:e instanceof Wo?e.options:e instanceof Go?ke.objectValues(e.enum):e instanceof Ko?Zn(e._def.innerType):e instanceof qo?[void 0]:e instanceof Vo?[null]:e instanceof Cn?[void 0,...Zn(e.unwrap())]:e instanceof Xn?[null,...Zn(e.unwrap())]:e instanceof Kl||e instanceof Xo?Zn(e.unwrap()):e instanceof Yo?Zn(e._def.innerType):[];let uf=class iy extends ge{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Y.object)return F(n,{code:q.invalid_type,expected:Y.object,received:n.parsedType}),re;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(F(n,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),re)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=Zn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new iy({typeName:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...de(r)})}};function Gl(e,t){const n=zn(e),r=zn(t);if(e===t)return{valid:!0,data:e};if(n===Y.object&&r===Y.object){const o=ke.objectKeys(t),s=ke.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Gl(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(n===Y.array&&r===Y.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=Gl(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===Y.date&&r===Y.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let Bo=class extends ge{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(Hl(s)||Hl(a))return re;const i=Gl(s.value,a.value);return i.valid?((Jl(s)||Jl(a))&&n.dirty(),{status:n.value,value:i.data}):(F(r,{code:q.invalid_intersection_types}),re)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Bo.create=(e,t,n)=>new Bo({left:e,right:t,typeName:I.ZodIntersection,...de(n)});class Sn extends ge{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Y.array)return F(r,{code:q.invalid_type,expected:Y.array,received:r.parsedType}),re;if(r.data.length<this._def.items.length)return F(r,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),re;!this._def.rest&&r.data.length>this._def.items.length&&(F(r,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new bn(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>ht.mergeArray(n,a)):ht.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Sn({...this._def,rest:t})}}Sn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Sn({items:e,typeName:I.ZodTuple,rest:null,...de(t)})};let df=class Ad extends ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Y.object)return F(r,{code:q.invalid_type,expected:Y.object,received:r.parsedType}),re;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in r.data)o.push({key:s._parse(new bn(r,i,r.path,i)),value:a._parse(new bn(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?ht.mergeObjectAsync(n,o):ht.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof ge?new Ad({keyType:t,valueType:n,typeName:I.ZodRecord,...de(r)}):new Ad({keyType:Xr.create(),valueType:t,typeName:I.ZodRecord,...de(n)})}};class $a extends ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Y.map)return F(r,{code:q.invalid_type,expected:Y.map,received:r.parsedType}),re;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([i,l],c)=>({key:o._parse(new bn(r,i,r.path,[c,"key"])),value:s._parse(new bn(r,l,r.path,[c,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return re;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),i.set(c.value,u.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return re;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),i.set(c.value,u.value)}return{status:n.value,value:i}}}}$a.create=(e,t,n)=>new $a({valueType:t,keyType:e,typeName:I.ZodMap,...de(n)});class kr extends ge{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Y.set)return F(r,{code:q.invalid_type,expected:Y.set,received:r.parsedType}),re;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(F(r,{code:q.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(F(r,{code:q.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return re;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}const i=[...r.data.values()].map((l,c)=>s._parse(new bn(r,l,r.path,c)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,n){return new kr({...this._def,minSize:{value:t,message:X.toString(n)}})}max(t,n){return new kr({...this._def,maxSize:{value:t,message:X.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}kr.create=(e,t)=>new kr({valueType:e,minSize:null,maxSize:null,typeName:I.ZodSet,...de(t)});class no extends ge{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Y.function)return F(n,{code:q.invalid_type,expected:Y.function,received:n.parsedType}),re;function r(i,l){return ba({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,wa(),Yr].filter(c=>!!c),issueData:{code:q.invalid_arguments,argumentsError:l}})}function o(i,l){return ba({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,wa(),Yr].filter(c=>!!c),issueData:{code:q.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof ro){const i=this;return yt(async function(...l){const c=new At([]),u=await i._def.args.parseAsync(l,s).catch(f=>{throw c.addIssue(r(l,f)),c}),h=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(h,s).catch(f=>{throw c.addIssue(o(h,f)),c})})}else{const i=this;return yt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new At([r(l,c.error)]);const u=Reflect.apply(a,this,c.data),h=i._def.returns.safeParse(u,s);if(!h.success)throw new At([o(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new no({...this._def,args:Sn.create(t).rest(Cr.create())})}returns(t){return new no({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new no({args:t||Sn.create([]).rest(Cr.create()),returns:n||Cr.create(),typeName:I.ZodFunction,...de(r)})}}let Ho=class extends ge{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ho.create=(e,t)=>new Ho({getter:e,typeName:I.ZodLazy,...de(t)});let Jo=class extends ge{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return F(n,{received:n.data,code:q.invalid_literal,expected:this._def.value}),re}return{status:"valid",value:t.data}}get value(){return this._def.value}};Jo.create=(e,t)=>new Jo({value:e,typeName:I.ZodLiteral,...de(t)});function pf(e,t){return new Wo({values:e,typeName:I.ZodEnum,...de(t)})}let Wo=class Md extends ge{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{expected:ke.joinValues(r),received:n.parsedType,code:q.invalid_type}),re}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{received:n.data,code:q.invalid_enum_value,options:r}),re}return yt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Md.create(t,{...this._def,...n})}exclude(t,n=this._def){return Md.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Wo.create=pf;class Go extends ge{_parse(t){const n=ke.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==Y.string&&r.parsedType!==Y.number){const o=ke.objectValues(n);return F(r,{expected:ke.joinValues(o),received:r.parsedType,code:q.invalid_type}),re}if(this._cache||(this._cache=new Set(ke.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=ke.objectValues(n);return F(r,{received:r.data,code:q.invalid_enum_value,options:o}),re}return yt(t.data)}get enum(){return this._def.values}}Go.create=(e,t)=>new Go({values:e,typeName:I.ZodNativeEnum,...de(t)});class ro extends ge{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Y.promise&&n.common.async===!1)return F(n,{code:q.invalid_type,expected:Y.promise,received:n.parsedType}),re;const r=n.parsedType===Y.promise?n.data:Promise.resolve(n.data);return yt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ro.create=(e,t)=>new ro({type:e,typeName:I.ZodPromise,...de(t)});class tn extends ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{F(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async i=>{if(n.value==="aborted")return re;const l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?re:l.status==="dirty"||n.value==="dirty"?Qr(l.value):l});{if(n.value==="aborted")return re;const i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?re:i.status==="dirty"||n.value==="dirty"?Qr(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?re:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?re:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!br(a))return re;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>br(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:n.value,value:i})):re);ke.assertNever(o)}}tn.create=(e,t,n)=>new tn({schema:e,typeName:I.ZodEffects,effect:t,...de(n)}),tn.createWithPreprocess=(e,t,n)=>new tn({schema:t,effect:{type:"preprocess",transform:e},typeName:I.ZodEffects,...de(n)});let Cn=class extends ge{_parse(t){return this._getType(t)===Y.undefined?yt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Cn.create=(e,t)=>new Cn({innerType:e,typeName:I.ZodOptional,...de(t)});let Xn=class extends ge{_parse(t){return this._getType(t)===Y.null?yt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Xn.create=(e,t)=>new Xn({innerType:e,typeName:I.ZodNullable,...de(t)});let Ko=class extends ge{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===Y.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ko.create=(e,t)=>new Ko({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...de(t)});let Yo=class extends ge{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Do(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Yo.create=(e,t)=>new Yo({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...de(t)});class ka extends ge{_parse(t){if(this._getType(t)!==Y.nan){const r=this._getOrReturnCtx(t);return F(r,{code:q.invalid_type,expected:Y.nan,received:r.parsedType}),re}return{status:"valid",value:t.data}}}ka.create=e=>new ka({typeName:I.ZodNaN,...de(e)});const Vb=Symbol("zod_brand");class Kl extends ge{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Qo extends ge{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?re:s.status==="dirty"?(n.dirty(),Qr(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?re:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Qo({in:t,out:n,typeName:I.ZodPipeline})}}let Xo=class extends ge{_parse(t){const n=this._def.innerType._parse(t),r=o=>(br(o)&&(o.value=Object.freeze(o.value)),o);return Do(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Xo.create=(e,t)=>new Xo({innerType:e,typeName:I.ZodReadonly,...de(t)});function ff(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function hf(e,t={},n){return e?eo.create().superRefine((r,o)=>{const s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){const i=ff(t,r),l=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=ff(t,r),i=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:i})}}):eo.create()}const Fb={object:Vt.lazycreate};var I;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(I||(I={}));const Bb=(e,t={message:`Input not instance of ${e.name}`})=>hf(n=>n instanceof e,t),mf=Xr.create,gf=Zo.create,Hb=ka.create,Jb=Qn.create,yf=Uo.create,Wb=Sr.create,Gb=Sa.create,Kb=qo.create,Yb=Vo.create,Qb=eo.create,Xb=Cr.create,e3=Dn.create,t3=Ca.create,n3=$r.create,vf=Vt.create,r3=Vt.strictCreate,o3=Fo.create,s3=uf.create,a3=Bo.create,i3=Sn.create,l3=df.create,c3=$a.create,u3=kr.create,d3=no.create,p3=Ho.create,f3=Jo.create,h3=Wo.create,m3=Go.create,g3=ro.create,_f=tn.create,y3=Cn.create,v3=Xn.create,_3=tn.createWithPreprocess,w3=Qo.create,b3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Vb,DIRTY:Qr,EMPTY_PATH:bb,INVALID:re,NEVER:re,OK:yt,ParseStatus:ht,Schema:ge,ZodAny:eo,ZodArray:$r,ZodBigInt:Qn,ZodBoolean:Uo,ZodBranded:Kl,ZodCatch:Yo,ZodDate:Sr,ZodDefault:Ko,ZodDiscriminatedUnion:uf,ZodEffects:tn,ZodEnum:Wo,ZodError:At,get ZodFirstPartyTypeKind(){return I},ZodFunction:no,ZodIntersection:Bo,ZodIssueCode:q,ZodLazy:Ho,ZodLiteral:Jo,ZodMap:$a,ZodNaN:ka,ZodNativeEnum:Go,ZodNever:Dn,ZodNull:Vo,ZodNullable:Xn,ZodNumber:Zo,ZodObject:Vt,ZodOptional:Cn,ZodParsedType:Y,ZodPipeline:Qo,ZodPromise:ro,ZodReadonly:Xo,ZodRecord:df,ZodSchema:ge,ZodSet:kr,ZodString:Xr,ZodSymbol:Sa,ZodTransformer:tn,ZodTuple:Sn,ZodType:ge,ZodUndefined:qo,ZodUnion:Fo,ZodUnknown:Cr,ZodVoid:Ca,addIssueToContext:F,any:Qb,array:n3,bigint:Jb,boolean:yf,coerce:{string:e=>Xr.create({...e,coerce:!0}),number:e=>Zo.create({...e,coerce:!0}),boolean:e=>Uo.create({...e,coerce:!0}),bigint:e=>Qn.create({...e,coerce:!0}),date:e=>Sr.create({...e,coerce:!0})},custom:hf,date:Wb,datetimeRegex:cf,defaultErrorMap:Yr,discriminatedUnion:s3,effect:_f,enum:h3,function:d3,getErrorMap:wa,getParsedType:zn,instanceof:Bb,intersection:a3,isAborted:Hl,isAsync:Do,isDirty:Jl,isValid:br,late:Fb,lazy:p3,literal:f3,makeIssue:ba,map:c3,nan:Hb,nativeEnum:m3,never:e3,null:Yb,nullable:v3,number:gf,object:vf,get objectUtil(){return Bl},oboolean:()=>yf().optional(),onumber:()=>gf().optional(),optional:y3,ostring:()=>mf().optional(),pipeline:w3,preprocess:_3,promise:g3,quotelessJson:_b,record:l3,set:u3,setErrorMap:wb,strictObject:r3,string:mf,symbol:Gb,transformer:_f,tuple:i3,undefined:Kb,union:o3,unknown:Xb,get util(){return ke},void:t3},Symbol.toStringTag,{value:"Module"})),S3=Object.freeze({status:"aborted"});function j(e,t,n){function r(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=n!=null&&n.Parent?new s:this;r(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var l,c;return n!=null&&n.Parent&&i instanceof n.Parent?!0:(c=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:c.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class es extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const wf={};function er(e){return wf}function bf(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function C3(e,t){return typeof t=="bigint"?t.toString():t}function Yl(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ql(e){return e==null}function Xl(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function $3(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Re(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ts(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ns(e){return JSON.stringify(e)}const Sf=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const k3=Yl(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function xa(e){if(Ta(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Ta(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const T3=new Set(["string","number","symbol"]);function rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tr(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function Q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function x3(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const E3={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 I3(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return tr(e,{...e._zod.def,shape:n,checks:[]})}function P3(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return tr(e,{...e._zod.def,shape:n,checks:[]})}function R3(e,t){if(!xa(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ts(this,"shape",r),r},checks:[]};return tr(e,n)}function O3(e,t){return tr(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ts(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function N3(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return tr(t,{...t._zod.def,shape:o,checks:[]})}function A3(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return tr(t,{...t._zod.def,shape:o,checks:[]})}function os(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function Tr(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ea(e){return typeof e=="string"?e:e==null?void 0:e.message}function nr(e,t,n){var o,s,a,i,l,c;const r={...e,path:e.path??[]};if(!e.message){const u=Ea((a=(s=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??Ea((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??Ea((l=n.customError)==null?void 0:l.call(n,e))??Ea((c=n.localeError)==null?void 0:c.call(n,e))??"Invalid input";r.message=u}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function ec(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ss(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Cf=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,C3,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$f=j("$ZodError",Cf),Ia=j("$ZodError",Cf,{Parent:Error});function M3(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function j3(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let i=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(n(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),r}const kf=e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new es;if(a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>nr(l,s,er())));throw Sf(i,o==null?void 0:o.callee),i}return a.value},L3=kf(Ia),Tf=e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>nr(l,s,er())));throw Sf(i,o==null?void 0:o.callee),i}return a.value},z3=Tf(Ia),xf=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new es;return s.issues.length?{success:!1,error:new(e??$f)(s.issues.map(a=>nr(a,o,er())))}:{success:!0,data:s.value}},tc=xf(Ia),Ef=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>nr(a,o,er())))}:{success:!0,data:s.value}},nc=Ef(Ia),D3=/^[cC][^\s-]{8,}$/,Z3=/^[0-9a-z]+$/,U3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,q3=/^[0-9a-vA-V]{20}$/,V3=/^[A-Za-z0-9]{27}$/,F3=/^[a-zA-Z0-9_-]{21}$/,B3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,H3=/^([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})$/,If=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,J3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,W3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function G3(){return new RegExp(W3,"u")}const K3=/^(?:(?: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])$/,Y3=/^(([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})$/,Q3=/^((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])$/,X3=/^(([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])$/,e9=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pf=/^[A-Za-z0-9_-]*$/,t9=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,n9=/^\+(?:[0-9]){6,14}[0-9]$/,Rf="(?:(?:\\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])))",r9=new RegExp(`^${Rf}$`);function Of(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function o9(e){return new RegExp(`^${Of(e)}$`)}function s9(e){const t=Of({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Rf}T(?:${r})$`)}const a9=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},i9=/^\d+$/,l9=/^-?\d+(?:\.\d+)?/i,c9=/true|false/i,u9=/null/i,d9=/^[^A-Z]*$/,p9=/^[^a-z]*$/,Tt=j("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Nf={number:"number",bigint:"bigint",object:"date"},Af=j("$ZodCheckLessThan",(e,t)=>{Tt.init(e,t);const n=Nf[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mf=j("$ZodCheckGreaterThan",(e,t)=>{Tt.init(e,t);const n=Nf[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),f9=j("$ZodCheckMultipleOf",(e,t)=>{Tt.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):$3(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),h9=j("$ZodCheckNumberFormat",(e,t)=>{var a;Tt.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,s]=E3[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=i9)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<o&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:e})}}),m9=j("$ZodCheckMaxLength",(e,t)=>{var n;Tt.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=ec(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),g9=j("$ZodCheckMinLength",(e,t)=>{var n;Tt.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=ec(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),y9=j("$ZodCheckLengthEquals",(e,t)=>{var n;Tt.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Ql(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=ec(o),i=s>t.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Pa=j("$ZodCheckStringFormat",(e,t)=>{var n,r;Tt.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),v9=j("$ZodCheckRegex",(e,t)=>{Pa.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_9=j("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=d9),Pa.init(e,t)}),w9=j("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=p9),Pa.init(e,t)}),b9=j("$ZodCheckIncludes",(e,t)=>{Tt.init(e,t);const n=rs(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),S9=j("$ZodCheckStartsWith",(e,t)=>{Tt.init(e,t);const n=new RegExp(`^${rs(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),C9=j("$ZodCheckEndsWith",(e,t)=>{Tt.init(e,t);const n=new RegExp(`.*${rs(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),$9=j("$ZodCheckOverwrite",(e,t)=>{Tt.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class k9{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
9
+ `).filter(a=>a),o=Math.min(...r.map(a=>a.length-a.trimStart().length)),s=r.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
10
+ `))}}const T9={major:4,minor:0,patch:0},De=j("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=T9;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,i,l)=>{let c=os(a),u;for(const h of i){if(h._zod.def.when){if(!h._zod.def.when(a))continue}else if(c)continue;const y=a.issues.length,f=h._zod.check(a);if(f instanceof Promise&&(l==null?void 0:l.async)===!1)throw new es;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,a.issues.length!==y&&(c||(c=os(a,y)))});else{if(a.issues.length===y)continue;c||(c=os(a,y))}}return u?u.then(()=>a):a};e._zod.run=(a,i)=>{const l=e._zod.parse(a,i);if(l instanceof Promise){if(i.async===!1)throw new es;return l.then(c=>s(c,r,i))}return s(l,r,i)}}e["~standard"]={validate:s=>{var a;try{const i=tc(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return nc(e,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),rc=j("$ZodString",(e,t)=>{var n;De.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??a9(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Je=j("$ZodStringFormat",(e,t)=>{Pa.init(e,t),rc.init(e,t)}),x9=j("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=H3),Je.init(e,t)}),E9=j("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=If(r))}else t.pattern??(t.pattern=If());Je.init(e,t)}),I9=j("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=J3),Je.init(e,t)}),P9=j("$ZodURL",(e,t)=>{Je.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t9.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),R9=j("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=G3()),Je.init(e,t)}),O9=j("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=F3),Je.init(e,t)}),N9=j("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=D3),Je.init(e,t)}),A9=j("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Z3),Je.init(e,t)}),M9=j("$ZodULID",(e,t)=>{t.pattern??(t.pattern=U3),Je.init(e,t)}),j9=j("$ZodXID",(e,t)=>{t.pattern??(t.pattern=q3),Je.init(e,t)}),L9=j("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=V3),Je.init(e,t)}),z9=j("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=s9(t)),Je.init(e,t)}),D9=j("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=r9),Je.init(e,t)}),Z9=j("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=o9(t)),Je.init(e,t)}),U9=j("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=B3),Je.init(e,t)}),q9=j("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=K3),Je.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),V9=j("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Y3),Je.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),F9=j("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Q3),Je.init(e,t)}),B9=j("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=X3),Je.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function jf(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const H9=j("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=e9),Je.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{jf(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function J9(e){if(!Pf.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return jf(n)}const W9=j("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Pf),Je.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{J9(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),G9=j("$ZodE164",(e,t)=>{t.pattern??(t.pattern=n9),Je.init(e,t)});function K9(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Y9=j("$ZodJWT",(e,t)=>{Je.init(e,t),e._zod.check=n=>{K9(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Lf=j("$ZodNumber",(e,t)=>{De.init(e,t),e._zod.pattern=e._zod.bag.pattern??l9,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Q9=j("$ZodNumber",(e,t)=>{h9.init(e,t),Lf.init(e,t)}),X9=j("$ZodBoolean",(e,t)=>{De.init(e,t),e._zod.pattern=c9,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),e4=j("$ZodNull",(e,t)=>{De.init(e,t),e._zod.pattern=u9,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),t4=j("$ZodAny",(e,t)=>{De.init(e,t),e._zod.parse=n=>n}),n4=j("$ZodUnknown",(e,t)=>{De.init(e,t),e._zod.parse=n=>n}),r4=j("$ZodNever",(e,t)=>{De.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function zf(e,t,n){e.issues.length&&t.issues.push(...Tr(n,e.issues)),t.value[n]=e.value}const o4=j("$ZodArray",(e,t)=>{De.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},r);l instanceof Promise?s.push(l.then(c=>zf(c,n,a))):zf(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function Ra(e,t,n){e.issues.length&&t.issues.push(...Tr(n,e.issues)),t.value[n]=e.value}function Df(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...Tr(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Zf=j("$ZodObject",(e,t)=>{De.init(e,t);const n=Yl(()=>{const h=Object.keys(t.shape);for(const f of h)if(!(t.shape[f]instanceof De))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const y=x3(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(y)}});Re(e._zod,"propValues",()=>{const h=t.shape,y={};for(const f in h){const g=h[f]._zod;if(g.values){y[f]??(y[f]=new Set);for(const v of g.values)y[f].add(v)}}return y});const r=h=>{const y=new k9(["shape","payload","ctx"]),f=n.value,g=w=>{const _=ns(w);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};y.write("const input = payload.value;");const v=Object.create(null);let m=0;for(const w of f.keys)v[w]=`key_${m++}`;y.write("const newResult = {}");for(const w of f.keys)if(f.optionalKeys.has(w)){const _=v[w];y.write(`const ${_} = ${g(w)};`);const b=ns(w);y.write(`
11
+ if (${_}.issues.length) {
12
+ if (input[${b}] === undefined) {
13
+ if (${b} in input) {
14
+ newResult[${b}] = undefined;
15
+ }
16
+ } else {
17
+ payload.issues = payload.issues.concat(
18
+ ${_}.issues.map((iss) => ({
19
+ ...iss,
20
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
21
+ }))
22
+ );
23
+ }
24
+ } else if (${_}.value === undefined) {
25
+ if (${b} in input) newResult[${b}] = undefined;
26
+ } else {
27
+ newResult[${b}] = ${_}.value;
28
+ }
29
+ `)}else{const _=v[w];y.write(`const ${_} = ${g(w)};`),y.write(`
30
+ if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
31
+ ...iss,
32
+ path: iss.path ? [${ns(w)}, ...iss.path] : [${ns(w)}]
33
+ })));`),y.write(`newResult[${ns(w)}] = ${_}.value`)}y.write("payload.value = newResult;"),y.write("return payload;");const d=y.compile();return(w,_)=>d(h,w,_)};let o;const s=Ta,a=!wf.jitless,l=a&&k3.value,c=t.catchall;let u;e._zod.parse=(h,y)=>{u??(u=n.value);const f=h.value;if(!s(f))return h.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),h;const g=[];if(a&&l&&(y==null?void 0:y.async)===!1&&y.jitless!==!0)o||(o=r(t.shape)),h=o(h,y);else{h.value={};const _=u.shape;for(const b of u.keys){const T=_[b],P=T._zod.run({value:f[b],issues:[]},y),E=T._zod.optin==="optional"&&T._zod.optout==="optional";P instanceof Promise?g.push(P.then(Z=>E?Df(Z,h,b,f):Ra(Z,h,b))):E?Df(P,h,b,f):Ra(P,h,b)}}if(!c)return g.length?Promise.all(g).then(()=>h):h;const v=[],m=u.keySet,d=c._zod,w=d.def.type;for(const _ of Object.keys(f)){if(m.has(_))continue;if(w==="never"){v.push(_);continue}const b=d.run({value:f[_],issues:[]},y);b instanceof Promise?g.push(b.then(T=>Ra(T,h,_))):Ra(b,h,_)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>h):h}});function Uf(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>nr(s,r,er())))}),t}const qf=j("$ZodUnion",(e,t)=>{De.init(e,t),Re(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Re(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Re(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Re(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Xl(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>Uf(a,n,e,r)):Uf(s,n,e,r)}}),s4=j("$ZodDiscriminatedUnion",(e,t)=>{qf.init(e,t);const n=e._zod.parse;Re(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const r=Yl(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!Ta(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=r.value.get(a==null?void 0:a[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),a4=j("$ZodIntersection",(e,t)=>{De.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Vf(n,l,c)):Vf(n,s,a)}});function oc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(xa(e)&&xa(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=oc(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=oc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vf(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),os(e))return e;const r=oc(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const i4=j("$ZodRecord",(e,t)=>{De.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!xa(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Tr(l,u.issues)),n.value[l]=u.value})):(c.issues.length&&n.issues.push(...Tr(l,c.issues)),n.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>nr(c,r,er())),input:a,path:[a],inst:e}),n.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...Tr(a,c.issues)),n.value[i.value]=c.value})):(l.issues.length&&n.issues.push(...Tr(a,l.issues)),n.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),l4=j("$ZodEnum",(e,t)=>{De.init(e,t);const n=bf(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>T3.has(typeof r)).map(r=>typeof r=="string"?rs(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),c4=j("$ZodLiteral",(e,t)=>{De.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?rs(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),u4=j("$ZodTransform",(e,t)=>{De.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new es;return n.value=o,n}}),d4=j("$ZodOptional",(e,t)=>{De.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Re(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Xl(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),p4=j("$ZodNullable",(e,t)=>{De.init(e,t),Re(e._zod,"optin",()=>t.innerType._zod.optin),Re(e._zod,"optout",()=>t.innerType._zod.optout),Re(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Xl(n.source)}|null)$`):void 0}),Re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),f4=j("$ZodDefault",(e,t)=>{De.init(e,t),e._zod.optin="optional",Re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ff(s,t)):Ff(o,t)}});function Ff(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const h4=j("$ZodPrefault",(e,t)=>{De.init(e,t),e._zod.optin="optional",Re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),m4=j("$ZodNonOptional",(e,t)=>{De.init(e,t),Re(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Bf(s,e)):Bf(o,e)}});function Bf(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const g4=j("$ZodCatch",(e,t)=>{De.init(e,t),e._zod.optin="optional",Re(e._zod,"optout",()=>t.innerType._zod.optout),Re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>nr(a,r,er()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>nr(s,r,er()))},input:n.value}),n.issues=[]),n)}}),y4=j("$ZodPipe",(e,t)=>{De.init(e,t),Re(e._zod,"values",()=>t.in._zod.values),Re(e._zod,"optin",()=>t.in._zod.optin),Re(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Hf(s,t,r)):Hf(o,t,r)}});function Hf(e,t,n){return os(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const v4=j("$ZodReadonly",(e,t)=>{De.init(e,t),Re(e._zod,"propValues",()=>t.innerType._zod.propValues),Re(e._zod,"values",()=>t.innerType._zod.values),Re(e._zod,"optin",()=>t.innerType._zod.optin),Re(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Jf):Jf(o)}});function Jf(e){return e.value=Object.freeze(e.value),e}const _4=j("$ZodLazy",(e,t)=>{De.init(e,t),Re(e._zod,"innerType",()=>t.getter()),Re(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Re(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Re(e._zod,"optin",()=>e._zod.innerType._zod.optin),Re(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),w4=j("$ZodCustom",(e,t)=>{Tt.init(e,t),De.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Wf(s,n,r,e));Wf(o,n,r,e)}});function Wf(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(ss(o))}}class Gf{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function b4(){return new Gf}const as=b4();function S4(e,t){return new e({type:"string",...Q(t)})}function C4(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Q(t)})}function Kf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Q(t)})}function $4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(t)})}function k4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(t)})}function T4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(t)})}function x4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(t)})}function Yf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Q(t)})}function E4(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(t)})}function I4(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(t)})}function P4(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(t)})}function R4(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(t)})}function O4(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(t)})}function N4(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Q(t)})}function A4(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(t)})}function M4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(t)})}function j4(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(t)})}function L4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(t)})}function z4(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(t)})}function Qf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Q(t)})}function D4(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(t)})}function Z4(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Q(t)})}function U4(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(t)})}function q4(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(t)})}function V4(e,t){return new e({type:"string",format:"date",check:"string_format",...Q(t)})}function F4(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Q(t)})}function B4(e,t){return new e({type:"string",format:"duration",check:"string_format",...Q(t)})}function H4(e,t){return new e({type:"number",checks:[],...Q(t)})}function J4(e,t){return new e({type:"number",coerce:!0,checks:[],...Q(t)})}function W4(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(t)})}function G4(e,t){return new e({type:"boolean",...Q(t)})}function K4(e,t){return new e({type:"null",...Q(t)})}function Y4(e){return new e({type:"any"})}function Q4(e){return new e({type:"unknown"})}function X4(e,t){return new e({type:"never",...Q(t)})}function Xf(e,t){return new Af({check:"less_than",...Q(t),value:e,inclusive:!1})}function sc(e,t){return new Af({check:"less_than",...Q(t),value:e,inclusive:!0})}function eh(e,t){return new Mf({check:"greater_than",...Q(t),value:e,inclusive:!1})}function ac(e,t){return new Mf({check:"greater_than",...Q(t),value:e,inclusive:!0})}function th(e,t){return new f9({check:"multiple_of",...Q(t),value:e})}function nh(e,t){return new m9({check:"max_length",...Q(t),maximum:e})}function Oa(e,t){return new g9({check:"min_length",...Q(t),minimum:e})}function rh(e,t){return new y9({check:"length_equals",...Q(t),length:e})}function e5(e,t){return new v9({check:"string_format",format:"regex",...Q(t),pattern:e})}function t5(e){return new _9({check:"string_format",format:"lowercase",...Q(e)})}function n5(e){return new w9({check:"string_format",format:"uppercase",...Q(e)})}function r5(e,t){return new b9({check:"string_format",format:"includes",...Q(t),includes:e})}function o5(e,t){return new S9({check:"string_format",format:"starts_with",...Q(t),prefix:e})}function s5(e,t){return new C9({check:"string_format",format:"ends_with",...Q(t),suffix:e})}function is(e){return new $9({check:"overwrite",tx:e})}function a5(e){return is(t=>t.normalize(e))}function i5(){return is(e=>e.trim())}function l5(){return is(e=>e.toLowerCase())}function c5(){return is(e=>e.toUpperCase())}function u5(e,t,n){return new e({type:"array",element:t,...Q(n)})}function d5(e,t,n){const r=Q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function p5(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Q(n)})}class oh{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??as,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var h,y,f;var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,i);const l=(y=(h=t._zod).toJSONSchema)==null?void 0:y.call(h);if(l)i.schema=l;else{const g={...n,schemaPath:[...n.schemaPath,t],path:n.path},v=t._zod.parent;if(v)i.ref=v,this.process(v,g),this.seen.get(v).isParent=!0;else{const m=i.schema;switch(o.type){case"string":{const d=m;d.type="string";const{minimum:w,maximum:_,format:b,patterns:T,contentEncoding:P}=t._zod.bag;if(typeof w=="number"&&(d.minLength=w),typeof _=="number"&&(d.maxLength=_),b&&(d.format=s[b]??b,d.format===""&&delete d.format),P&&(d.contentEncoding=P),T&&T.size>0){const E=[...T];E.length===1?d.pattern=E[0].source:E.length>1&&(i.schema.allOf=[...E.map(Z=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Z.source}))])}break}case"number":{const d=m,{minimum:w,maximum:_,format:b,multipleOf:T,exclusiveMaximum:P,exclusiveMinimum:E}=t._zod.bag;typeof b=="string"&&b.includes("int")?d.type="integer":d.type="number",typeof E=="number"&&(d.exclusiveMinimum=E),typeof w=="number"&&(d.minimum=w,typeof E=="number"&&(E>=w?delete d.minimum:delete d.exclusiveMinimum)),typeof P=="number"&&(d.exclusiveMaximum=P),typeof _=="number"&&(d.maximum=_,typeof P=="number"&&(P<=_?delete d.maximum:delete d.exclusiveMaximum)),typeof T=="number"&&(d.multipleOf=T);break}case"boolean":{const d=m;d.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":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const d=m,{minimum:w,maximum:_}=t._zod.bag;typeof w=="number"&&(d.minItems=w),typeof _=="number"&&(d.maxItems=_),d.type="array",d.items=this.process(o.element,{...g,path:[...g.path,"items"]});break}case"object":{const d=m;d.type="object",d.properties={};const w=o.shape;for(const T in w)d.properties[T]=this.process(w[T],{...g,path:[...g.path,"properties",T]});const _=new Set(Object.keys(w)),b=new Set([..._].filter(T=>{const P=o.shape[T]._zod;return this.io==="input"?P.optin===void 0:P.optout===void 0}));b.size>0&&(d.required=Array.from(b)),((f=o.catchall)==null?void 0:f._zod.def.type)==="never"?d.additionalProperties=!1:o.catchall?o.catchall&&(d.additionalProperties=this.process(o.catchall,{...g,path:[...g.path,"additionalProperties"]})):this.io==="output"&&(d.additionalProperties=!1);break}case"union":{const d=m;d.anyOf=o.options.map((w,_)=>this.process(w,{...g,path:[...g.path,"anyOf",_]}));break}case"intersection":{const d=m,w=this.process(o.left,{...g,path:[...g.path,"allOf",0]}),_=this.process(o.right,{...g,path:[...g.path,"allOf",1]}),b=P=>"allOf"in P&&Object.keys(P).length===1,T=[...b(w)?w.allOf:[w],...b(_)?_.allOf:[_]];d.allOf=T;break}case"tuple":{const d=m;d.type="array";const w=o.items.map((T,P)=>this.process(T,{...g,path:[...g.path,"prefixItems",P]}));if(this.target==="draft-2020-12"?d.prefixItems=w:d.items=w,o.rest){const T=this.process(o.rest,{...g,path:[...g.path,"items"]});this.target==="draft-2020-12"?d.items=T:d.additionalItems=T}o.rest&&(d.items=this.process(o.rest,{...g,path:[...g.path,"items"]}));const{minimum:_,maximum:b}=t._zod.bag;typeof _=="number"&&(d.minItems=_),typeof b=="number"&&(d.maxItems=b);break}case"record":{const d=m;d.type="object",d.propertyNames=this.process(o.keyType,{...g,path:[...g.path,"propertyNames"]}),d.additionalProperties=this.process(o.valueType,{...g,path:[...g.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 d=m,w=bf(o.entries);w.every(_=>typeof _=="number")&&(d.type="number"),w.every(_=>typeof _=="string")&&(d.type="string"),d.enum=w;break}case"literal":{const d=m,w=[];for(const _ of o.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");w.push(Number(_))}else w.push(_);if(w.length!==0)if(w.length===1){const _=w[0];d.type=_===null?"null":typeof _,d.const=_}else w.every(_=>typeof _=="number")&&(d.type="number"),w.every(_=>typeof _=="string")&&(d.type="string"),w.every(_=>typeof _=="boolean")&&(d.type="string"),w.every(_=>_===null)&&(d.type="null"),d.enum=w;break}case"file":{const d=m,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:b,mime:T}=t._zod.bag;_!==void 0&&(w.minLength=_),b!==void 0&&(w.maxLength=b),T?T.length===1?(w.contentMediaType=T[0],Object.assign(d,w)):d.anyOf=T.map(P=>({...w,contentMediaType:P})):Object.assign(d,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const d=this.process(o.innerType,g);m.anyOf=[d,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"success":{const d=m;d.type="boolean";break}case"default":{this.process(o.innerType,g),i.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,g),i.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,g),i.ref=o.innerType;let d;try{d=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=d;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const d=m,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");d.type="string",d.pattern=w.source;break}case"pipe":{const d=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(d,g),i.ref=d;break}case"readonly":{this.process(o.innerType,g),i.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,g),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"lazy":{const d=t._zod.innerType;this.process(d,g),i.ref=d;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&et(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,n){var u,h,y,f,g,v;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var T;const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const P=(T=r.external.registry.get(m[0]))==null?void 0:T.id,E=r.external.uri??(U=>U);if(P)return{ref:E(P)};const Z=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=Z,{defId:Z,ref:`${E("__shared")}#/${d}/${Z}`}}if(m[1]===o)return{ref:"#"};const _=`#/${d}/`,b=m[1].schema.id??`__schema${this.counter++}`;return{defId:b,ref:_+b}},a=m=>{if(m[1].schema.$ref)return;const d=m[1],{ref:w,defId:_}=s(m);d.def={...d.schema},_&&(d.defId=_);const b=d.schema;for(const T in b)delete b[T];b.$ref=w};if(r.cycles==="throw")for(const m of this.seen.entries()){const d=m[1];if(d.cycle)throw new Error(`Cycle detected: #/${(u=d.cycle)==null?void 0:u.join("/")}/<root>
34
+
35
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const d=m[1];if(t===m[0]){a(m);continue}if(r.external){const _=(h=r.external.registry.get(m[0]))==null?void 0:h.id;if(t!==m[0]&&_){a(m);continue}}if((y=this.metadataRegistry.get(m[0]))==null?void 0:y.id){a(m);continue}if(d.cycle){a(m);continue}if(d.count>1&&r.reused==="ref"){a(m);continue}}const i=(m,d)=>{const w=this.seen.get(m),_=w.def??w.schema,b={..._};if(w.ref===null)return;const T=w.ref;if(w.ref=null,T){i(T,d);const P=this.seen.get(T).schema;P.$ref&&d.target==="draft-7"?(_.allOf=_.allOf??[],_.allOf.push(P)):(Object.assign(_,P),Object.assign(_,b))}w.isParent||this.override({zodSchema:m,jsonSchema:_,path:w.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(f=r.external)!=null&&f.uri){const m=(g=r.external.registry.get(t))==null?void 0:g.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(m)}Object.assign(l,o.def);const c=((v=r.external)==null?void 0:v.defs)??{};for(const m of this.seen.entries()){const d=m[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function ic(e,t){if(e instanceof Gf){const r=new oh(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;r.process(c)}const s={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const n=new oh(t);return n.process(e),n.emit(e,t)}function et(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return et(o.element,n);case"object":{for(const s in o.shape)if(et(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(et(s,n))return!0;return!1}case"intersection":return et(o.left,n)||et(o.right,n);case"tuple":{for(const s of o.items)if(et(s,n))return!0;return!!(o.rest&&et(o.rest,n))}case"record":return et(o.keyType,n)||et(o.valueType,n);case"map":return et(o.keyType,n)||et(o.valueType,n);case"set":return et(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,n);case"lazy":return et(o.getter(),n);case"default":return et(o.innerType,n);case"prefault":return et(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,n)||et(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const f5=j("ZodISODateTime",(e,t)=>{z9.init(e,t),Ke.init(e,t)});function h5(e){return q4(f5,e)}const m5=j("ZodISODate",(e,t)=>{D9.init(e,t),Ke.init(e,t)});function g5(e){return V4(m5,e)}const y5=j("ZodISOTime",(e,t)=>{Z9.init(e,t),Ke.init(e,t)});function v5(e){return F4(y5,e)}const _5=j("ZodISODuration",(e,t)=>{U9.init(e,t),Ke.init(e,t)});function w5(e){return B4(_5,e)}const Na=j("ZodError",(e,t)=>{$f.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>j3(e,n)},flatten:{value:n=>M3(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),b5=kf(Na),S5=Tf(Na),C5=xf(Na),lc=Ef(Na),Be=j("ZodType",(e,t)=>(De.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>tr(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>b5(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>C5(e,n,r),e.parseAsync=async(n,r)=>S5(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>lc(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(h6(n,r)),e.superRefine=n=>e.check(m6(n)),e.overwrite=n=>e.check(is(n)),e.optional=()=>te(e),e.nullable=()=>mh(e),e.nullish=()=>te(mh(e)),e.nonoptional=n=>a6(e,n),e.array=()=>A(e),e.or=n=>ne([e,n]),e.and=n=>uc(e,n),e.transform=n=>pc(e,fh(n)),e.default=n=>r6(e,n),e.prefault=n=>s6(e,n),e.catch=n=>l6(e,n),e.pipe=n=>pc(e,n),e.readonly=()=>d6(e),e.describe=n=>{const r=e.clone();return as.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=as.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return as.get(e);const r=e.clone();return as.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),sh=j("_ZodString",(e,t)=>{rc.init(e,t),Be.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(e5(...r)),e.includes=(...r)=>e.check(r5(...r)),e.startsWith=(...r)=>e.check(o5(...r)),e.endsWith=(...r)=>e.check(s5(...r)),e.min=(...r)=>e.check(Oa(...r)),e.max=(...r)=>e.check(nh(...r)),e.length=(...r)=>e.check(rh(...r)),e.nonempty=(...r)=>e.check(Oa(1,...r)),e.lowercase=r=>e.check(t5(r)),e.uppercase=r=>e.check(n5(r)),e.trim=()=>e.check(i5()),e.normalize=(...r)=>e.check(a5(...r)),e.toLowerCase=()=>e.check(l5()),e.toUpperCase=()=>e.check(c5())}),$5=j("ZodString",(e,t)=>{rc.init(e,t),sh.init(e,t),e.email=n=>e.check(C4(k5,n)),e.url=n=>e.check(Yf(ih,n)),e.jwt=n=>e.check(U4(Z5,n)),e.emoji=n=>e.check(E4(x5,n)),e.guid=n=>e.check(Kf(ah,n)),e.uuid=n=>e.check($4(Aa,n)),e.uuidv4=n=>e.check(k4(Aa,n)),e.uuidv6=n=>e.check(T4(Aa,n)),e.uuidv7=n=>e.check(x4(Aa,n)),e.nanoid=n=>e.check(I4(E5,n)),e.guid=n=>e.check(Kf(ah,n)),e.cuid=n=>e.check(P4(I5,n)),e.cuid2=n=>e.check(R4(P5,n)),e.ulid=n=>e.check(O4(R5,n)),e.base64=n=>e.check(Qf(lh,n)),e.base64url=n=>e.check(D4(z5,n)),e.xid=n=>e.check(N4(O5,n)),e.ksuid=n=>e.check(A4(N5,n)),e.ipv4=n=>e.check(M4(A5,n)),e.ipv6=n=>e.check(j4(M5,n)),e.cidrv4=n=>e.check(L4(j5,n)),e.cidrv6=n=>e.check(z4(L5,n)),e.e164=n=>e.check(Z4(D5,n)),e.datetime=n=>e.check(h5(n)),e.date=n=>e.check(g5(n)),e.time=n=>e.check(v5(n)),e.duration=n=>e.check(w5(n))});function p(e){return S4($5,e)}const Ke=j("ZodStringFormat",(e,t)=>{Je.init(e,t),sh.init(e,t)}),k5=j("ZodEmail",(e,t)=>{I9.init(e,t),Ke.init(e,t)}),ah=j("ZodGUID",(e,t)=>{x9.init(e,t),Ke.init(e,t)}),Aa=j("ZodUUID",(e,t)=>{E9.init(e,t),Ke.init(e,t)}),ih=j("ZodURL",(e,t)=>{P9.init(e,t),Ke.init(e,t)});function T5(e){return Yf(ih,e)}const x5=j("ZodEmoji",(e,t)=>{R9.init(e,t),Ke.init(e,t)}),E5=j("ZodNanoID",(e,t)=>{O9.init(e,t),Ke.init(e,t)}),I5=j("ZodCUID",(e,t)=>{N9.init(e,t),Ke.init(e,t)}),P5=j("ZodCUID2",(e,t)=>{A9.init(e,t),Ke.init(e,t)}),R5=j("ZodULID",(e,t)=>{M9.init(e,t),Ke.init(e,t)}),O5=j("ZodXID",(e,t)=>{j9.init(e,t),Ke.init(e,t)}),N5=j("ZodKSUID",(e,t)=>{L9.init(e,t),Ke.init(e,t)}),A5=j("ZodIPv4",(e,t)=>{q9.init(e,t),Ke.init(e,t)}),M5=j("ZodIPv6",(e,t)=>{V9.init(e,t),Ke.init(e,t)}),j5=j("ZodCIDRv4",(e,t)=>{F9.init(e,t),Ke.init(e,t)}),L5=j("ZodCIDRv6",(e,t)=>{B9.init(e,t),Ke.init(e,t)}),lh=j("ZodBase64",(e,t)=>{H9.init(e,t),Ke.init(e,t)});function ch(e){return Qf(lh,e)}const z5=j("ZodBase64URL",(e,t)=>{W9.init(e,t),Ke.init(e,t)}),D5=j("ZodE164",(e,t)=>{G9.init(e,t),Ke.init(e,t)}),Z5=j("ZodJWT",(e,t)=>{Y9.init(e,t),Ke.init(e,t)}),cc=j("ZodNumber",(e,t)=>{Lf.init(e,t),Be.init(e,t),e.gt=(r,o)=>e.check(eh(r,o)),e.gte=(r,o)=>e.check(ac(r,o)),e.min=(r,o)=>e.check(ac(r,o)),e.lt=(r,o)=>e.check(Xf(r,o)),e.lte=(r,o)=>e.check(sc(r,o)),e.max=(r,o)=>e.check(sc(r,o)),e.int=r=>e.check(uh(r)),e.safe=r=>e.check(uh(r)),e.positive=r=>e.check(eh(0,r)),e.nonnegative=r=>e.check(ac(0,r)),e.negative=r=>e.check(Xf(0,r)),e.nonpositive=r=>e.check(sc(0,r)),e.multipleOf=(r,o)=>e.check(th(r,o)),e.step=(r,o)=>e.check(th(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function O(e){return H4(cc,e)}const U5=j("ZodNumberFormat",(e,t)=>{Q9.init(e,t),cc.init(e,t)});function uh(e){return W4(U5,e)}const q5=j("ZodBoolean",(e,t)=>{X9.init(e,t),Be.init(e,t)});function le(e){return G4(q5,e)}const V5=j("ZodNull",(e,t)=>{e4.init(e,t),Be.init(e,t)});function F5(e){return K4(V5,e)}const B5=j("ZodAny",(e,t)=>{t4.init(e,t),Be.init(e,t)});function Mt(){return Y4(B5)}const H5=j("ZodUnknown",(e,t)=>{n4.init(e,t),Be.init(e,t)});function Ze(){return Q4(H5)}const J5=j("ZodNever",(e,t)=>{r4.init(e,t),Be.init(e,t)});function W5(e){return X4(J5,e)}const G5=j("ZodArray",(e,t)=>{o4.init(e,t),Be.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Oa(n,r)),e.nonempty=n=>e.check(Oa(1,n)),e.max=(n,r)=>e.check(nh(n,r)),e.length=(n,r)=>e.check(rh(n,r)),e.unwrap=()=>e.element});function A(e,t){return u5(G5,e,t)}const dh=j("ZodObject",(e,t)=>{Zf.init(e,t),Be.init(e,t),Re(e,"shape",()=>t.shape),e.keyof=()=>Se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ze()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ze()}),e.strict=()=>e.clone({...e._zod.def,catchall:W5()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>R3(e,n),e.merge=n=>O3(e,n),e.pick=n=>I3(e,n),e.omit=n=>P3(e,n),e.partial=(...n)=>N3(hh,e,n[0]),e.required=(...n)=>A3(gh,e,n[0])});function C(e,t){const n={type:"object",get shape(){return ts(this,"shape",{...e}),this.shape},...Q(t)};return new dh(n)}function lt(e,t){return new dh({type:"object",get shape(){return ts(this,"shape",{...e}),this.shape},catchall:Ze(),...Q(t)})}const ph=j("ZodUnion",(e,t)=>{qf.init(e,t),Be.init(e,t),e.options=t.options});function ne(e,t){return new ph({type:"union",options:e,...Q(t)})}const K5=j("ZodDiscriminatedUnion",(e,t)=>{ph.init(e,t),s4.init(e,t)});function rt(e,t,n){return new K5({type:"union",options:t,discriminator:e,...Q(n)})}const Y5=j("ZodIntersection",(e,t)=>{a4.init(e,t),Be.init(e,t)});function uc(e,t){return new Y5({type:"intersection",left:e,right:t})}const Q5=j("ZodRecord",(e,t)=>{i4.init(e,t),Be.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function fe(e,t,n){return new Q5({type:"record",keyType:e,valueType:t,...Q(n)})}const dc=j("ZodEnum",(e,t)=>{l4.init(e,t),Be.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new dc({...t,checks:[],...Q(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new dc({...t,checks:[],...Q(o),entries:s})}});function Se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new dc({type:"enum",entries:n,...Q(t)})}const X5=j("ZodLiteral",(e,t)=>{c4.init(e,t),Be.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function N(e,t){return new X5({type:"literal",values:Array.isArray(e)?e:[e],...Q(t)})}const e6=j("ZodTransform",(e,t)=>{u4.init(e,t),Be.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ss(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(ss(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function fh(e){return new e6({type:"transform",transform:e})}const hh=j("ZodOptional",(e,t)=>{d4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function te(e){return new hh({type:"optional",innerType:e})}const t6=j("ZodNullable",(e,t)=>{p4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mh(e){return new t6({type:"nullable",innerType:e})}const n6=j("ZodDefault",(e,t)=>{f4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function r6(e,t){return new n6({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const o6=j("ZodPrefault",(e,t)=>{h4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function s6(e,t){return new o6({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const gh=j("ZodNonOptional",(e,t)=>{m4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function a6(e,t){return new gh({type:"nonoptional",innerType:e,...Q(t)})}const i6=j("ZodCatch",(e,t)=>{g4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function l6(e,t){return new i6({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const c6=j("ZodPipe",(e,t)=>{y4.init(e,t),Be.init(e,t),e.in=t.in,e.out=t.out});function pc(e,t){return new c6({type:"pipe",in:e,out:t})}const u6=j("ZodReadonly",(e,t)=>{v4.init(e,t),Be.init(e,t)});function d6(e){return new u6({type:"readonly",innerType:e})}const p6=j("ZodLazy",(e,t)=>{_4.init(e,t),Be.init(e,t),e.unwrap=()=>e._zod.def.getter()});function yh(e){return new p6({type:"lazy",getter:e})}const fc=j("ZodCustom",(e,t)=>{w4.init(e,t),Be.init(e,t)});function f6(e){const t=new Tt({check:"custom"});return t._zod.check=e,t}function vh(e,t){return d5(fc,e??(()=>!0),t)}function h6(e,t={}){return p5(fc,e,t)}function m6(e){const t=f6(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ss(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(ss(o))}},e(n.value,n)));return t}function Ma(e,t={error:`Input not instance of ${e.name}`}){const n=new fc({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...Q(t)});return n._zod.bag.Class=e,n}function g6(e,t){return pc(fh(e),t)}const y6={custom:"custom"};function v6(e){return J4(cc,e)}const ls="2025-06-18",_h=[ls,"2025-03-26","2024-11-05","2024-10-07"],ja="2.0",$n=vh(e=>e!==null&&(typeof e=="object"||typeof e=="function")),wh=ne([p(),O().int()]),bh=p(),_6=lt({progressToken:wh.optional()}),nn=lt({_meta:_6.optional()}),xt=C({method:p(),params:nn.optional()}),oo=lt({_meta:fe(p(),Ze()).optional()}),rn=C({method:p(),params:oo.optional()}),Ft=lt({_meta:fe(p(),Ze()).optional()}),La=ne([p(),O().int()]),Sh=C({jsonrpc:N(ja),id:La,...xt.shape}).strict(),Ch=e=>Sh.safeParse(e).success,$h=C({jsonrpc:N(ja),...rn.shape}).strict(),w6=e=>$h.safeParse(e).success,kh=C({jsonrpc:N(ja),id:La,result:Ft}).strict(),hc=e=>kh.safeParse(e).success;var Ee;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ee||(Ee={}));const Th=C({jsonrpc:N(ja),id:La,error:C({code:O().int(),message:p(),data:te(Ze())})}).strict(),b6=e=>Th.safeParse(e).success,Un=ne([Sh,$h,kh,Th]),rr=Ft.strict(),S6=oo.extend({requestId:La,reason:p().optional()}),mc=rn.extend({method:N("notifications/cancelled"),params:S6}),C6=C({src:p(),mimeType:p().optional(),sizes:A(p()).optional()}),cs=C({icons:A(C6).optional()}),so=C({name:p(),title:p().optional()}),xh=so.extend({...so.shape,...cs.shape,version:p(),websiteUrl:p().optional()}),$6=uc(C({applyDefaults:le().optional()}),fe(p(),Ze())),k6=g6(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,uc(C({form:$6.optional(),url:$n.optional()}),fe(p(),Ze()).optional())),T6=C({experimental:fe(p(),$n).optional(),sampling:C({context:$n.optional(),tools:$n.optional()}).optional(),elicitation:k6.optional(),roots:C({listChanged:le().optional()}).optional()}),x6=nn.extend({protocolVersion:p(),capabilities:T6,clientInfo:xh}),Eh=xt.extend({method:N("initialize"),params:x6}),E6=C({experimental:fe(p(),$n).optional(),logging:$n.optional(),completions:$n.optional(),prompts:te(C({listChanged:te(le())})),resources:C({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:C({listChanged:le().optional()}).optional()}),Ih=Ft.extend({protocolVersion:p(),capabilities:E6,serverInfo:xh,instructions:p().optional()}),gc=rn.extend({method:N("notifications/initialized")}),I6=e=>gc.safeParse(e).success,yc=xt.extend({method:N("ping")}),P6=C({progress:O(),total:te(O()),message:te(p())}),R6=C({...oo.shape,...P6.shape,progressToken:wh}),vc=rn.extend({method:N("notifications/progress"),params:R6}),O6=nn.extend({cursor:bh.optional()}),za=xt.extend({params:O6.optional()}),Da=Ft.extend({nextCursor:te(bh)}),Ph=C({uri:p(),mimeType:te(p()),_meta:fe(p(),Ze()).optional()}),Rh=Ph.extend({text:p()}),_c=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Oh=Ph.extend({blob:_c}),Nh=C({...so.shape,...cs.shape,uri:p(),description:te(p()),mimeType:te(p()),_meta:te(lt({}))}),N6=C({...so.shape,...cs.shape,uriTemplate:p(),description:te(p()),mimeType:te(p()),_meta:te(lt({}))}),Za=za.extend({method:N("resources/list")}),Ah=Da.extend({resources:A(Nh)}),wc=za.extend({method:N("resources/templates/list")}),Mh=Da.extend({resourceTemplates:A(N6)}),bc=nn.extend({uri:p()}),A6=bc,Sc=xt.extend({method:N("resources/read"),params:A6}),jh=Ft.extend({contents:A(ne([Rh,Oh]))}),Lh=rn.extend({method:N("notifications/resources/list_changed")}),M6=bc,zh=xt.extend({method:N("resources/subscribe"),params:M6}),j6=bc,Dh=xt.extend({method:N("resources/unsubscribe"),params:j6}),L6=oo.extend({uri:p()}),Zh=rn.extend({method:N("notifications/resources/updated"),params:L6}),z6=C({name:p(),description:te(p()),required:te(le())}),D6=C({...so.shape,...cs.shape,description:te(p()),arguments:te(A(z6)),_meta:te(lt({}))}),Cc=za.extend({method:N("prompts/list")}),Uh=Da.extend({prompts:A(D6)}),Z6=nn.extend({name:p(),arguments:fe(p(),p()).optional()}),$c=xt.extend({method:N("prompts/get"),params:Z6}),qh=C({type:N("text"),text:p(),_meta:fe(p(),Ze()).optional()}),Vh=C({type:N("image"),data:_c,mimeType:p(),_meta:fe(p(),Ze()).optional()}),Fh=C({type:N("audio"),data:_c,mimeType:p(),_meta:fe(p(),Ze()).optional()}),U6=C({type:N("tool_use"),name:p(),id:p(),input:C({}).passthrough(),_meta:te(C({}).passthrough())}).passthrough(),q6=C({type:N("resource"),resource:ne([Rh,Oh]),_meta:fe(p(),Ze()).optional()}),V6=Nh.extend({type:N("resource_link")}),kc=ne([qh,Vh,Fh,V6,q6]),F6=C({role:Se(["user","assistant"]),content:kc}),Bh=Ft.extend({description:te(p()),messages:A(F6)}),Hh=rn.extend({method:N("notifications/prompts/list_changed")}),B6=C({title:p().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),Jh=C({...so.shape,...cs.shape,description:p().optional(),inputSchema:C({type:N("object"),properties:fe(p(),$n).optional(),required:A(p()).optional()}).catchall(Ze()),outputSchema:C({type:N("object"),properties:fe(p(),$n).optional(),required:A(p()).optional()}).catchall(Ze()).optional(),annotations:te(B6),_meta:fe(p(),Ze()).optional()}),Tc=za.extend({method:N("tools/list")}),Wh=Da.extend({tools:A(Jh)}),Ua=Ft.extend({content:A(kc).default([]),structuredContent:fe(p(),Ze()).optional(),isError:te(le())});Ua.or(Ft.extend({toolResult:Ze()}));const H6=nn.extend({name:p(),arguments:te(fe(p(),Ze()))}),xc=xt.extend({method:N("tools/call"),params:H6}),Gh=rn.extend({method:N("notifications/tools/list_changed")}),qa=Se(["debug","info","notice","warning","error","critical","alert","emergency"]),J6=nn.extend({level:qa}),Va=xt.extend({method:N("logging/setLevel"),params:J6}),W6=oo.extend({level:qa,logger:p().optional(),data:Ze()}),Kh=rn.extend({method:N("notifications/message"),params:W6}),G6=C({name:p().optional()}),K6=C({hints:te(A(G6)),costPriority:te(O().min(0).max(1)),speedPriority:te(O().min(0).max(1)),intelligencePriority:te(O().min(0).max(1))}),Y6=C({mode:te(Se(["auto","required","none"]))}),Q6=C({type:N("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:A(kc).default([]),structuredContent:C({}).passthrough().optional(),isError:te(le()),_meta:te(C({}).passthrough())}).passthrough(),Fa=rt("type",[qh,Vh,Fh,U6,Q6]),X6=C({role:Se(["user","assistant"]),content:ne([Fa,A(Fa)]),_meta:te(C({}).passthrough())}).passthrough(),eS=nn.extend({messages:A(X6),modelPreferences:K6.optional(),systemPrompt:p().optional(),includeContext:Se(["none","thisServer","allServers"]).optional(),temperature:O().optional(),maxTokens:O().int(),stopSequences:A(p()).optional(),metadata:$n.optional(),tools:te(A(Jh)),toolChoice:te(Y6)}),Yh=xt.extend({method:N("sampling/createMessage"),params:eS}),Ec=Ft.extend({model:p(),stopReason:te(Se(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:Se(["user","assistant"]),content:ne([Fa,A(Fa)])}),tS=C({type:N("boolean"),title:p().optional(),description:p().optional(),default:le().optional()}),nS=C({type:N("string"),title:p().optional(),description:p().optional(),minLength:O().optional(),maxLength:O().optional(),format:Se(["email","uri","date","date-time"]).optional(),default:p().optional()}),rS=C({type:Se(["number","integer"]),title:p().optional(),description:p().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),oS=C({type:N("string"),title:p().optional(),description:p().optional(),enum:A(p()),default:p().optional()}),sS=C({type:N("string"),title:p().optional(),description:p().optional(),oneOf:A(C({const:p(),title:p()})),default:p().optional()}),aS=C({type:N("string"),title:p().optional(),description:p().optional(),enum:A(p()),enumNames:A(p()).optional(),default:p().optional()}),iS=ne([oS,sS]),lS=C({type:N("array"),title:p().optional(),description:p().optional(),minItems:O().optional(),maxItems:O().optional(),items:C({type:N("string"),enum:A(p())}),default:A(p()).optional()}),cS=C({type:N("array"),title:p().optional(),description:p().optional(),minItems:O().optional(),maxItems:O().optional(),items:C({anyOf:A(C({const:p(),title:p()}))}),default:A(p()).optional()}),uS=ne([lS,cS]),dS=ne([aS,iS,uS]),pS=ne([dS,tS,nS,rS]),fS=nn.extend({mode:N("form").optional(),message:p(),requestedSchema:C({type:N("object"),properties:fe(p(),pS),required:A(p()).optional()})}),hS=nn.extend({mode:N("url"),message:p(),elicitationId:p(),url:p().url()}),mS=ne([fS,hS]),Ic=xt.extend({method:N("elicitation/create"),params:mS}),gS=oo.extend({elicitationId:p()}),yS=rn.extend({method:N("notifications/elicitation/complete"),params:gS}),us=Ft.extend({action:Se(["accept","decline","cancel"]),content:fe(p(),ne([p(),O(),le(),A(p())])).optional()}),vS=C({type:N("ref/resource"),uri:p()}),_S=C({type:N("ref/prompt"),name:p()}),wS=nn.extend({ref:ne([_S,vS]),argument:C({name:p(),value:p()}),context:C({arguments:fe(p(),p()).optional()}).optional()}),Pc=xt.extend({method:N("completion/complete"),params:wS});function bS(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function SS(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Qh=Ft.extend({completion:lt({values:A(p()).max(100),total:te(O().int()),hasMore:te(le())})}),CS=C({uri:p().startsWith("file://"),name:p().optional(),_meta:fe(p(),Ze()).optional()}),Xh=xt.extend({method:N("roots/list")}),Rc=Ft.extend({roots:A(CS)}),e0=rn.extend({method:N("notifications/roots/list_changed")});ne([yc,Eh,Pc,Va,$c,Cc,Za,wc,Sc,zh,Dh,xc,Tc]),ne([mc,vc,gc,e0]),ne([rr,Ec,us,Rc]),ne([yc,Yh,Ic,Xh]),ne([mc,vc,Kh,Zh,Lh,Gh,Hh,yS]),ne([rr,Ih,Qh,Bh,Uh,Ah,Mh,jh,Ua,Wh]);class Ie extends Error{constructor(t,n,r){super(`MCP error ${t}: ${n}`),this.code=t,this.data=r,this.name="McpError"}static fromError(t,n,r){if(t===Ee.UrlElicitationRequired&&r){const o=r;if(o.elicitations)return new $S(o.elicitations,n)}return new Ie(t,n,r)}}class $S extends Ie{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(Ee.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){var t,n;return(n=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&n!==void 0?n:[]}}const kS=j("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");De.init(e,t),e.def=t,e.parse=(n,r)=>L3(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>tc(e,n,r),e.parseAsync=async(n,r)=>z3(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>nc(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>tr(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e)}),TS=j("ZodMiniObject",(e,t)=>{Zf.init(e,t),kS.init(e,t),Re(e,"shape",()=>t.shape)});function t0(e,t){const n={type:"object",get shape(){return ts(this,"shape",{...e}),this.shape},...Q(t)};return new TS(n)}function on(e){return!!e._zod}function ds(e){const t=Object.values(e);if(t.length===0)return t0({});const n=t.every(on),r=t.every(o=>!on(o));if(n)return t0(e);if(r)return vf(e);throw new Error("Mixed Zod versions detected in object shape.")}function Ba(e,t){return on(e)?tc(e,t):e.safeParse(t)}async function Oc(e,t){return on(e)?await nc(e,t):await e.safeParseAsync(t)}function ps(e){var t,n;if(!e)return;let r;if(on(e)?r=(n=(t=e._zod)===null||t===void 0?void 0:t.def)===null||n===void 0?void 0:n.shape:r=e.shape,!!r){if(typeof r=="function")try{return r()}catch{return}return r}}function fs(e){var t;if(e){if(typeof e=="object"){const n=e,r=e;if(!n._def&&!r._zod){const o=Object.values(e);if(o.length>0&&o.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return ds(e)}}if(on(e)){const r=(t=e._zod)===null||t===void 0?void 0:t.def;if(r&&(r.typeName==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Nc(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function xS(e){var t,n,r,o;if(on(e))return(n=(t=e._zod)===null||t===void 0?void 0:t.def)===null||n===void 0?void 0:n.description;const s=e;return(r=e.description)!==null&&r!==void 0?r:(o=s._def)===null||o===void 0?void 0:o.description}function ES(e){var t,n,r;if(on(e))return((n=(t=e._zod)===null||t===void 0?void 0:t.def)===null||n===void 0?void 0:n.typeName)==="ZodOptional";const o=e;return typeof e.isOptional=="function"?e.isOptional():((r=o._def)===null||r===void 0?void 0:r.typeName)==="ZodOptional"}function n0(e){var t;if(on(e)){const a=(t=e._zod)===null||t===void 0?void 0:t.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const o=e.value;if(o!==void 0)return o}const IS=Symbol("Let zodToJsonSchema decide on which parser to use"),r0={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"},PS=e=>typeof e=="string"?{...r0,name:e}:{...r0,...e},RS=e=>{const t=PS(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}};function o0(e,t,n,r){r!=null&&r.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function je(e,t,n,r,o){e[t]=n,o0(e,t,r,o)}const s0=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Et(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?s0(t,e.currentPath):t.join("/")}}function OS(e,t){var r,o,s;const n={type:"array"};return(r=e.type)!=null&&r._def&&((s=(o=e.type)==null?void 0:o._def)==null?void 0:s.typeName)!==I.ZodAny&&(n.items=Oe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&je(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&je(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(je(n,"minItems",e.exactLength.value,e.exactLength.message,t),je(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function NS(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?je(n,"minimum",r.value,r.message,t):je(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),je(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?je(n,"maximum",r.value,r.message,t):je(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),je(n,"maximum",r.value,r.message,t));break;case"multipleOf":je(n,"multipleOf",r.value,r.message,t);break}return n}function AS(){return{type:"boolean"}}function a0(e,t){return Oe(e.type._def,t)}const MS=(e,t)=>Oe(e.innerType._def,t);function i0(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>i0(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return jS(e,t)}}const jS=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":je(n,"minimum",r.value,r.message,t);break;case"max":je(n,"maximum",r.value,r.message,t);break}return n};function LS(e,t){return{...Oe(e.innerType._def,t),default:e.defaultValue()}}function zS(e,t){return t.effectStrategy==="input"?Oe(e.schema._def,t):Et(t)}function DS(e){return{type:"string",enum:Array.from(e.values)}}const ZS=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function US(e,t){const n=[Oe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Oe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach(s=>{if(ZS(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else r=void 0;o.push(a)}}),o.length?{allOf:o,...r}:void 0}function qS(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let Ac;const sn={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:()=>(Ac===void 0&&(Ac=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ac),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 l0(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":je(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":je(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":an(n,"email",r.message,t);break;case"format:idn-email":an(n,"idn-email",r.message,t);break;case"pattern:zod":vt(n,sn.email,r.message,t);break}break;case"url":an(n,"uri",r.message,t);break;case"uuid":an(n,"uuid",r.message,t);break;case"regex":vt(n,r.regex,r.message,t);break;case"cuid":vt(n,sn.cuid,r.message,t);break;case"cuid2":vt(n,sn.cuid2,r.message,t);break;case"startsWith":vt(n,RegExp(`^${Mc(r.value,t)}`),r.message,t);break;case"endsWith":vt(n,RegExp(`${Mc(r.value,t)}$`),r.message,t);break;case"datetime":an(n,"date-time",r.message,t);break;case"date":an(n,"date",r.message,t);break;case"time":an(n,"time",r.message,t);break;case"duration":an(n,"duration",r.message,t);break;case"length":je(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),je(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{vt(n,RegExp(Mc(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&an(n,"ipv4",r.message,t),r.version!=="v4"&&an(n,"ipv6",r.message,t);break}case"base64url":vt(n,sn.base64url,r.message,t);break;case"jwt":vt(n,sn.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&vt(n,sn.ipv4Cidr,r.message,t),r.version!=="v4"&&vt(n,sn.ipv6Cidr,r.message,t);break}case"emoji":vt(n,sn.emoji(),r.message,t);break;case"ulid":{vt(n,sn.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{an(n,"binary",r.message,t);break}case"contentEncoding:base64":{je(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{vt(n,sn.base64,r.message,t);break}}break}case"nanoid":vt(n,sn.nanoid,r.message,t)}return n}function Mc(e,t){return t.patternStrategy==="escape"?FS(e):e}const VS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FS(e){let t="";for(let n=0;n<e.length;n++)VS.has(e[n])||(t+="\\"),t+=e[n];return t}function an(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):je(e,"format",t,n,r)}function vt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:c0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):je(e,"pattern",c0(t,r),n,r)}function c0(e,t){var l;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(a){if(r[c].match(/[a-z]/)){i?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),i=!1):r[c+1]==="-"&&((l=r[c+2])!=null&&l.match(/[a-z]/))?(o+=r[c],i=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
36
+ ]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
37
+ ]))`;continue}}if(n.s&&r[c]==="."){o+=a?`${r[c]}\r
38
+ `:`[${r[c]}\r
39
+ ]`;continue}o+=r[c],r[c]==="\\"?s=!0:a&&r[c]==="]"?a=!1:!a&&r[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function u0(e,t){var r,o,s,a,i,l;if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&((r=e.keyType)==null?void 0:r._def.typeName)===I.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((c,u)=>({...c,[u]:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",u]})??Et(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(((o=e.keyType)==null?void 0:o._def.typeName)===I.ZodString&&((s=e.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=l0(e.keyType._def,t);return{...n,propertyNames:u}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===I.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===I.ZodBranded&&e.keyType._def.type._def.typeName===I.ZodString&&((l=e.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...u}=a0(e.keyType._def,t);return{...n,propertyNames:u}}}return n}function BS(e,t){if(t.mapStrategy==="record")return u0(e,t);const n=Oe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Et(t),r=Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Et(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function HS(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function JS(e){return e.target==="openAi"?void 0:{not:Et({...e,currentPath:[...e.currentPath,"not"]})}}function WS(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ha={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function GS(e,t){if(t.target==="openApi3")return d0(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ha&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Ha[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return d0(e,t)}const d0=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>Oe(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function KS(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ha[e.innerType._def.typeName],nullable:!0}:{type:[Ha[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function YS(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",o0(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?je(n,"minimum",r.value,r.message,t):je(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),je(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?je(n,"maximum",r.value,r.message,t):je(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),je(n,"maximum",r.value,r.message,t));break;case"multipleOf":je(n,"multipleOf",r.value,r.message,t);break}return n}function QS(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=e7(l);c&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Oe(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});u!==void 0&&(r.properties[i]=u,c||o.push(i))}o.length&&(r.required=o);const a=XS(e,t);return a!==void 0&&(r.additionalProperties=a),r}function XS(e,t){if(e.catchall._def.typeName!=="ZodNever")return Oe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function e7(e){try{return e.isOptional()}catch{return!0}}const t7=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Oe(e.innerType._def,t);const n=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Et(t)},n]}:Et(t)},n7=(e,t)=>{if(t.pipeStrategy==="input")return Oe(e.in._def,t);if(t.pipeStrategy==="output")return Oe(e.out._def,t);const n=Oe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Oe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function r7(e,t){return Oe(e.type._def,t)}function o7(e,t){const r={type:"array",uniqueItems:!0,items:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&je(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&je(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function s7(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Oe(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Oe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Oe(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function a7(e){return{not:Et(e)}}function i7(e){return Et(e)}const l7=(e,t)=>Oe(e.innerType._def,t),c7=(e,t,n)=>{switch(t){case I.ZodString:return l0(e,n);case I.ZodNumber:return YS(e,n);case I.ZodObject:return QS(e,n);case I.ZodBigInt:return NS(e,n);case I.ZodBoolean:return AS();case I.ZodDate:return i0(e,n);case I.ZodUndefined:return a7(n);case I.ZodNull:return WS(n);case I.ZodArray:return OS(e,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return GS(e,n);case I.ZodIntersection:return US(e,n);case I.ZodTuple:return s7(e,n);case I.ZodRecord:return u0(e,n);case I.ZodLiteral:return qS(e,n);case I.ZodEnum:return DS(e);case I.ZodNativeEnum:return HS(e);case I.ZodNullable:return KS(e,n);case I.ZodOptional:return t7(e,n);case I.ZodMap:return BS(e,n);case I.ZodSet:return o7(e,n);case I.ZodLazy:return()=>e.getter()._def;case I.ZodPromise:return r7(e,n);case I.ZodNaN:case I.ZodNever:return JS(n);case I.ZodEffects:return zS(e,n);case I.ZodAny:return Et(n);case I.ZodUnknown:return i7(n);case I.ZodDefault:return LS(e,n);case I.ZodBranded:return a0(e,n);case I.ZodReadonly:return l7(e,n);case I.ZodCatch:return MS(e,n);case I.ZodPipeline:return n7(e,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}};function Oe(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const l=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(l!==IS)return l}if(r&&!n){const l=u7(r,t);if(l!==void 0)return l}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=c7(e,e.typeName,t),a=typeof s=="function"?Oe(s(),t):s;if(a&&d7(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return o.jsonSchema=a,l}return o.jsonSchema=a,a}const u7=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s0(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Et(t)):t.$refStrategy==="seen"?Et(t):void 0}},d7=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),p7=(e,t)=>{const n=RS(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:Oe(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??Et(n)}),{}):void 0;const o=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,s=Oe(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Et(n),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 f7(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function p0(e,t){var n,r,o;return on(e)?ic(e,{target:f7(t==null?void 0:t.target),io:(n=t==null?void 0:t.pipeStrategy)!==null&&n!==void 0?n:"input"}):p7(e,{strictUnions:(r=t==null?void 0:t.strictUnions)!==null&&r!==void 0?r:!0,pipeStrategy:(o=t==null?void 0:t.pipeStrategy)!==null&&o!==void 0?o:"input"})}function f0(e){const t=ps(e),n=t==null?void 0:t.method;if(!n)throw new Error("Schema is missing a method literal");const r=n0(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function h0(e,t){const n=Ba(e,t);if(!n.success)throw n.error;return n.data}const h7=6e4;class m0{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(mc,n=>{const r=this._requestHandlerAbortControllers.get(n.params.requestId);r==null||r.abort(n.params.reason)}),this.setNotificationHandler(vc,n=>{this._onprogress(n)}),this.setRequestHandler(yc,n=>({}))}_setupTimeout(t,n,r,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const n=this._timeoutInfo.get(t);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),Ie.fromError(Ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){const n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var n,r,o;this._transport=t;const s=(n=this.transport)===null||n===void 0?void 0:n.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const a=(r=this.transport)===null||r===void 0?void 0:r.onerror;this._transport.onerror=l=>{a==null||a(l),this._onerror(l)};const i=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(l,c)=>{i==null||i(l,c),hc(l)||b6(l)?this._onresponse(l):Ch(l)?this._onrequest(l,c):w6(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var t;const n=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);const r=Ie.fromError(Ee.ConnectionClosed,"Connection closed");for(const o of n.values())o(r)}_onerror(t){var n;(n=this.onerror)===null||n===void 0||n.call(this,t)}_onnotification(t){var n;const r=(n=this._notificationHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,n){var r,o;const s=(r=this._requestHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackRequestHandler,a=this._transport;if(s===void 0){a==null||a.send({jsonrpc:"2.0",id:t.id,error:{code:Ee.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const l={signal:i.signal,sessionId:a==null?void 0:a.sessionId,_meta:(o=t.params)===null||o===void 0?void 0:o._meta,sendNotification:c=>this.notification(c,{relatedRequestId:t.id}),sendRequest:(c,u,h)=>this.request(c,u,{...h,relatedRequestId:t.id}),authInfo:n==null?void 0:n.authInfo,requestId:t.id,requestInfo:n==null?void 0:n.requestInfo};Promise.resolve().then(()=>s(t,l)).then(c=>{if(!i.signal.aborted)return a==null?void 0:a.send({result:c,jsonrpc:"2.0",id:t.id})},c=>{var u;if(!i.signal.aborted)return a==null?void 0:a.send({jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(c.code)?c.code:Ee.InternalError,message:(u=c.message)!==null&&u!==void 0?u:"Internal error",...c.data!==void 0&&{data:c.data}}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:n,...r}=t.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){a(l);return}s(r)}_onresponse(t){const n=Number(t.id),r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}if(this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),hc(t))r(t);else{const o=Ie.fromError(t.error.code,t.error.message,t.error.data);r(o)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}request(t,n,r){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}=r??{};return new Promise((i,l)=>{var c,u,h,y,f,g;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(t.method),(u=r==null?void 0:r.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:v};r!=null&&r.onprogress&&(this._progressHandlers.set(v,r.onprogress),m.params={...t.params,_meta:{...((h=t.params)===null||h===void 0?void 0:h._meta)||{},progressToken:v}});const d=b=>{var T;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(T=this._transport)===null||T===void 0||T.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`))),l(b)};this._responseHandlers.set(v,b=>{var T;if(!(!((T=r==null?void 0:r.signal)===null||T===void 0)&&T.aborted)){if(b instanceof Error)return l(b);try{const P=Ba(n,b.result);P.success?i(P.data):l(P.error)}catch(P){l(P)}}}),(y=r==null?void 0:r.signal)===null||y===void 0||y.addEventListener("abort",()=>{var b;d((b=r==null?void 0:r.signal)===null||b===void 0?void 0:b.reason)});const w=(f=r==null?void 0:r.timeout)!==null&&f!==void 0?f:h7,_=()=>d(Ie.fromError(Ee.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(v,w,r==null?void 0:r.maxTotalTimeout,_,(g=r==null?void 0:r.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(v),l(b)})})}async notification(t,n){var r,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(t.method),((o=(r=this._options)===null||r===void 0?void 0:r.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(t.method)&&!t.params&&!(n!=null&&n.relatedRequestId)){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;const c={...t,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,n).catch(u=>this._onerror(u))});return}const i={...t,jsonrpc:"2.0"};await this._transport.send(i,n)}setRequestHandler(t,n){const r=f0(t);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{const a=h0(t,o);return Promise.resolve(n(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){const r=f0(t);this._notificationHandlers.set(r,o=>{const s=h0(t,o);return Promise.resolve(n(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}}function g0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function y0(e,t){const n={...e};for(const r in t){const o=r,s=t[o];if(s===void 0)continue;const a=n[o];g0(a)&&g0(s)?n[o]={...a,...s}:n[o]=s}return n}var jc={exports:{}},v0={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(V,B){return{validate:V,compare:B}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(y(!0),f),"iso-time":t(l(),u),"iso-date-time":t(y(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:d,"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:W,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:P},int64:{type:"number",validate:E},float:{type:"number",validate:Z},double:{type:"number",validate:Z},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(V){return V%4===0&&(V%100!==0||V%400===0)}const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(V){const B=r.exec(V);if(!B)return!1;const J=+B[1],H=+B[2],ue=+B[3];return H>=1&&H<=12&&ue>=1&&ue<=(H===2&&n(J)?29:o[H])}function a(V,B){if(V&&B)return V>B?1:V<B?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(V){return function(J){const H=i.exec(J);if(!H)return!1;const ue=+H[1],Ce=+H[2],ae=+H[3],ye=H[4],he=H[5]==="-"?-1:1,L=+(H[6]||0),x=+(H[7]||0);if(L>23||x>59||V&&!ye)return!1;if(ue<=23&&Ce<=59&&ae<60)return!0;const M=Ce-x*he,R=ue-L*he-(M<0?1:0);return(R===23||R===-1)&&(M===59||M===-1)&&ae<61}}function c(V,B){if(!(V&&B))return;const J=new Date("2020-01-01T"+V).valueOf(),H=new Date("2020-01-01T"+B).valueOf();if(J&&H)return J-H}function u(V,B){if(!(V&&B))return;const J=i.exec(V),H=i.exec(B);if(J&&H)return V=J[1]+J[2]+J[3],B=H[1]+H[2]+H[3],V>B?1:V<B?-1:0}const h=/t|\s/i;function y(V){const B=l(V);return function(H){const ue=H.split(h);return ue.length===2&&s(ue[0])&&B(ue[1])}}function f(V,B){if(!(V&&B))return;const J=new Date(V).valueOf(),H=new Date(B).valueOf();if(J&&H)return J-H}function g(V,B){if(!(V&&B))return;const[J,H]=V.split(h),[ue,Ce]=B.split(h),ae=a(J,ue);if(ae!==void 0)return ae||c(H,Ce)}const v=/\/|:/,m=/^(?:[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 d(V){return v.test(V)&&m.test(V)}const w=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function _(V){return w.lastIndex=0,w.test(V)}const b=-2147483648,T=2**31-1;function P(V){return Number.isInteger(V)&&V<=T&&V>=b}function E(V){return Number.isInteger(V)}function Z(){return!0}const U=/[^\\]\\Z/;function W(V){if(U.test(V))return!1;try{return new RegExp(V),!0}catch{return!1}}})(v0);var _0={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Fl,n=me,r=n.operators,o={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,n.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,n._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:h,it:y}=i,{opts:f,self:g}=y;if(!f.validateFormats)return;const v=new t.KeywordCxt(y,g.RULES.all.format.definition,"format");v.$data?m():d();function m(){const _=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),b=l.const("fmt",(0,n._)`${_}[${v.schemaCode}]`);i.fail$data((0,n.or)((0,n._)`typeof ${b} != "object"`,(0,n._)`${b} instanceof RegExp`,(0,n._)`typeof ${b}.compare != "function"`,w(b)))}function d(){const _=v.schema,b=g.formats[_];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${h}": format "${_}" does not define "compare" function`);const T=l.scopeValue("formats",{key:_,ref:b,code:f.code.formats?(0,n._)`${f.code.formats}${(0,n.getProperty)(_)}`:void 0});i.fail$data(w(T))}function w(_){return(0,n._)`${_}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(_0),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=v0,r=_0,o=me,s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,n.fullFormats,s),c;const[h,y]=u.mode==="fast"?[n.fastFormats,a]:[n.fullFormats,s],f=u.formats||n.formatNames;return l(c,f,h,y),u.keywords&&(0,r.default)(c),c};i.get=(c,u="full")=>{const y=(u==="fast"?n.fastFormats:n.fullFormats)[c];if(!y)throw new Error(`Unknown format "${c}"`);return y};function l(c,u,h,y){var f,g;(f=(g=c.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${y}`);for(const v of u)c.addFormat(v,h[v])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(jc,jc.exports);var m7=jc.exports;const g7=Zr(m7);function y7(){const e=new Fl.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return g7(e),e}class w0{constructor(t){this._ajv=t??y7()}getValidator(t){var n;const r="$id"in t&&typeof t.$id=="string"?(n=this._ajv.getSchema(t.$id))!==null&&n!==void 0?n:this._ajv.compile(t):this._ajv.compile(t);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}function Ja(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const n=t,r=e.properties;for(const o of Object.keys(r)){const s=r[o];n[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(n[o]=s.default),n[o]!==void 0&&Ja(s,n[o])}}if(Array.isArray(e.anyOf))for(const n of e.anyOf)Ja(n,t);if(Array.isArray(e.oneOf))for(const n of e.oneOf)Ja(n,t)}}function v7(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}class hs extends m0{constructor(t,n){var r,o;super(n),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._capabilities=(r=n==null?void 0:n.capabilities)!==null&&r!==void 0?r:{},this._jsonSchemaValidator=(o=n==null?void 0:n.jsonSchemaValidator)!==null&&o!==void 0?o:new w0}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=y0(this._capabilities,t)}setRequestHandler(t,n){var r,o,s;const a=ps(t),i=a==null?void 0:a.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(on(i)){const u=i,h=(r=u._zod)===null||r===void 0?void 0:r.def;l=(o=h==null?void 0:h.value)!==null&&o!==void 0?o:u.value}else{const u=i,h=u._def;l=(s=h==null?void 0:h.value)!==null&&s!==void 0?s:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");if(l==="elicitation/create"){const u=async(h,y)=>{var f,g,v;const m=Ba(Ic,h);if(!m.success){const U=m.error instanceof Error?m.error.message:String(m.error);throw new Ie(Ee.InvalidParams,`Invalid elicitation request: ${U}`)}const{params:d}=m.data,w=(f=d.mode)!==null&&f!==void 0?f:"form",{supportsFormMode:_,supportsUrlMode:b}=v7(this._capabilities.elicitation);if(w==="form"&&!_)throw new Ie(Ee.InvalidParams,"Client does not support form-mode elicitation requests");if(w==="url"&&!b)throw new Ie(Ee.InvalidParams,"Client does not support URL-mode elicitation requests");const T=await Promise.resolve(n(h,y)),P=Ba(us,T);if(!P.success){const U=P.error instanceof Error?P.error.message:String(P.error);throw new Ie(Ee.InvalidParams,`Invalid elicitation result: ${U}`)}const E=P.data,Z=w==="form"?d.requestedSchema:void 0;if(w==="form"&&E.action==="accept"&&E.content&&Z&&!((v=(g=this._capabilities.elicitation)===null||g===void 0?void 0:g.form)===null||v===void 0)&&v.applyDefaults)try{Ja(Z,E.content)}catch{}return E};return super.setRequestHandler(t,u)}return super.setRequestHandler(t,n)}assertCapability(t,n){var r;if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r[t]))throw new Error(`Server does not support ${t} (required for ${n})`)}async connect(t,n){if(await super.connect(t),t.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:ls,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ih,n);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!_h.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"})}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var n,r,o,s,a;switch(t){case"logging/setLevel":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.resources))throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var n;switch(t){case"notifications/roots/list_changed":if(!(!((n=this._capabilities.roots)===null||n===void 0)&&n.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break}}async ping(t){return this.request({method:"ping"},rr,t)}async complete(t,n){return this.request({method:"completion/complete",params:t},Qh,n)}async setLoggingLevel(t,n){return this.request({method:"logging/setLevel",params:{level:t}},rr,n)}async getPrompt(t,n){return this.request({method:"prompts/get",params:t},Bh,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},Uh,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Ah,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Mh,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},jh,n)}async subscribeResource(t,n){return this.request({method:"resources/subscribe",params:t},rr,n)}async unsubscribeResource(t,n){return this.request({method:"resources/unsubscribe",params:t},rr,n)}async callTool(t,n=Ua,r){const o=await this.request({method:"tools/call",params:t},n,r),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new Ie(Ee.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new Ie(Ee.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof Ie?a:new Ie(Ee.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}cacheToolOutputSchemas(t){this._cachedToolOutputValidators.clear();for(const n of t)if(n.outputSchema){const r=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,r)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,n){const r=await this.request({method:"tools/list",params:t},Wh,n);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class b0 extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function Lc(e){}function S0(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Lc,onError:n=Lc,onRetry:r=Lc,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(v){const m=a?v.replace(/^\xEF\xBB\xBF/,""):v,[d,w]=_7(`${s}${m}`);for(const _ of d)h(_);s=w,a=!1}function h(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const d=v.slice(0,m),w=v[m+1]===" "?2:1,_=v.slice(m+w);y(d,_,v);return}y(v,"",v)}function y(v,m,d){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
40
+ `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?r(parseInt(m,10)):n(new b0(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:d}));break;default:n(new b0(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:d}));break}}function f(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
41
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function g(v={}){s&&v.consume&&h(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:g}}function _7(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
42
+ `,r);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){n=e.slice(r);break}else{const i=e.slice(r,a);t.push(i),r=a+1,e[r-1]==="\r"&&e[r]===`
43
+ `&&r++}}return[t,n]}class C0 extends Event{constructor(t,n){var r,o;super(t),this.code=(r=n==null?void 0:n.code)!=null?r:void 0,this.message=(o=n==null?void 0:n.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r($0(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t($0(this),n)}}function w7(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function zc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(zc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${zc(e.cause)}`:e.message:`${e}`}function $0(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var k0=e=>{throw TypeError(e)},Dc=(e,t,n)=>t.has(e)||k0("Cannot "+n),be=(e,t,n)=>(Dc(e,t,"read from private field"),n?n.call(e):t.get(e)),tt=(e,t,n)=>t.has(e)?k0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),We=(e,t,n,r)=>(Dc(e,t,"write to private field"),t.set(e,n),n),qn=(e,t,n)=>(Dc(e,t,"access private method"),n),It,xr,ao,Wa,Ga,ms,io,gs,or,lo,co,uo,ys,ln,Zc,Uc,qc,T0,Vc,Fc,vs,Bc,Hc;class Ka extends EventTarget{constructor(t,n){var r,o;super(),tt(this,ln),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,tt(this,It),tt(this,xr),tt(this,ao),tt(this,Wa),tt(this,Ga),tt(this,ms),tt(this,io),tt(this,gs,null),tt(this,or),tt(this,lo),tt(this,co,null),tt(this,uo,null),tt(this,ys,null),tt(this,Uc,async s=>{var a;be(this,lo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){qn(this,ln,vs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,ao,new URL(s.url)):We(this,ao,void 0),c!==200){qn(this,ln,vs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){qn(this,ln,vs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(be(this,It)===this.CLOSED)return;We(this,It,this.OPEN);const h=new Event("open");if((a=be(this,ys))==null||a.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){qn(this,ln,vs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const y=new TextDecoder,f=i.getReader();let g=!0;do{const{done:v,value:m}=await f.read();m&&be(this,lo).feed(y.decode(m,{stream:!v})),v&&(g=!1,be(this,lo).reset(),qn(this,ln,Bc).call(this))}while(g)}),tt(this,qc,s=>{We(this,or,void 0),!(s.name==="AbortError"||s.type==="aborted")&&qn(this,ln,Bc).call(this,zc(s))}),tt(this,Vc,s=>{typeof s.id=="string"&&We(this,gs,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:be(this,ao)?be(this,ao).origin:be(this,xr).origin,lastEventId:s.id||""});be(this,uo)&&(!s.event||s.event==="message")&&be(this,uo).call(this,a),this.dispatchEvent(a)}),tt(this,Fc,s=>{We(this,ms,s)}),tt(this,Hc,()=>{We(this,io,void 0),be(this,It)===this.CONNECTING&&qn(this,ln,Zc).call(this)});try{if(t instanceof URL)We(this,xr,t);else if(typeof t=="string")We(this,xr,new URL(t,b7()));else throw new Error("Invalid URL")}catch{throw w7("An invalid or illegal string was specified")}We(this,lo,S0({onEvent:be(this,Vc),onRetry:be(this,Fc)})),We(this,It,this.CONNECTING),We(this,ms,3e3),We(this,Ga,(r=n==null?void 0:n.fetch)!=null?r:globalThis.fetch),We(this,Wa,(o=n==null?void 0:n.withCredentials)!=null?o:!1),qn(this,ln,Zc).call(this)}get readyState(){return be(this,It)}get url(){return be(this,xr).href}get withCredentials(){return be(this,Wa)}get onerror(){return be(this,co)}set onerror(t){We(this,co,t)}get onmessage(){return be(this,uo)}set onmessage(t){We(this,uo,t)}get onopen(){return be(this,ys)}set onopen(t){We(this,ys,t)}addEventListener(t,n,r){const o=n;super.addEventListener(t,o,r)}removeEventListener(t,n,r){const o=n;super.removeEventListener(t,o,r)}close(){be(this,io)&&clearTimeout(be(this,io)),be(this,It)!==this.CLOSED&&(be(this,or)&&be(this,or).abort(),We(this,It,this.CLOSED),We(this,or,void 0))}}It=new WeakMap,xr=new WeakMap,ao=new WeakMap,Wa=new WeakMap,Ga=new WeakMap,ms=new WeakMap,io=new WeakMap,gs=new WeakMap,or=new WeakMap,lo=new WeakMap,co=new WeakMap,uo=new WeakMap,ys=new WeakMap,ln=new WeakSet,Zc=function(){We(this,It,this.CONNECTING),We(this,or,new AbortController),be(this,Ga)(be(this,xr),qn(this,ln,T0).call(this)).then(be(this,Uc)).catch(be(this,qc))},Uc=new WeakMap,qc=new WeakMap,T0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...be(this,gs)?{"Last-Event-ID":be(this,gs)}:void 0},cache:"no-store",signal:(e=be(this,or))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Vc=new WeakMap,Fc=new WeakMap,vs=function(e,t){var n;be(this,It)!==this.CLOSED&&We(this,It,this.CLOSED);const r=new C0("error",{code:t,message:e});(n=be(this,co))==null||n.call(this,r),this.dispatchEvent(r)},Bc=function(e,t){var n;if(be(this,It)===this.CLOSED)return;We(this,It,this.CONNECTING);const r=new C0("error",{code:t,message:e});(n=be(this,co))==null||n.call(this,r),this.dispatchEvent(r),We(this,io,setTimeout(be(this,Hc),be(this,ms)))},Hc=new WeakMap,Ka.CONNECTING=0,Ka.OPEN=1,Ka.CLOSED=2;function b7(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function Jc(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function x0(e=fetch,t){return t?async(n,r)=>{const o={...t,...r,headers:r!=null&&r.headers?{...Jc(t.headers),...Jc(r.headers)}:t.headers};return e(n,o)}:e}let Wc;Wc=globalThis.crypto;async function S7(e){return(await Wc).getRandomValues(new Uint8Array(e))}async function C7(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length;let r="";for(;r.length<e;){const o=await S7(e-r.length);for(const s of o)s<n&&(r+=t[s%t.length])}return r}async function $7(e){return await C7(e)}async function k7(e){const t=await(await Wc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function T7(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await $7(e),n=await k7(t);return{code_verifier:t,code_challenge:n}}const ct=T5().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:y6.custom,message:"URL must be parseable",fatal:!0}),S3}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),x7=lt({resource:p().url(),authorization_servers:A(ct).optional(),jwks_uri:p().url().optional(),scopes_supported:A(p()).optional(),bearer_methods_supported:A(p()).optional(),resource_signing_alg_values_supported:A(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:le().optional(),authorization_details_types_supported:A(p()).optional(),dpop_signing_alg_values_supported:A(p()).optional(),dpop_bound_access_tokens_required:le().optional()}),E0=lt({issuer:p(),authorization_endpoint:ct,token_endpoint:ct,registration_endpoint:ct.optional(),scopes_supported:A(p()).optional(),response_types_supported:A(p()),response_modes_supported:A(p()).optional(),grant_types_supported:A(p()).optional(),token_endpoint_auth_methods_supported:A(p()).optional(),token_endpoint_auth_signing_alg_values_supported:A(p()).optional(),service_documentation:ct.optional(),revocation_endpoint:ct.optional(),revocation_endpoint_auth_methods_supported:A(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:A(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A(p()).optional(),code_challenge_methods_supported:A(p()).optional(),client_id_metadata_document_supported:le().optional()}),E7=lt({issuer:p(),authorization_endpoint:ct,token_endpoint:ct,userinfo_endpoint:ct.optional(),jwks_uri:ct,registration_endpoint:ct.optional(),scopes_supported:A(p()).optional(),response_types_supported:A(p()),response_modes_supported:A(p()).optional(),grant_types_supported:A(p()).optional(),acr_values_supported:A(p()).optional(),subject_types_supported:A(p()),id_token_signing_alg_values_supported:A(p()),id_token_encryption_alg_values_supported:A(p()).optional(),id_token_encryption_enc_values_supported:A(p()).optional(),userinfo_signing_alg_values_supported:A(p()).optional(),userinfo_encryption_alg_values_supported:A(p()).optional(),userinfo_encryption_enc_values_supported:A(p()).optional(),request_object_signing_alg_values_supported:A(p()).optional(),request_object_encryption_alg_values_supported:A(p()).optional(),request_object_encryption_enc_values_supported:A(p()).optional(),token_endpoint_auth_methods_supported:A(p()).optional(),token_endpoint_auth_signing_alg_values_supported:A(p()).optional(),display_values_supported:A(p()).optional(),claim_types_supported:A(p()).optional(),claims_supported:A(p()).optional(),service_documentation:p().optional(),claims_locales_supported:A(p()).optional(),ui_locales_supported:A(p()).optional(),claims_parameter_supported:le().optional(),request_parameter_supported:le().optional(),request_uri_parameter_supported:le().optional(),require_request_uri_registration:le().optional(),op_policy_uri:ct.optional(),op_tos_uri:ct.optional(),client_id_metadata_document_supported:le().optional()}),I7=C({...E7.shape,...E0.pick({code_challenge_methods_supported:!0}).shape}),I0=C({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:O().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),P7=C({error:p(),error_description:p().optional(),error_uri:p().optional()}),P0=ct.optional().or(N("").transform(()=>{})),R7=C({redirect_uris:A(ct),token_endpoint_auth_method:p().optional(),grant_types:A(p()).optional(),response_types:A(p()).optional(),client_name:p().optional(),client_uri:ct.optional(),logo_uri:P0,scope:p().optional(),contacts:A(p()).optional(),tos_uri:P0,policy_uri:p().optional(),jwks_uri:ct.optional(),jwks:Mt().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),O7=C({client_id:p(),client_secret:p().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),N7=R7.merge(O7);C({error:p(),error_description:p().optional()}).strip(),C({token:p(),token_type_hint:p().optional()}).strip();function A7(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function M7({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),r=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return o.startsWith(s)}class ut extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class Gc extends ut{}Gc.errorCode="invalid_request";class Ya extends ut{}Ya.errorCode="invalid_client";class Qa extends ut{}Qa.errorCode="invalid_grant";class Xa extends ut{}Xa.errorCode="unauthorized_client";class Kc extends ut{}Kc.errorCode="unsupported_grant_type";class Yc extends ut{}Yc.errorCode="invalid_scope";class Qc extends ut{}Qc.errorCode="access_denied";class po extends ut{}po.errorCode="server_error";class Xc extends ut{}Xc.errorCode="temporarily_unavailable";class eu extends ut{}eu.errorCode="unsupported_response_type";class tu extends ut{}tu.errorCode="unsupported_token_type";class nu extends ut{}nu.errorCode="invalid_token";class ru extends ut{}ru.errorCode="method_not_allowed";class ou extends ut{}ou.errorCode="too_many_requests";class ei extends ut{}ei.errorCode="invalid_client_metadata";class su extends ut{}su.errorCode="insufficient_scope";const j7={[Gc.errorCode]:Gc,[Ya.errorCode]:Ya,[Qa.errorCode]:Qa,[Xa.errorCode]:Xa,[Kc.errorCode]:Kc,[Yc.errorCode]:Yc,[Qc.errorCode]:Qc,[po.errorCode]:po,[Xc.errorCode]:Xc,[eu.errorCode]:eu,[tu.errorCode]:tu,[nu.errorCode]:nu,[ru.errorCode]:ru,[ou.errorCode]:ou,[ei.errorCode]:ei,[su.errorCode]:su};class Bt extends Error{constructor(t){super(t??"Unauthorized")}}function L7(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const au="code",iu="S256";function R0(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&L7(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function O0(e,t,n,r){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":z7(o,s,n);return;case"client_secret_post":D7(o,s,r);return;case"none":Z7(o,r);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function z7(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${r}`)}function D7(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function Z7(e,t){t.set("client_id",e)}async function lu(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const r=P7.parse(JSON.parse(n)),{error:o,error_description:s,error_uri:a}=r,i=j7[o]||po;return new i(s||"",a)}catch(r){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new po(o)}}async function Er(e,t){var n,r;try{return await cu(e,t)}catch(o){if(o instanceof Ya||o instanceof Xa)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"all")),await cu(e,t);if(o instanceof Qa)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"tokens")),await cu(e,t);throw o}}async function cu(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:o,fetchFn:s}){var a,i;let l,c;try{l=await V7(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",t));const u=await q7(t,e,l),h=await W7(c,{fetchFn:s});let y=await Promise.resolve(e.clientInformation());if(!y){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const d=(h==null?void 0:h.client_id_metadata_document_supported)===!0,w=e.clientMetadataUrl;if(w&&!U7(w))throw new ei(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(d&&w)y={client_id:w},await((a=e.saveClientInformation)===null||a===void 0?void 0:a.call(e,y));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await Q7(c,{metadata:h,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(b),y=b}}if(n!==void 0){const d=await e.codeVerifier(),w=await K7(c,{metadata:h,clientInformation:y,authorizationCode:n,codeVerifier:d,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}const f=await e.tokens();if(f!=null&&f.refresh_token)try{const d=await Y7(c,{metadata:h,clientInformation:y,refreshToken:f.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(d),"AUTHORIZED"}catch(d){if(!(!(d instanceof ut)||d instanceof po))throw d}const g=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:m}=await G7(c,{metadata:h,clientInformation:y,state:g,redirectUrl:e.redirectUrl,scope:r||((i=l==null?void 0:l.scopes_supported)===null||i===void 0?void 0:i.join(" "))||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(v),"REDIRECT"}function U7(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function q7(e,t,n){const r=A7(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n==null?void 0:n.resource);if(n){if(!M7({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function ti(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[n,r]=t.split(" ");if(n.toLowerCase()!=="bearer"||!r)return{};const o=uu(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=uu(e,"scope")||void 0,i=uu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function uu(e,t){const n=e.headers.get("WWW-Authenticate");if(!n)return null;const r=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=n.match(r);return o?o[1]||o[2]:null}async function V7(e,t,n=fetch){const r=await H7(e,"oauth-protected-resource",n,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return x7.parse(await r.json())}async function du(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?du(e,void 0,n):void 0;throw r}}function F7(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function N0(e,t,n=fetch){return await du(e,{"MCP-Protocol-Version":t},n)}function B7(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function H7(e,t,n,r){var o,s;const a=new URL(e),i=(o=r==null?void 0:r.protocolVersion)!==null&&o!==void 0?o:ls;let l;if(r!=null&&r.metadataUrl)l=new URL(r.metadataUrl);else{const u=F7(t,a.pathname);l=new URL(u,(s=r==null?void 0:r.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let c=await N0(l,i,n);if(!(r!=null&&r.metadataUrl)&&B7(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await N0(u,i,n)}return c}function J7(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function W7(e,{fetchFn:t=fetch,protocolVersion:n=ls}={}){const r={"MCP-Protocol-Version":n,Accept:"application/json"},o=J7(e);for(const{url:s,type:a}of o){const i=await du(s,r,t);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 ${s}`)}return a==="oauth"?E0.parse(await i.json()):I7.parse(await i.json())}}}async function G7(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(au))throw new Error(`Incompatible auth server: does not support response type ${au}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(iu))throw new Error(`Incompatible auth server: does not support code challenge method ${iu}`)}else i=new URL("/authorize",e);const l=await T7(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",au),i.searchParams.set("client_id",n.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",iu),i.searchParams.set("redirect_uri",String(r)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o!=null&&o.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}async function K7(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",h=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t!=null&&t.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const y=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:u,code:r,code_verifier:o,redirect_uri:String(s)});if(i)i(y,f,e,t);else{const v=(c=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],m=R0(n,v);O0(m,n,y,f)}a&&f.set("resource",a.href);const g=await(l??fetch)(h,{method:"POST",headers:y,body:f});if(!g.ok)throw await lu(g);return I0.parse(await g.json())}async function Y7(e,{metadata:t,clientInformation:n,refreshToken:r,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:r});if(s)s(u,h,e,t);else{const f=(i=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],g=R0(n,f);O0(g,n,u,h)}o&&h.set("resource",o.href);const y=await(a??fetch)(c,{method:"POST",headers:u,body:h});if(!y.ok)throw await lu(y);return I0.parse({refresh_token:r,...await y.json()})}async function Q7(e,{metadata:t,clientMetadata:n,fetchFn:r}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(r??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw await lu(s);return N7.parse(await s.json())}class X7 extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class _s{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n==null?void 0:n.eventSourceInit,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._fetchWithInit=x0(n==null?void 0:n.fetch,n==null?void 0:n.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new Bt("No auth provider");let n;try{n=await Er(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Bt;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}return this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion),new Headers({...n,...(t=this._requestInit)===null||t===void 0?void 0:t.headers})}_startOrAuth(){var t,n,r;const o=(r=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&r!==void 0?r:fetch;return new Promise((s,a)=>{this._eventSource=new Ka(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await o(i,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:y}=ti(u);this._resourceMetadataUrl=h,this._scope=y}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,a);return}const c=new X7(i.code,i.message,i);a(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.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),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let h;try{h=Un.parse(JSON.parse(u.data))}catch(y){(l=this.onerror)===null||l===void 0||l.call(this,y);return}(c=this.onmessage)===null||c===void 0||c.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(t){if(!this._authProvider)throw new Bt("No auth provider");if(await Er(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Bt("Failed to authorize")}async close(){var t,n,r;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t){var n,r,o;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._endpoint,a);if(!i.ok){if(i.status===401&&this._authProvider){const{resourceMetadataUrl:c,scope:u}=ti(i);if(this._resourceMetadataUrl=c,this._scope=u,await Er(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Bt;return this.send(t)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}class ni extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=S0({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}}const e8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class ws extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class bs{constructor(t,n){var r;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._fetchWithInit=x0(n==null?void 0:n.fetch,n==null?void 0:n.requestInit),this._sessionId=n==null?void 0:n.sessionId,this._reconnectionOptions=(r=n==null?void 0:n.reconnectionOptions)!==null&&r!==void 0?r:e8}async _authThenStart(){var t;if(!this._authProvider)throw new Bt("No auth provider");let n;try{n=await Er(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Bt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(n.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=Jc((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,o;const{resumptionToken:s}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:a,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new ws(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),o)}_scheduleReconnection(t,n=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&n>=o){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);setTimeout(()=>{this._startOrAuthSse(t).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(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=n;let a,i=!1;(async()=>{var c,u,h,y;try{const f=t.pipeThrough(new TextDecoderStream).pipeThrough(new ni({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){const{value:v,done:m}=await f.read();if(m)break;if(v.id&&(a=v.id,i=!0,o==null||o(v.id)),!v.event||v.event==="message")try{const d=Un.parse(JSON.parse(v.data));s!==void 0&&hc(d)&&(d.id=s),(c=this.onmessage)===null||c===void 0||c.call(this,d)}catch(d){(u=this.onerror)===null||u===void 0||u.call(this,d)}}(r||i)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(f){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${f}`)),(r||i)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(v){(y=this.onerror)===null||y===void 0||y.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(t){if(!this._authProvider)throw new Bt("No auth provider");if(await Er(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Bt("Failed to authorize")}async close(){var t,n;(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var r,o,s,a;try{const{resumptionToken:i,onresumptiontoken:l}=n||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ch(t)?t.id:void 0}).catch(m=>{var d;return(d=this.onerror)===null||d===void 0?void 0:d.call(this,m)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},h=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,u),y=h.headers.get("mcp-session-id");if(y&&(this._sessionId=y),!h.ok){if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ws(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:d,scope:w}=ti(h);if(this._resourceMetadataUrl=d,this._scope=w,await Er(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Bt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(h.status===403&&this._authProvider){const{resourceMetadataUrl:d,scope:w,error:_}=ti(h);if(_==="insufficient_scope"){const b=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===b)throw new ws(403,"Server returned 403 after trying upscoping");if(w&&(this._scope=w),d&&(this._resourceMetadataUrl=d),this._lastUpscopingHeader=b??void 0,await Er(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Bt;return this.send(t)}}const m=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){I6(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var d;return(d=this.onerror)===null||d===void 0?void 0:d.call(this,m)});return}const g=(Array.isArray(t)?t:[t]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,v=h.headers.get("content-type");if(g)if(v!=null&&v.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:l},!1);else if(v!=null&&v.includes("application/json")){const m=await h.json(),d=Array.isArray(m)?m.map(w=>Un.parse(w)):[Un.parse(m)];for(const w of d)(s=this.onmessage)===null||s===void 0||s.call(this,w)}else throw new ws(-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 t,n,r;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new ws(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(r=this.onerror)===null||r===void 0||r.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n==null?void 0:n.onresumptiontoken})}}const t8="mcp";class A0{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,n)=>{this._socket=new WebSocket(this._url,t8),this._socket.onerror=r=>{var o;const s="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);n(s),(o=this.onerror)===null||o===void 0||o.call(this,s)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{var r;(r=this.onclose)===null||r===void 0||r.call(this)},this._socket.onmessage=r=>{var o,s;let a;try{a=Un.parse(JSON.parse(r.data))}catch(i){(o=this.onerror)===null||o===void 0||o.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,a)}})}async close(){var t;(t=this._socket)===null||t===void 0||t.close()}send(t){return new Promise((n,r)=>{var o;if(!this._socket){r(new Error("Not connected"));return}(o=this._socket)===null||o===void 0||o.send(JSON.stringify(t)),n()})}}function ri(){const e=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return ri=function(){return e},ri()}(function(e,t){const n=Qe,r=Qe,o=e();for(;;)try{if(parseInt(n(417))/1*(parseInt(n(421))/2)+parseInt(n(433))/3+parseInt(n(424))/4*(-parseInt(r(429))/5)+parseInt(r(423))/6*(-parseInt(r(418))/7)+-parseInt(r(430))/8+-parseInt(n(416))/9*(-parseInt(n(405))/10)+-parseInt(n(415))/11*(-parseInt(n(411))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ri,650197);const M0=()=>{const e=Qe,t={EGhzU:function(n,r){return n!==r},kIrDB:"undefined",llYQe:function(n,r){return n!==r},PZfJg:function(n,r){return n(r)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:t[e(407)](typeof window,t.kIrDB)?window:t.llYQe(typeof global,t.kIrDB)?global:typeof self!==e(398)?self:t.PZfJg(Function,t[e(399)])()},n8=(e,t,n)=>{const r=Qe,o=Qe,s={};s[r(410)]=o(398),s.dBkaX=function(i,l){return i===l},s[o(393)]="function";const a=s;typeof window!==a[o(410)]?e.postMessage(t,"*",n):o(428)in e&&a.dBkaX(typeof e.postMessage,a[r(393)])&&e.postMessage(t,n)},r8=(e,t)=>{const n=Qe,r=Qe,o={};o.MbsGh="addEventListener",o.PPniK=function(a,i){return a===i},o[n(419)]=r(412),o[r(404)]="onmessage",o[n(397)]="undefined";const s=o;s.MbsGh in e&&s.PPniK(typeof e[n(427)],s.wRKyh)?e[n(427)](n(400),t):s.thraG in e&&typeof e[r(413)]!==s[r(397)]&&(e.onmessage=t)};class Ss{constructor(t){const n=Qe;this[n(406)]=t}async start(){const t=Qe,n=Qe;this[t(406)]&&(this[t(406)][t(413)]=r=>{var o,s;const a=t,i=n;try{const l=Un[a(402)](r.data[a(400)]);(o=this[a(413)])==null||o.call(this,l,r[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[t(396)]=r=>{var o;const s=n,a=n,i=new Error(s(394)+JSON[a(395)](r));(o=this.onerror)==null||o.call(this,i)},this[t(406)][t(434)]())}async send(t,n){const r={lEyuq:function(o){return o()},YihNw:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=Qe,l=Qe;try{const c={};c[i(403)]=n==null?void 0:n[i(403)];const u={};u[l(400)]=t,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),r.lEyuq(o)}catch(c){const u=c instanceof Error?c:new Error(r.YihNw(String,c));(a=this[l(408)])==null||a.call(this,u),s(u)}})}async close(){var t,n;const r=Qe,o=Qe;(t=this._port)==null||t[r(431)](),this._port=void 0,(n=this[o(420)])==null||n.call(this)}}class pu extends Ss{constructor(t,n=M0()){const r=Qe,o=Qe,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[r(391)]=t,this[o(401)]=n;const a=new MessageChannel;this[o(406)]=a.port1,s[o(426)](n8,this[r(401)],{endpoint:this[o(391)]},[a[o(414)]])}}class fu extends Ss{constructor(t,n=M0()){const r=Qe,o={mOWMr:function(s,a){return s===a},kgkem:function(s,a,i){return s(a,i)}};super(),this._endpoint=t,this._globalObject=n,this[r(432)]=new Promise(s=>{const a=r,i=r;o[a(392)](r8,this[i(401)],l=>{const c=i,u=i;l.data&&o[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],s())})})}async listen(){return this[Qe(432)]}}function Qe(e,t){const n=ri();return Qe=function(r,o){return r=r-(17*-491+-669+9407),n[r]},Qe(e,t)}const o8=()=>{const e=new MessageChannel;return[new Ss(e.port1),new Ss(e.port2)]};(function(e,t){const n=qe,r=qe,o=e();for(;;)try{if(parseInt(n(355))/1+-parseInt(n(356))/2*(-parseInt(n(373))/3)+-parseInt(n(337))/4+parseInt(r(357))/5+-parseInt(r(389))/6*(-parseInt(n(396))/7)+parseInt(r(325))/8*(parseInt(n(382))/9)+-parseInt(n(366))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(oi,-763475+-52067*10+1724410);const s8=async(e,t,n)=>{var r;const o=qe,s=qe,a={};a[o(345)]="tools/list",a.rqstG="tools/call",a.WqUnk="resources/list",a[o(329)]=s(358),a[o(365)]=o(335),a.ookoz="resources/unsubscribe",a[o(385)]=o(340),a.VTIWq="prompts/list",a.SkoRK=o(376),a.QUtUV=o(388),a.XtowM=s(332);const i=a,{id:l,method:c,params:u}=n;let h={};switch(c){case i[s(345)]:h=await t.listTools(u);break;case i.rqstG:h=await t.callTool(u);break;case i[o(334)]:h=await t[o(350)](u);break;case i[s(329)]:h=await t.listResourceTemplates(u);break;case o(372):h=await t[o(383)](u);break;case i.HgYgW:h=await t.subscribeResource(u);break;case i.ookoz:h=await t.unsubscribeResource(u);break;case i[o(385)]:h=await t.getPrompt(u);break;case i.VTIWq:h=await t.listPrompts(u);break;case i[o(344)]:h=await t[o(376)]();break;case i.QUtUV:h=await t.complete(u);break;case o(390):h=await t[o(336)](u==null?void 0:u.level);break}const y={};y[o(361)]=h,y[o(394)]=i[o(364)],y.id=l,await((r=e==null?void 0:e.transport)==null?void 0:r[o(392)](y))},a8=async(e,t,n)=>{var r;const o=qe,s=qe,a={};a.jQBBS="sampling/createMessage",a.EZqgC="elicitation/create",a[o(370)]=s(376),a.aVeaL=s(332);const i=a,{id:l,method:c,params:u}=n;let h={};switch(c){case o(368):const f={};f.method=c,f[s(367)]=u,h=await t.request(f,Rc);break;case i[s(391)]:const g={};g.method=c,g[s(367)]=u,h=await t[s(381)](g,Ec);break;case i.EZqgC:const v={};v.method=c,v.params=u,h=await t.request(v,us);break;case i[s(370)]:const m={};m.method=c,h=await t[s(381)](m,rr);break}const y={};return y[s(361)]=h,y.jsonrpc=i[s(387)],y.id=l,await((r=e==null?void 0:e[o(371)])==null?void 0:r.send(y)),h},i8=(e,t)=>{const n=qe,r={gXsjT:function(s,a){return s===a},oegpC:n(351),lZOUC:function(s,a,i,l){return s(a,i,l)},ifIKG:"2.0"},o=e._onrequest;e._onrequest=async(s,a)=>{var i,l,c,u,h;const y=n,f=n,{id:g,method:v}=s;try{r[y(333)](v,r.oegpC)?await o[y(386)](e,s,a):await r.lZOUC(s8,e,t,s)}catch(m){const{code:d,message:w,data:_}=m;try{if(d){const b={};b.code=d,b.message=w,b.data=_;const T={};T.error=b,T[y(394)]=r[f(331)],T.id=g,await((i=e==null?void 0:e.transport)==null?void 0:i.send(T))}else(c=(l=e==null?void 0:e[f(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(h=(u=e==null?void 0:e[y(371)])==null?void 0:u.onerror)==null||h.call(u,b)}}}},l8=(e,t)=>{const n=qe,r=qe,o={};o[n(363)]=function(a,i){return a!==i},o[n(398)]=n(353),o.hzhyg="notifications/cancelled";const s=o;e._onnotification=async a=>{var i,l;const c=n,u=r,{method:h,params:y}=a;if(s[c(363)](h,s[u(398)])&&(s[c(363)](h,s.hzhyg)||y!=null&&y.forward))try{await t.notification(a)}catch(f){(l=(i=e==null?void 0:e.transport)==null?void 0:i.onerror)==null||l.call(i,f)}}},c8=(e,t)=>async n=>{var r,o,s,a,i;const l=qe,c=qe,u={};u.SEmWX=l(332);const h=u;try{return await a8(e,t,n)}catch(y){const{code:f,message:g,data:v}=y;try{if(f){const m={};m[c(377)]=f,m.message=g,m.data=v;const d={};d[c(348)]=m,d.jsonrpc=h[l(338)],d.id=n.id,await((r=e==null?void 0:e.transport)==null?void 0:r[c(392)](d))}else(s=(o=e==null?void 0:e.transport)==null?void 0:o[c(339)])==null||s.call(o,y)}catch(m){(i=(a=e==null?void 0:e[l(371)])==null?void 0:a[c(339)])==null||i.call(a,m)}}},u8=(e,t)=>async n=>{var r,o,s;const a=qe,i=qe,l={};l.dtUgZ=function(y,f){return y!==f},l.jgCIb=a(353),l.uUjKY="2.0";const c=l,{method:u,params:h}=n;if(c.dtUgZ(u,c.jgCIb)&&(u!==a(400)||h!=null&&h.forward))try{const y={...n};y[a(394)]=c[i(352)],await((r=t==null?void 0:t[a(371)])==null?void 0:r[a(392)](y))}catch(y){(s=(o=e==null?void 0:e[a(371)])==null?void 0:o[i(339)])==null||s.call(o,y)}};function qe(e,t){const n=oi();return qe=function(r,o){return r=r-(9*-113+-1439*-1+-97),n[r]},qe(e,t)}const d8=(e,t)=>async n=>{var r,o,s,a,i,l;const c=qe,u=qe,h={};h[c(401)]=u(332);const y=h;try{await((r=t==null?void 0:t.transport)==null?void 0:r.send(n))}catch(f){const{code:g,message:v,data:m}=f;try{if(g){const d={};d.code=g,d[c(399)]=v,d.data=m;const w={};w[c(348)]=d,w[c(394)]=y.OhJjz,w.id=n.id,await((o=e==null?void 0:e[c(371)])==null?void 0:o.send(w))}else(a=(s=e==null?void 0:e.transport)==null?void 0:s[u(339)])==null||a.call(s,f)}catch(d){(l=(i=e==null?void 0:e.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},hu=()=>{const e=qe,t=qe,n={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},r=[],o=(c,u)=>{const h=qe,y=qe;if(u){const f=[];for(const g of r)try{f.push(g(c,u))}catch{}for(const g of f)if(n[h(379)](g,null))return g}else for(const f of r)try{n[y(343)](f,c)}catch{}},s=c=>{const u=qe;n[u(384)](typeof c,u(369))&&!r.includes(c)&&r.push(c)},a=c=>{const u=r.indexOf(c);u!==-1&&r.splice(u,1*-6854+8*-33+7119)},i=()=>{const c=qe;r[c(374)]=7102*1+5522+-526*24},l={};return l[e(346)]=o,l[t(330)]=s,l.removeListener=a,l[e(359)]=i,l},p8=e=>{const t=qe,n=qe,r={xwPeb:function(o){return o()},Mfvzm:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=r[t(326)](hu);e._onresponse=o,e[t(395)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=r[n(326)](hu);e[n(328)]=o,e.addRequestListener=s,e[n(354)]=a,e[n(341)]=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=r[t(375)](hu);e[t(342)]=o,e[t(327)]=s,e.removeNotificationListener=a,e.clearNotificationListener=i}};function oi(){const e=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return oi=function(){return e},oi()}const f8=(e,{beforeInit:t,afterInit:n}={})=>{const r=qe,o=qe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:r(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},a=new Map(e._notificationHandlers);e[r(393)][r(402)](),e._notificationHandlers[r(402)](),s.tqDZP(typeof t,s[r(380)])&&t(),s[r(362)](e._onresponse.name,s[r(360)])&&(e[o(349)]=e._onresponse),s[r(347)](p8,e),e.addResponseListener(i=>{const l=o;e.originalOnResponse[l(386)](e,i)}),s.tqDZP(typeof n,s[o(380)])&&s[r(397)](n),e[o(327)](i=>{const{method:l}=i,c=a.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},h8=kn,m8=kn;(function(e,t){const n=kn,r=kn,o=e();for(;;)try{if(-parseInt(n(393))/1+parseInt(n(397))/2*(-parseInt(n(400))/3)+-parseInt(r(398))/4+parseInt(n(390))/5*(parseInt(r(388))/6)+-parseInt(n(389))/7+-parseInt(n(402))/8*(-parseInt(r(395))/9)+parseInt(r(399))/10*(parseInt(r(385))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(si,-1*-881393+2*180895+1*-644809);function kn(e,t){const n=si();return kn=function(r,o){return r=r-(-1861+-499*4+4241),n[r]},kn(e,t)}function si(){const e=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return si=function(){return e},si()}const g8=()=>{const e=kn,t=kn,n={};n.REzPF=function(o,s){return o&s},n.suJHI=function(o,s){return o===s},n[e(386)]=function(o,s){return o&s},n[t(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const r=n;return r.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[t(391)]():r.dHTfU.replace(/[xy]/g,o=>{const s=e,a=e,i=r[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(r.suJHI(o,"x")?i:r[a(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},y8=e=>{const t=kn,n=kn,r=new Uint8Array(e);return crypto.getRandomValues(r),Array[t(401)](r,o=>o[n(403)](-3*1739+-6509+2*5871)[t(387)](2,"0")).join("")},sr={};sr[h8(391)]=g8,sr[m8(396)]=y8;const jt=Tn;(function(e,t){const n=Tn,r=Tn,o=e();for(;;)try{if(parseInt(n(521))/1*(parseInt(r(499))/2)+parseInt(r(543))/3*(parseInt(r(514))/4)+parseInt(n(502))/5*(parseInt(r(539))/6)+parseInt(n(553))/7+parseInt(n(516))/8*(-parseInt(n(518))/9)+-parseInt(n(531))/10+-parseInt(n(545))/11*(parseInt(n(541))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ai,1472653*1+-2*-897917+-2275789);const v8=(e,t)=>{const n=Tn,r=Tn,o={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};i8(e,t),l8(e,t);const s=c8(t,e),a=o[n(510)](d8,t,e),i=o[r(549)](u8,t,e);t[r(537)](s),t[n(519)](a),t.addNotificationListener(i),e[r(556)]=()=>{const l=r;t.removeRequestListener(s),t[l(530)](a),t[l(529)](i)}},mu=(e,t,n)=>{const r=Tn,o={pMiva:function(i,l){return i instanceof l},TeTEy:r(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=r;o.pMiva(n,_s)&&((i=n._eventSource)==null||i.addEventListener(o[l(547)],()=>{var c;const u=l;(c=n[u(509)])==null||c[u(546)]()})),v8(e,t)},a={};a.afterInit=s,o.fyZbd(f8,t,a)},j0=(e,t=sr.randomUUID())=>{const n=Tn,r=Tn,o={OfssH:function(u,h,y){return u(h,y)}},s={};s[n(528)]=t;const a=s,i={};i[n(528)]=t;const l={};l[r(558)]=i,l[n(534)]=n(524);const c={requestInit:l,eventSourceInit:{async fetch(u,h){const y=n,f=r,g=new Headers((h==null?void 0:h[y(558)])||{});Object.entries(a)[f(498)](([m,d])=>{g[f(527)](m,d)});const v={...h};return v[f(558)]=g,o.OfssH(fetch,u,v)},withCredentials:!0}};return e&&(c.requestInit[n(558)].Authorization=n(533)+e,a.Authorization="Bearer "+e),c},L0=(e,t=sr[jt(517)]())=>{const n=jt,r=jt,o={};o.nwQhY="include";const s=o,a={};a["stream-session-id"]=t;const i={};i.headers=a,i.credentials=s[n(520)];const l={};l[n(544)]=i;const c=l;return e&&(c.requestInit.headers[r(552)]=r(533)+e),c},gu=async(e,t,n)=>{const r=jt,o=jt,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},a=s.CFfFC(n);try{return await e[r(538)](a),a}catch(i){if(i instanceof Bt){const l=await t();return await a[o(505)](l),await s[r(525)](gu,e,t,n)}else throw i}};function Tn(e,t){const n=ai();return Tn=function(r,o){return r=r-(74*-67+-8341+-73*-189),n[r]},Tn(e,t)}const z0=(e,t)=>{const n=jt,r=jt,o={};o.RsKXs=function(a,i){return a in i},o.PBhps="waitForOAuthCode",o[n(535)]="function",o[n(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=o;if(s.RsKXs(s[r(551)],e))return e[r(523)];if(typeof t===s.yTKoP)return t;throw new Error(s.RZhOv)},_8=async e=>{const t=jt,n=jt,r={TFSRn:function(U,W,V){return U(W,V)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(U){return U()},WIVYl:function(U,W,V,B){return U(W,V,B)},jniGY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=e,y={};y.authProvider=l,y.requestInit=c,y.eventSourceInit=u;const f=y,g=i||sr.randomUUID(),v=r[t(506)](j0,a,g);if(c){const U={...v.requestInit,...c};U.headers={...v[t(544)].headers,...c.headers},f.requestInit=U}else f[n(544)]=v.requestInit;if(u){const U={...v[t(559)],...u};f.eventSourceInit=U}else f.eventSourceInit=v.eventSourceInit;const m={};m.listChanged=!0;const d={};d.roots=m,d.sampling={},d[t(511)]={};const w=d,_={};_[n(536)]=r.HwvVa,_.version=t(526);const b={};b.capabilities=w;const T=new hs(_,b),P=()=>new _s(new URL(s),f);let E=r[n(504)](P);if(l){const U=r[t(506)](z0,l,h);E=await r[n(513)](gu,T,U,P)}else await T[t(538)](E);r[n(513)](mu,T,o,E),E[n(557)]=E[n(542)].searchParams[n(532)](r.jniGY);const Z={};return Z.transport=E,Z.sessionId=E[t(557)],Z};function ai(){const e=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ai=function(){return e},ai()}const w8=async e=>{const t=jt,n=jt,r={Vajmx:t(500),biJOc:function(U){return U()},zXcpO:function(U,W,V){return U(W,V)},zDnjZ:function(U,W,V,B){return U(W,V,B)},FQMAh:function(U,W,V,B){return U(W,V,B)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=e,y={};y.authProvider=l,y.requestInit=c,y.reconnectionOptions=u;const f=y,g=i||sr.randomUUID(),v=L0(a,g);if(c){const U={...v.requestInit,...c};U.headers={...v.requestInit.headers,...c.headers},f[t(544)]=U}else f.requestInit=v.requestInit;const m={};m.listChanged=!0;const d={};d[n(550)]=m,d.sampling={},d.elicitation={};const w=d,_={};_[t(536)]=r[n(508)],_[t(555)]="1.0.0";const b={};b.capabilities=w;const T=new hs(_,b),P=()=>new bs(new URL(s),f);let E=r[t(503)](P);if(l){const U=r[t(501)](z0,l,h);E=await r.zDnjZ(gu,T,U,P)}else await T.connect(E);r.FQMAh(mu,T,o,E);const Z={};return Z.transport=E,Z[n(557)]=E.sessionId,Z},b8=async e=>{const t=jt,n=jt,r={QgzDy:t(540),jkaVB:function(d,w,_,b){return d(w,_,b)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l.listChanged=!0;const c={};c[t(550)]=l,c[t(515)]={},c[n(511)]={};const u=c,h={};h.name=r[n(548)],h[n(555)]=n(526);const y={};y.capabilities=u;const f=new hs(h,y),g=i||sr[n(517)](),v=new A0(new URL(s+t(522)+g+n(554)+a));await f.connect(v),r.jkaVB(mu,f,o,v);const m={};return m[t(512)]=v,m[n(557)]=g,m},Cs=Pt,ii=Pt;function Pt(e,t){const n=li();return Pt=function(r,o){return r=r-(-16761+51*337),n[r]},Pt(e,t)}(function(e,t){const n=Pt,r=Pt,o=e();for(;;)try{if(-parseInt(n(440))/1+-parseInt(n(458))/2*(parseInt(n(448))/3)+-parseInt(n(451))/4*(parseInt(r(449))/5)+-parseInt(r(455))/6+-parseInt(n(427))/7+-parseInt(r(438))/8*(parseInt(r(459))/9)+parseInt(n(430))/10*(parseInt(r(436))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(li,-220880+1*-333337+-2*-384996);function li(){const e=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return li=function(){return e},li()}const S8=()=>sr.randomBytes(3485*1+-261+-3184);class C8{constructor(t){const n=Pt,r=Pt;this._callBackPromise={};const{clientMetadata:o,state:s,redirectCallback:a,getAuthCodeByState:i,waitForOAuthCode:l}=t;this[n(428)]=o,this[n(454)]=o[n(445)][0],this._state=s||S8(),this._redirectCallback=a||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[r(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var n,r,o,s,a,i;const l=Pt,c=Pt,u={qITTp:function(g,v,m){return g(v,m)},qcFPW:l(452)},h=await u.qITTp(fetch,t,{method:u[l(453)]});!h.ok&&((r=(n=this._callBackPromise).reject)==null||r.call(n,c(446)+h.statusText));const y=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!y.ok){(s=(o=this[l(433)]).reject)==null||s.call(o,"Failed to fetch auth code: "+y.statusText);return}const f=await y[l(431)]();(i=(a=this[c(433)])[l(456)])==null||i.call(a,f[l(432)])}async getAuthCodeByStateFunction(t,n){const r=Pt,o=Pt,s={};s.tuSmb=r(429);const a=s,i={};i[r(460)]=a.tuSmb;const l={};return l[o(441)]=n,fetch(t,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const t=Pt,n=this[t(433)];return()=>new Promise((r,o)=>{const s=t;n.resolve=r,n[s(434)]=o})}get redirectUrl(){return this[Pt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Cs(447)](){return this[Cs(444)]}[ii(435)](t){const n=Cs;this[n(444)]=t}[ii(457)](){return this[ii(439)]}saveTokens(t){this._tokens=t}[ii(450)](t){this[Cs(443)](t)}saveCodeVerifier(t){this._codeVerifier=t}codeVerifier(){if(!this[Cs(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(e,t){for(var n=ui,r=ui,o=e();;)try{var s=parseInt(n(361))/1*(parseInt(r(363))/2)+-parseInt(n(358))/3+parseInt(n(359))/4*(parseInt(n(357))/5)+parseInt(r(354))/6*(parseInt(n(360))/7)+parseInt(r(362))/8+parseInt(r(364))/9+-parseInt(r(356))/10*(parseInt(n(355))/11);if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ci,-73523*-3+1*-407717+530518);function ci(){var e=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return ci=function(){return e},ci()}function ui(e,t){var n=ci();return ui=function(r,o){r=r-(-1*-642+503*-5+2227);var s=n[r];return s},ui(e,t)}class $8 extends m0{constructor(t,n){var r,o;super(n),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qa.options.map((s,a)=>[s,a])),this.isMessageIgnored=(s,a)=>{const i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(s)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=(r=n==null?void 0:n.capabilities)!==null&&r!==void 0?r:{},this._instructions=n==null?void 0:n.instructions,this._jsonSchemaValidator=(o=n==null?void 0:n.jsonSchemaValidator)!==null&&o!==void 0?o:new w0,this.setRequestHandler(Eh,s=>this._oninitialize(s)),this.setNotificationHandler(gc,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)}),this._capabilities.logging&&this.setRequestHandler(Va,async(s,a)=>{var i;const l=a.sessionId||((i=a.requestInfo)===null||i===void 0?void 0:i.headers["mcp-session-id"])||void 0,{level:c}=s.params,u=qa.safeParse(c);return u.success&&this._loggingLevels.set(l,u.data),{}})}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=y0(this._capabilities,t)}assertCapabilityForMethod(t){var n,r,o;switch(t){case"sampling/createMessage":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.sampling))throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.elicitation))throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!(!((o=this._clientCapabilities)===null||o===void 0)&&o.roots))throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){var n,r;switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!(!((r=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||r===void 0)&&r.url))throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break}}async _oninitialize(t){const n=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:_h.includes(n)?n:ls,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"},rr)}async createMessage(t,n){var r,o;if((t.tools||t.toolChoice)&&!(!((o=(r=this._clientCapabilities)===null||r===void 0?void 0:r.sampling)===null||o===void 0)&&o.tools))throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){const s=t.messages[t.messages.length-1],a=Array.isArray(s.content)?s.content:[s.content],i=a.some(h=>h.type==="tool_result"),l=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=l?Array.isArray(l.content)?l.content:[l.content]:[],u=c.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(c.filter(f=>f.type==="tool_use").map(f=>f.id)),y=new Set(a.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(h.size!==y.size||![...h].every(f=>y.has(f)))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:t},Ec,n)}async elicitInput(t,n){var r,o,s,a,i;switch((r=t.mode)!==null&&r!==void 0?r:"form"){case"url":{if(!(!((s=(o=this._clientCapabilities)===null||o===void 0?void 0:o.elicitation)===null||s===void 0)&&s.url))throw new Error("Client does not support url elicitation.");const c=t;return this.request({method:"elicitation/create",params:c},us,n)}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 c=t.mode==="form"?t:{...t,mode:"form"},u=await this.request({method:"elicitation/create",params:c},us,n);if(u.action==="accept"&&u.content&&c.requestedSchema)try{const y=this._jsonSchemaValidator.getValidator(c.requestedSchema)(u.content);if(!y.valid)throw new Ie(Ee.InvalidParams,`Elicitation response content does not match requested schema: ${y.errorMessage}`)}catch(h){throw h instanceof Ie?h:new Ie(Ee.InternalError,`Error validating elicitation response: ${h instanceof Error?h.message:String(h)}`)}return u}}}createElicitationCompletionNotifier(t,n){var r,o;if(!(!((o=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||o===void 0)&&o.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},n)}async listRoots(t,n){return this.request({method:"roots/list",params:t},Rc,n)}async sendLoggingMessage(t,n){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,n))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const yu=Symbol.for("mcp.completable");function k8(e,t){return Object.defineProperty(e,yu,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function T8(e){return!!e&&typeof e=="object"&&yu in e}function x8(e){const t=e[yu];return t==null?void 0:t.complete}var D0;(function(e){e.Completable="McpCompletable"})(D0||(D0={}));const Z0=1e6,vu=1e6,U0=1e4,E8=1e6;class Vn{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,n,r){if(t.length>n)throw new Error(`${r} exceeds maximum length of ${n} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){Vn.validateLength(t,Z0,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){const n=[];let r="",o=0,s=0;for(;o<t.length;)if(t[o]==="{"){r&&(n.push(r),r="");const a=t.indexOf("}",o);if(a===-1)throw new Error("Unclosed template expression");if(s++,s>U0)throw new Error(`Template contains too many expressions (max ${U0})`);const i=t.slice(o+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),h=u[0];for(const y of u)Vn.validateLength(y,vu,"Variable name");n.push({name:h,operator:l,names:u,exploded:c}),o=a+1}else r+=t[o],o++;return r&&n.push(r),n}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){const n=this.getOperator(t);return t.slice(n.length).split(",").map(r=>r.replace("*","").trim()).filter(r=>r.length>0)}encodeValue(t,n){return Vn.validateLength(t,vu,"Variable value"),n==="+"||n==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,n){if(t.operator==="?"||t.operator==="&"){const a=t.names.map(l=>{const c=n[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(h=>this.encodeValue(h,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(t.operator==="?"?"?":"&")+a.join("&")}if(t.names.length>1){const a=t.names.map(i=>n[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const r=n[t.name];if(r===void 0)return"";const s=(Array.isArray(r)?r:[r]).map(a=>this.encodeValue(a,t.operator));switch(t.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(t){let n="",r=!1;for(const o of this.parts){if(typeof o=="string"){n+=o;continue}const s=this.expandPart(o,t);s&&((o.operator==="?"||o.operator==="&")&&r?n+=s.replace("?","&"):n+=s,(o.operator==="?"||o.operator==="&")&&(r=!0))}return n}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){const n=[];for(const s of t.names)Vn.validateLength(s,vu,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const a=t.names[s],i=s===0?"\\"+t.operator:"&";n.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return n}let r;const o=t.name;switch(t.operator){case"":r=t.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":r="(.+)";break;case".":r="\\.([^/,]+)";break;case"/":r="/"+(t.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:r="([^/]+)"}return n.push({pattern:r,name:o}),n}match(t){Vn.validateLength(t,Z0,"URI");let n="^";const r=[];for(const i of this.parts)if(typeof i=="string")n+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)n+=c,r.push({name:u,exploded:i.exploded})}n+="$",Vn.validateLength(n,E8,"Generated regex pattern");const o=new RegExp(n),s=t.match(o);if(!s)return null;const a={};for(let i=0;i<r.length;i++){const{name:l,exploded:c}=r[i],u=s[i+1],h=l.replace("*","");c&&u.includes(",")?a[h]=u.split(","):a[h]=u}return a}}const I8=/^[A-Za-z0-9._-]{1,128}$/;function P8(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!I8.test(e)){const n=e.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return t.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function R8(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const n of t)console.warn(` - ${n}`);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 q0(e){const t=P8(e);return R8(e,t.warnings),t.isValid}class V0{constructor(t,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new $8(t,n)}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ar(Tc)),this.server.assertCanSetRequestHandler(ar(xc)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Tc,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,n])=>{const r={name:t,title:n.title,description:n.description,inputSchema:(()=>{const o=fs(n.inputSchema);return o?p0(o,{strictUnions:!0,pipeStrategy:"input"}):N8})(),annotations:n.annotations,_meta:n._meta};if(n.outputSchema){const o=fs(n.outputSchema);o&&(r.outputSchema=p0(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(xc,async(t,n)=>{const r=this._registeredTools[t.params.name];let o;try{if(!r)throw new Ie(Ee.InvalidParams,`Tool ${t.params.name} not found`);if(!r.enabled)throw new Ie(Ee.InvalidParams,`Tool ${t.params.name} disabled`);if(r.inputSchema){const s=r.callback,a=fs(r.inputSchema),i=a??r.inputSchema,l=await Oc(i,t.params.arguments);if(!l.success)throw new Ie(Ee.InvalidParams,`Input validation error: Invalid arguments for tool ${t.params.name}: ${Nc(l.error)}`);const c=l.data;o=await Promise.resolve(s(c,n))}else{const s=r.callback;o=await Promise.resolve(s(n))}if(r.outputSchema&&!o.isError){if(!o.structuredContent)throw new Ie(Ee.InvalidParams,`Output validation error: Tool ${t.params.name} has an output schema but no structured content was provided`);const s=fs(r.outputSchema),a=await Oc(s,o.structuredContent);if(!a.success)throw new Ie(Ee.InvalidParams,`Output validation error: Invalid structured content for tool ${t.params.name}: ${Nc(a.error)}`)}}catch(s){if(s instanceof Ie&&s.code===Ee.UrlElicitationRequired)throw s;return this.createToolError(s instanceof Error?s.message:String(s))}return o}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ar(Pc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Pc,async t=>{switch(t.params.ref.type){case"ref/prompt":return bS(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return SS(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Ie(Ee.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,n){const r=this._registeredPrompts[n.name];if(!r)throw new Ie(Ee.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new Ie(Ee.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return $s;const o=ps(r.argsSchema),s=o==null?void 0:o[t.params.argument.name];if(!T8(s))return $s;const a=x8(s);if(!a)return $s;const i=await a(t.params.argument.value,t.params.context);return B0(i)}async handleResourceCompletion(t,n){const r=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return $s;throw new Ie(Ee.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=r.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return $s;const s=await o(t.params.argument.value,t.params.context);return B0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ar(Za)),this.server.assertCanSetRequestHandler(ar(wc)),this.server.assertCanSetRequestHandler(ar(Sc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Za,async(t,n)=>{const r=Object.entries(this._registeredResources).filter(([s,a])=>a.enabled).map(([s,a])=>({uri:s,name:a.name,...a.metadata})),o=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const a=await s.resourceTemplate.listCallback(n);for(const i of a.resources)o.push({...s.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler(wc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Sc,async(t,n)=>{const r=new URL(t.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Ie(Ee.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(r.toString());if(a)return s.readCallback(r,a,n)}throw new Ie(Ee.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ar(Cc)),this.server.assertCanSetRequestHandler(ar($c)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Cc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,n])=>({name:t,title:n.title,description:n.description,arguments:n.argsSchema?M8(n.argsSchema):void 0}))})),this.server.setRequestHandler($c,async(t,n)=>{const r=this._registeredPrompts[t.params.name];if(!r)throw new Ie(Ee.InvalidParams,`Prompt ${t.params.name} not found`);if(!r.enabled)throw new Ie(Ee.InvalidParams,`Prompt ${t.params.name} disabled`);if(r.argsSchema){const o=fs(r.argsSchema),s=await Oc(o,t.params.arguments);if(!s.success)throw new Ie(Ee.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${Nc(s.error)}`);const a=s.data,i=r.callback;return await Promise.resolve(i(a,n))}else{const o=r.callback;return await Promise.resolve(o(n))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(t,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());const s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);const a=this._createRegisteredResource(t,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);const s=this._createRegisteredResource(t,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,n,r,o,s){const a={name:t,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],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[r]=a,a}_createRegisteredResourceTemplate(t,n,r,o,s){const a={resourceTemplate:r,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==t&&(delete this._registeredResourceTemplates[t],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[t]=a,a}_createRegisteredPrompt(t,n,r,o,s){const a={title:n,description:r,argsSchema:o===void 0?void 0:ds(o),callback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==t&&(delete this._registeredPrompts[t],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=ds(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,a}_createRegisteredTool(t,n,r,o,s,a,i,l){q0(t);const c={title:n,description:r,inputSchema:F0(o),outputSchema:F0(s),annotations:a,_meta:i,callback:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(typeof u.name=="string"&&q0(u.name),delete this._registeredTools[t],u.name&&(this._registeredTools[u.name]=c)),typeof u.title<"u"&&(c.title=u.title),typeof u.description<"u"&&(c.description=u.description),typeof u.paramsSchema<"u"&&(c.inputSchema=ds(u.paramsSchema)),typeof u.callback<"u"&&(c.callback=u.callback),typeof u.annotations<"u"&&(c.annotations=u.annotations),typeof u._meta<"u"&&(c._meta=u._meta),typeof u.enabled<"u"&&(c.enabled=u.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(t,...n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let r,o,s,a;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){const l=n[0];_u(l)?(o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!_u(n[0])&&(a=n.shift())):typeof l=="object"&&l!==null&&(a=n.shift())}const i=n[0];return this._createRegisteredTool(t,void 0,r,o,s,a,void 0,i)}registerTool(t,n,r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);const{title:o,description:s,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=n;return this._createRegisteredTool(t,o,s,a,i,l,c,r)}prompt(t,...n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());const s=n[0],a=this._createRegisteredPrompt(t,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,n,r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);const{title:o,description:s,argsSchema:a}=n,i=this._createRegisteredPrompt(t,o,s,a,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,n){return this.server.sendLoggingMessage(t,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class O8{constructor(t,n){this._callbacks=n,this._uriTemplate=typeof t=="string"?new Vn(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){var n;return(n=this._callbacks.complete)===null||n===void 0?void 0:n[t]}}const N8={type:"object",properties:{}};function _u(e){return typeof e!="object"||e===null?!1:Object.keys(e).length===0||Object.values(e).some(A8)}function A8(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function F0(e){if(e)return _u(e)?ds(e):e}function M8(e){const t=ps(e);return t?Object.entries(t).map(([n,r])=>{const o=xS(r),s=ES(r);return{name:n,description:o,required:!s}}):[]}function ar(e){const t=ps(e),n=t==null?void 0:t.method;if(!n)throw new Error("Schema is missing a method literal");const r=n0(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function B0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const $s={completion:{values:[],hasMore:!1}};function j8(e){var t;return e.title!==void 0&&e.title!==""?e.title:!((t=e.annotations)===null||t===void 0)&&t.title?e.annotations.title:e.name}class ks{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new ks,n=new ks;return t._otherTransport=n,n._otherTransport=t,[t,n]}async start(){for(var t;this._messageQueue.length>0;){const n=this._messageQueue.shift();(t=this.onmessage)===null||t===void 0||t.call(this,n.message,n.extra)}}async close(){var t;const n=this._otherTransport;this._otherTransport=void 0,await(n==null?void 0:n.close()),(t=this.onclose)===null||t===void 0||t.call(this)}async send(t,n){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:n==null?void 0:n.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:n==null?void 0:n.authInfo}})}}class L8{constructor(t,n){const r={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new V0(t||r,n||{capabilities:o}),this.server.server.oninitialized=()=>{var s;(s=this.oninitialized)==null||s.call(this)},this.server.server.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.server.server.onerror=s=>{var a;(a=this.onerror)==null||a.call(this,s)},this.server.server.setRequestHandler(Va,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new fu(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,n,r){return this.server.registerTool(t,n,r)}registerPrompt(t,n,r){return this.server.registerPrompt(t,n,r)}registerResource(t,n,r,o){return typeof n=="string"?this.server.registerResource(t,n,r,o):this.server.registerResource(t,n,r,o)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(t,n){return await this.server.server.createMessage(t,n)}async elicitInput(t,n){return await this.server.server.elicitInput(t,n)}async listRoots(t,n){return await this.server.server.listRoots(t,n)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,n,r){return this.server.server.request(t,n,r)}async notification(t,n){return await this.server.server.notification(t,n)}setRequestHandler(t,n){this.server.server.setRequestHandler(t,n)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,n){this.server.server.setNotificationHandler(t,n)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(zh,t)}onUnsubscribe(t){this.server.server.setRequestHandler(Dh,t)}onSetLogLevel(t){this.server.server.setRequestHandler(Va,t)}onListResources(t){this.server.server.setRequestHandler(Za,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(e0,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const z8=(e,t)=>new fu(e,t),D8=()=>o8(),Z8=e=>e instanceof fu,U8=e=>e instanceof V0;class H0{constructor(t,n){const r={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new hs(t||r,n||{capabilities:o}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var a;(a=this.onerror)==null||a.call(this,s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:n,token:r,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:n,token:r,sessionId:o};let h;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await _8(u):s==="socket"?await b8(u):await w8(u);f.onerror=async v=>{i==null||i(v)},h={transport:f,sessionId:g}})(),h}const l=new URL(n);let c;if(s==="channel"&&(c=new pu(n),await this.client.connect(c)),s==="sse"){const u=j0(r,o);c=new _s(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new A0(new URL(`${n}?sessionId=${o}&token=${r}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=L0(r,o);c=new bs(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,n){return await this.client.complete(t,n)}async setLoggingLevel(t,n){return await this.client.setLoggingLevel(t,n)}async getPrompt(t,n){return await this.client.getPrompt(t,n)}async listPrompts(t,n){return await this.client.listPrompts(t,n)}async listResources(t,n){return await this.client.listResources(t,n)}async listResourceTemplates(t,n){return await this.client.listResourceTemplates(t,n)}async readResource(t,n){return await this.client.readResource(t,n)}async subscribeResource(t,n){return await this.client.subscribeResource(t,n)}async unsubscribeResource(t,n){return await this.client.unsubscribeResource(t,n)}async callTool(t,n){return await this.client.callTool(t,Ua,n)}async listTools(t,n){return await this.client.listTools(t,n)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,n,r){return this.client.request(t,n,r)}async notification(t,n){return await this.client.notification(t,n)}setRequestHandler(t,n){this.client.setRequestHandler(t,n)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,n){this.client.setNotificationHandler(t,n)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(Ic,t)}onCreateMessage(t){this.client.setRequestHandler(Yh,t)}onListRoots(t){this.client.setRequestHandler(Xh,t)}onToolListChanged(t){this.client.setNotificationHandler(Gh,t)}onPromptListChanged(t){this.client.setNotificationHandler(Hh,t)}onResourceListChanged(t){this.client.setNotificationHandler(Lh,t)}onResourceUpdated(t){this.client.setNotificationHandler(Zh,t)}onLoggingMessage(t){this.client.setNotificationHandler(Kh,t)}async onPagehide(t){t.persisted||(J0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const q8=(e,t)=>new _s(e,t),V8=(e,t)=>new bs(e,t),F8=(e,t)=>new pu(e,t),B8=e=>e instanceof _s,J0=e=>e instanceof bs,H8=e=>e instanceof pu,J8=e=>e instanceof hs,fo=(e,t,n)=>{window.postMessage({type:e,direction:n,data:t},"*")},W0=(e,t,n)=>{const r=async function(o){o.source===window&&o.data.type===e&&o.data.direction===n&&await t(o.data.data)};return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},wu=(e,t,n)=>{if(n.endsWith("content"))chrome.tabs.query({},r=>{r.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:n,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:n,type:e,data:t})},bu=(e,t,n,r)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===n&&(!r||r&&s.tabId===r)){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class G0{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=bu("mcp-server-to-client",n=>{var r;try{if(n.sessionId!==this.targetSessionId)return;const o=Un.parse(n.mcpMessage);(r=this.onmessage)==null||r.call(this,o)}catch(o){console.log("【Client Transport】处理server消息错误:",o)}},"content->side")}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,n){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const r=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!r,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=r.tabIds[r.tabIds.length-1];wu("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const K0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});class W8{constructor(t=null,n){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||K0(),this.tabId=n,this._messageListener1=W0("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=W0("mcp-client-to-server-to-page",r=>{var a,i,l;if(r.sessionId!==this.sessionId||r.tabId!==this.tabId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const o=Un.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,o),((i=r.mcpMessage.params)==null?void 0:i.name)&&fo("update-page-app-message",{status:"run",message:(l=r.mcpMessage.params)==null?void 0:l.name},"page->content")},"content->page")}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(t,n){var r;this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),fo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&((r=t.result)!=null&&r.content)&&fo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{fo("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"page->content")}catch(n){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(n))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}class G8{constructor(t=null,n){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||K0(),this.tabId=n,bu("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.log("【Content Svr Transport】 notifyRegistration 失败",r)})},"side->content",this.tabId)}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");bu("mcp-client-to-server",t=>{var n,r,o;if(!(t.sessionId!==this.sessionId||t.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",t.mcpMessage);const s=Un.parse(t.mcpMessage);(n=this.onmessage)==null||n.call(this,s),((r=t.mcpMessage.params)==null?void 0:r.name)&&fo("update-page-app-message",{status:"run",message:(o=t.mcpMessage.params)==null?void 0:o.name},"page->content")}catch(s){console.log("【Content Svr Transport】 处理消息时发生错误:",s)}},"side->content",this.tabId),this._isStarted=!0}}async send(t,n){var r;this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",t),wu("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->side"),"result"in t&&((r=t.result)!=null&&r.content)&&fo("update-page-app-message",{status:"ready",message:""},"page->content")}catch(o){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(o))}}async notifyRegistration(t){this._isStarted&&(this._lastRegistration=t,wu("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(t))}}}var ho={},K8=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Y0={},Lt={};let Su;const Y8=[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];Lt.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},Lt.getSymbolTotalCodewords=function(t){return Y8[t]},Lt.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},Lt.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Su=t},Lt.isKanjiModeEnabled=function(){return typeof Su<"u"},Lt.toSJIS=function(t){return Su(t)};var di={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(di);function Q0(){this.buffer=[],this.length=0}Q0.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var Q8=Q0;function Ts(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)}Ts.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},Ts.prototype.get=function(e,t){return this.data[e*this.size+t]},Ts.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},Ts.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var X8=Ts,X0={};(function(e){const t=Lt.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(X0);var em={};const eC=Lt.getSymbolSize,tm=7;em.getPositions=function(t){const n=eC(t);return[[0,0],[n-tm,0],[0,n-tm]]};var nm={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let h=0;h<s;h++){i=l=0,c=u=null;for(let y=0;y<s;y++){let f=o.get(h,y);f===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=f,i=1),f=o.get(y,h),f===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=f,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(nm);var pi={};const ir=di,fi=[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],hi=[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];pi.getBlocksCount=function(t,n){switch(n){case ir.L:return fi[(t-1)*4+0];case ir.M:return fi[(t-1)*4+1];case ir.Q:return fi[(t-1)*4+2];case ir.H:return fi[(t-1)*4+3];default:return}},pi.getTotalCodewordsCount=function(t,n){switch(n){case ir.L:return hi[(t-1)*4+0];case ir.M:return hi[(t-1)*4+1];case ir.Q:return hi[(t-1)*4+2];case ir.H:return hi[(t-1)*4+3];default:return}};var rm={},mi={};const xs=new Uint8Array(512),gi=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)xs[n]=t,gi[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)xs[n]=xs[n-255]})(),mi.log=function(t){if(t<1)throw new Error("log("+t+")");return gi[t]},mi.exp=function(t){return xs[t]},mi.mul=function(t,n){return t===0||n===0?0:xs[gi[t]+gi[n]]},function(e){const t=mi;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(rm);const om=rm;function Cu(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Cu.prototype.initialize=function(t){this.degree=t,this.genPoly=om.generateECPolynomial(this.degree)},Cu.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=om.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var tC=Cu,sm={},lr={},$u={};$u.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var xn={};const am="[0-9]+",nC="[A-Z $%*+\\-./:]+";let Es="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Es=Es.replace(/u/g,"\\u");const rC="(?:(?![A-Z0-9 $%*+\\-./:]|"+Es+`)(?:.|[\r
44
+ ]))+`;xn.KANJI=new RegExp(Es,"g"),xn.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),xn.BYTE=new RegExp(rC,"g"),xn.NUMERIC=new RegExp(am,"g"),xn.ALPHANUMERIC=new RegExp(nC,"g");const oC=new RegExp("^"+Es+"$"),sC=new RegExp("^"+am+"$"),aC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");xn.testKanji=function(t){return oC.test(t)},xn.testNumeric=function(t){return sC.test(t)},xn.testAlphanumeric=function(t){return aC.test(t)},function(e){const t=$u,n=xn;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return r(s)}catch{return a}}}(lr),function(e){const t=Lt,n=pi,r=di,o=lr,s=$u,a=7973,i=t.getBCHDigit(a);function l(y,f,g){for(let v=1;v<=40;v++)if(f<=e.getCapacity(v,g,y))return v}function c(y,f){return o.getCharCountIndicator(y,f)+4}function u(y,f){let g=0;return y.forEach(function(v){const m=c(v.mode,f);g+=m+v.getBitsLength()}),g}function h(y,f){for(let g=1;g<=40;g++)if(u(y,g)<=e.getCapacity(g,f,o.MIXED))return g}e.from=function(f,g){return s.isValid(f)?parseInt(f,10):g},e.getCapacity=function(f,g,v){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const m=t.getSymbolTotalCodewords(f),d=n.getTotalCodewordsCount(f,g),w=(m-d)*8;if(v===o.MIXED)return w;const _=w-c(v,f);switch(v){case o.NUMERIC:return Math.floor(_/10*3);case o.ALPHANUMERIC:return Math.floor(_/11*2);case o.KANJI:return Math.floor(_/13);case o.BYTE:default:return Math.floor(_/8)}},e.getBestVersionForData=function(f,g){let v;const m=r.from(g,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,m);if(f.length===0)return 1;v=f[0]}else v=f;return l(v.mode,v.getLength(),m)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-i>=0;)g^=a<<t.getBCHDigit(g)-i;return f<<12|g}}(sm);var im={};const ku=Lt,lm=1335,iC=21522,cm=ku.getBCHDigit(lm);im.getEncodedBits=function(t,n){const r=t.bit<<3|n;let o=r<<10;for(;ku.getBCHDigit(o)-cm>=0;)o^=lm<<ku.getBCHDigit(o)-cm;return(r<<10|o)^iC};var um={};const lC=lr;function mo(e){this.mode=lC.NUMERIC,this.data=e.toString()}mo.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},mo.prototype.getLength=function(){return this.data.length},mo.prototype.getBitsLength=function(){return mo.getBitsLength(this.data.length)},mo.prototype.write=function(t){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),t.put(o,10);const s=this.data.length-n;s>0&&(r=this.data.substr(n),o=parseInt(r,10),t.put(o,s*3+1))};var cC=mo;const uC=lr,Tu=["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 go(e){this.mode=uC.ALPHANUMERIC,this.data=e}go.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)},go.prototype.getLength=function(){return this.data.length},go.prototype.getBitsLength=function(){return go.getBitsLength(this.data.length)},go.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Tu.indexOf(this.data[n])*45;r+=Tu.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(Tu.indexOf(this.data[n]),6)};var dC=go;const pC=lr;function yo(e){this.mode=pC.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}yo.getBitsLength=function(t){return t*8},yo.prototype.getLength=function(){return this.data.length},yo.prototype.getBitsLength=function(){return yo.getBitsLength(this.data.length)},yo.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)};var fC=yo;const hC=lr,mC=Lt;function vo(e){this.mode=hC.KANJI,this.data=e}vo.getBitsLength=function(t){return t*13},vo.prototype.getLength=function(){return this.data.length},vo.prototype.getBitsLength=function(){return vo.getBitsLength(this.data.length)},vo.prototype.write=function(e){let t;for(t=0;t<this.data.length;t++){let n=mC.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+`
45
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};var gC=vo,dm={exports:{}};(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},a={};a[r]=0;var i=t.PriorityQueue.make();i.push(r,0);for(var l,c,u,h,y,f,g,v,m;!i.empty();){l=i.pop(),c=l.value,h=l.cost,y=n[c]||{};for(u in y)y.hasOwnProperty(u)&&(f=y[u],g=h+f,v=a[u],m=typeof a[u]>"u",(m||v>g)&&(a[u]=g,i.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var d=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(d)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(dm);var yC=dm.exports;(function(e){const t=lr,n=cC,r=dC,o=fC,s=gC,a=xn,i=Lt,l=yC;function c(d){return unescape(encodeURIComponent(d)).length}function u(d,w,_){const b=[];let T;for(;(T=d.exec(_))!==null;)b.push({data:T[0],index:T.index,mode:w,length:T[0].length});return b}function h(d){const w=u(a.NUMERIC,t.NUMERIC,d),_=u(a.ALPHANUMERIC,t.ALPHANUMERIC,d);let b,T;return i.isKanjiModeEnabled()?(b=u(a.BYTE,t.BYTE,d),T=u(a.KANJI,t.KANJI,d)):(b=u(a.BYTE_KANJI,t.BYTE,d),T=[]),w.concat(_,b,T).sort(function(E,Z){return E.index-Z.index}).map(function(E){return{data:E.data,mode:E.mode,length:E.length}})}function y(d,w){switch(w){case t.NUMERIC:return n.getBitsLength(d);case t.ALPHANUMERIC:return r.getBitsLength(d);case t.KANJI:return s.getBitsLength(d);case t.BYTE:return o.getBitsLength(d)}}function f(d){return d.reduce(function(w,_){const b=w.length-1>=0?w[w.length-1]:null;return b&&b.mode===_.mode?(w[w.length-1].data+=_.data,w):(w.push(_),w)},[])}function g(d){const w=[];for(let _=0;_<d.length;_++){const b=d[_];switch(b.mode){case t.NUMERIC:w.push([b,{data:b.data,mode:t.ALPHANUMERIC,length:b.length},{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.ALPHANUMERIC:w.push([b,{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.KANJI:w.push([b,{data:b.data,mode:t.BYTE,length:c(b.data)}]);break;case t.BYTE:w.push([{data:b.data,mode:t.BYTE,length:c(b.data)}])}}return w}function v(d,w){const _={},b={start:{}};let T=["start"];for(let P=0;P<d.length;P++){const E=d[P],Z=[];for(let U=0;U<E.length;U++){const W=E[U],V=""+P+U;Z.push(V),_[V]={node:W,lastCount:0},b[V]={};for(let B=0;B<T.length;B++){const J=T[B];_[J]&&_[J].node.mode===W.mode?(b[J][V]=y(_[J].lastCount+W.length,W.mode)-y(_[J].lastCount,W.mode),_[J].lastCount+=W.length):(_[J]&&(_[J].lastCount=W.length),b[J][V]=y(W.length,W.mode)+4+t.getCharCountIndicator(W.mode,w))}}T=Z}for(let P=0;P<T.length;P++)b[T[P]].end=0;return{map:b,table:_}}function m(d,w){let _;const b=t.getBestModeForData(d);if(_=t.from(w,b),_!==t.BYTE&&_.bit<b.bit)throw new Error('"'+d+'" cannot be encoded with mode '+t.toString(_)+`.
46
+ Suggested mode is: `+t.toString(b));switch(_===t.KANJI&&!i.isKanjiModeEnabled()&&(_=t.BYTE),_){case t.NUMERIC:return new n(d);case t.ALPHANUMERIC:return new r(d);case t.KANJI:return new s(d);case t.BYTE:return new o(d)}}e.fromArray=function(w){return w.reduce(function(_,b){return typeof b=="string"?_.push(m(b,null)):b.data&&_.push(m(b.data,b.mode)),_},[])},e.fromString=function(w,_){const b=h(w,i.isKanjiModeEnabled()),T=g(b),P=v(T,_),E=l.find_path(P.map,"start","end"),Z=[];for(let U=1;U<E.length-1;U++)Z.push(P.table[E[U]].node);return e.fromArray(f(Z))},e.rawSplit=function(w){return e.fromArray(h(w,i.isKanjiModeEnabled()))}})(um);const yi=Lt,xu=di,vC=Q8,_C=X8,wC=X0,bC=em,Eu=nm,Iu=pi,SC=tC,vi=sm,CC=im,$C=lr,Pu=um;function kC(e,t){const n=e.size,r=bC.getPositions(t);for(let o=0;o<r.length;o++){const s=r[o][0],a=r[o][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||n<=s+i))for(let l=-1;l<=7;l++)a+l<=-1||n<=a+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?e.set(s+i,a+l,!0,!0):e.set(s+i,a+l,!1,!0))}}function TC(e){const t=e.size;for(let n=8;n<t-8;n++){const r=n%2===0;e.set(n,6,r,!0),e.set(6,n,r,!0)}}function xC(e,t){const n=wC.getPositions(t);for(let r=0;r<n.length;r++){const o=n[r][0],s=n[r][1];for(let a=-2;a<=2;a++)for(let i=-2;i<=2;i++)a===-2||a===2||i===-2||i===2||a===0&&i===0?e.set(o+a,s+i,!0,!0):e.set(o+a,s+i,!1,!0)}}function EC(e,t){const n=e.size,r=vi.getEncodedBits(t);let o,s,a;for(let i=0;i<18;i++)o=Math.floor(i/3),s=i%3+n-8-3,a=(r>>i&1)===1,e.set(o,s,a,!0),e.set(s,o,a,!0)}function Ru(e,t,n){const r=e.size,o=CC.getEncodedBits(t,n);let s,a;for(s=0;s<15;s++)a=(o>>s&1)===1,s<6?e.set(s,8,a,!0):s<8?e.set(s+1,8,a,!0):e.set(r-15+s,8,a,!0),s<8?e.set(8,r-s-1,a,!0):s<9?e.set(8,15-s-1+1,a,!0):e.set(8,15-s-1,a,!0);e.set(r-8,8,1,!0)}function IC(e,t){const n=e.size;let r=-1,o=n-1,s=7,a=0;for(let i=n-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!e.isReserved(o,i-l)){let c=!1;a<t.length&&(c=(t[a]>>>s&1)===1),e.set(o,i-l,c),s--,s===-1&&(a++,s=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function PC(e,t,n){const r=new vC;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),$C.getCharCountIndicator(l.mode,e)),l.write(r)});const o=yi.getSymbolTotalCodewords(e),s=Iu.getTotalCodewordsCount(e,t),a=(o-s)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const i=(a-r.getLengthInBits())/8;for(let l=0;l<i;l++)r.put(l%2?17:236,8);return RC(r,e,t)}function RC(e,t,n){const r=yi.getSymbolTotalCodewords(t),o=Iu.getTotalCodewordsCount(t,n),s=r-o,a=Iu.getBlocksCount(t,n),i=r%a,l=a-i,c=Math.floor(r/a),u=Math.floor(s/a),h=u+1,y=c-u,f=new SC(y);let g=0;const v=new Array(a),m=new Array(a);let d=0;const w=new Uint8Array(e.buffer);for(let E=0;E<a;E++){const Z=E<l?u:h;v[E]=w.slice(g,g+Z),m[E]=f.encode(v[E]),g+=Z,d=Math.max(d,Z)}const _=new Uint8Array(r);let b=0,T,P;for(T=0;T<d;T++)for(P=0;P<a;P++)T<v[P].length&&(_[b++]=v[P][T]);for(T=0;T<y;T++)for(P=0;P<a;P++)_[b++]=m[P][T];return _}function OC(e,t,n,r){let o;if(Array.isArray(e))o=Pu.fromArray(e);else if(typeof e=="string"){let c=t;if(!c){const u=Pu.rawSplit(e);c=vi.getBestVersionForData(u,n)}o=Pu.fromString(e,c||40)}else throw new Error("Invalid data");const s=vi.getBestVersionForData(o,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!t)t=s;else if(t<s)throw new Error(`
20
47
  The chosen QR Code version cannot contain this amount of data.
21
48
  Minimum version required to store current data is: `+s+`.
22
- `);const o=zT(e,r,n),i=Xi.getSymbolSize(e),l=new IT(i);return AT(l,e),MT(l),jT(l,e),wd(l,r,0),e>=7&&DT(l,e),LT(l,o),isNaN(a)&&(a=gd.getBestMask(l,wd.bind(null,l,r))),gd.applyMask(a,l),wd(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}hv.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=vd.M,n,s;return typeof r<"u"&&(a=vd.from(r.errorCorrectionLevel,vd.M),n=el.from(r.version),s=gd.from(r.maskPattern),r.toSJISFunc&&Xi.setToSJISFunction(r.toSJISFunc)),qT(e,n,a,s)};var Tv={},bd={};(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 a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),c=Math.floor((o+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let g=0;g<c;g++)for(let d=0;d<c;d++){let m=(g*c+d)*4,v=s.color.light;if(g>=u&&d>=u&&g<c-u&&d<c-u){const h=Math.floor((g-u)/l),p=Math.floor((d-u)/l);v=f[i[h*o+p]?1:0]}a[m++]=v.r,a[m++]=v.g,a[m++]=v.b,a[m]=v.a}}})(bd),function(t){const e=bd;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,c=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(c=a()),l=e.getOptions(l);const u=e.getImageWidth(s.modules.size,l),f=c.getContext("2d"),g=f.createImageData(u,u);return e.qrToImageData(g.data,s,l),r(f,c,u),f.putImageData(g,0,0),c},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const c=t.render(s,o,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}}(Tv);var Cv={};const FT=bd;function Rv(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function Ed(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function ZT(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),c=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?Ed("M",l+r,.5+c+r):Ed("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=Ed("h",o),o=0)):n++}return a}Cv.render=function(e,r,a){const n=FT.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Rv(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",c="<path "+Rv(n.color.dark,"stroke")+' d="'+ZT(o,s,n.margin)+'"/>',u='viewBox="0 0 '+i+" "+i+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
23
- `;return typeof a=="function"&&a(null,g),g};const VT=sT,Sd=hv,Ov=Tv,HT=Cv;function $d(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!VT())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,c){try{const u=Sd.create(r,a);l(t(u,e,a))}catch(u){c(u)}})}try{const l=Sd.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Ha.create=Sd.create,Ha.toCanvas=$d.bind(null,Ov.render),Ha.toDataURL=$d.bind(null,Ov.renderToDataURL),Ha.toString=$d.bind(null,function(t,e,r){return HT.render(t,r)});class Nv{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Ha.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Ha.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const BT="https://agent.opentiny.design/tiny-robot",Av="https://ai.opentiny.design/next-remoter",Mv=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
24
- <rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
25
- <rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
26
- <rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
27
- <line x1="9" y1="6" x2="9" y2="18" stroke="currentColor" stroke-width="1.5"/>
28
- <line x1="15" y1="6" x2="15" y2="18" stroke="currentColor" stroke-width="1.5"/>
29
- <line x1="6" y1="9" x2="18" y2="9" stroke="currentColor" stroke-width="1.5"/>
30
- <line x1="6" y1="15" x2="18" y2="15" stroke="currentColor" stroke-width="1.5"/>
31
- <circle cx="12" cy="12" r="1" fill="currentColor"/>
32
- </svg>`},{action:"ai-chat",show:!0,text:"弹出 AI 对话框",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
33
- <path d="M20 2H4C2.9 2 2 2.9 2 4V22L6 18H20C21.1 18 22 17.1 22 16V4C22 2.9 21.1 2 20 2ZM20 16H6L4 18V4H20V16Z" fill="currentColor"/>
34
- <path d="M7 9H17V11H7V9Z" fill="currentColor"/>
35
- <path d="M7 12H14V14H7V12Z" fill="currentColor"/>
36
- </svg>`},{action:"remote-control",show:!0,text:`识别码:${t.sessionId.slice(-6)}`,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
37
- <rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2" fill="none"/>
38
- <rect x="6" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
39
- <rect x="10" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
40
- <rect x="14" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
41
- <rect x="6" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
42
- <rect x="10" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
43
- <rect x="14" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
44
- <rect x="6" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
45
- <rect x="10" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
46
- <rect x="14" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
47
- </svg>`},{action:"remote-url",show:!0,text:`${t.remoteUrl}`,tip:t.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
48
- <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
49
- <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
50
- </svg>`}];class JT{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Av,remoteUrl:e.remoteUrl||BT},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?Mv(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):Mv(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=`
49
+ `);const a=PC(t,n,o),i=yi.getSymbolSize(t),l=new _C(i);return kC(l,t),TC(l),xC(l,t),Ru(l,n,0),t>=7&&EC(l,t),IC(l,a),isNaN(r)&&(r=Eu.getBestMask(l,Ru.bind(null,l,n))),Eu.applyMask(r,l),Ru(l,n,r),{modules:l,version:t,errorCorrectionLevel:n,maskPattern:r,segments:o}}Y0.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=xu.M,o,s;return typeof n<"u"&&(r=xu.from(n.errorCorrectionLevel,xu.M),o=vi.from(n.version),s=Eu.from(n.maskPattern),n.toSJISFunc&&yi.setToSJISFunction(n.toSJISFunc)),OC(t,o,r,s)};var pm={},Ou={};(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,a=r.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},e.getImageWidth=function(r,o){const s=e.getScale(r,o);return Math.floor((r+o.margin*2)*s)},e.qrToImageData=function(r,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,h=[s.color.light,s.color.dark];for(let y=0;y<c;y++)for(let f=0;f<c;f++){let g=(y*c+f)*4,v=s.color.light;if(y>=u&&f>=u&&y<c-u&&f<c-u){const m=Math.floor((y-u)/l),d=Math.floor((f-u)/l);v=h[i[m*a+d]?1:0]}r[g++]=v.r,r[g++]=v.g,r[g++]=v.b,r[g]=v.a}}})(Ou),function(e){const t=Ou;function n(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=r()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),h=c.getContext("2d"),y=h.createImageData(u,u);return t.qrToImageData(y.data,s,l),n(h,c,u),h.putImageData(y,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}}(pm);var fm={};const NC=Ou;function hm(e,t){const n=e.a/255,r=t+'="'+e.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Nu(e,t,n){let r=e+t;return typeof n<"u"&&(r+=" "+n),r}function AC(e,t,n){let r="",o=0,s=!1,a=0;for(let i=0;i<e.length;i++){const l=Math.floor(i%t),c=Math.floor(i/t);!l&&!s&&(s=!0),e[i]?(a++,i>0&&l>0&&e[i-1]||(r+=s?Nu("M",l+n,.5+c+n):Nu("m",o,0),o=0,s=!1),l+1<t&&e[i+1]||(r+=Nu("h",a),a=0)):o++}return r}fm.render=function(t,n,r){const o=NC.getOptions(n),s=t.modules.size,a=t.modules.data,i=s+o.margin*2,l=o.color.light.a?"<path "+hm(o.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",c="<path "+hm(o.color.dark,"stroke")+' d="'+AC(a,s,o.margin)+'"/>',u='viewBox="0 0 '+i+" "+i+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
50
+ `;return typeof r=="function"&&r(null,y),y};const MC=K8,Au=Y0,mm=pm,jC=fm;function Mu(e,t,n,r,o){const s=[].slice.call(arguments,1),a=s.length,i=typeof s[a-1]=="function";if(!i&&!MC())throw new Error("Callback required as last argument");if(i){if(a<2)throw new Error("Too few arguments provided");a===2?(o=n,n=t,t=r=void 0):a===3&&(t.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=t,t=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(n=t,t=r=void 0):a===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(l,c){try{const u=Au.create(n,r);l(e(u,t,r))}catch(u){c(u)}})}try{const l=Au.create(n,r);o(null,e(l,t,r))}catch(l){o(l)}}ho.create=Au.create,ho.toCanvas=Mu.bind(null,mm.render),ho.toDataURL=Mu.bind(null,mm.renderToDataURL),ho.toString=Mu.bind(null,function(e,t,n){return jC.render(e,n)});class gm{constructor(t,{size:n=200,margin:r=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=n,this.margin=r,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return ho.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return ho.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const LC={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class zC{constructor(t,n={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...LC,...n},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(()=>{var t;(t=this.tip)==null||t.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
51
+ <div class="${this.opts.className}__arrow"></div>
52
+ <div class="${this.opts.className}__inner">${t}</div>
53
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const n of t){const r=this.calcStyle(n);if(this.checkViewport(r)){this.applyStyle(r),this.tip.className=`${this.opts.className} ${this.opts.className}--${n}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const n=this.el.getBoundingClientRect(),r=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=n.top+o-r.height-a:i==="bottom"?c=n.bottom+o+a:i==="left"?u=n.left+s-r.width-a:i==="right"&&(u=n.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=n.left+s:l==="end"?u=n.right+s-r.width:u=(n.left+n.right)/2+s-r.width/2),(i==="left"||i==="right")&&(l==="start"?c=n.top+o:l==="end"?c=n.bottom+o-r.height:c=(n.top+n.bottom)/2+o-r.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:n}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${n}px`})}checkViewport({top:t,left:n}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return n>=5&&t>=5&&n+a.width<=o-5&&t+a.height<=s-5}placementList(t){const n={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 n[t.split("-")[0]]||n.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const n=t.composedPath();!n.includes(this.el)&&!n.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(){var t;return!!((t=this.tip)!=null&&t.parentNode)}}const ym="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(ym))return;const e=document.createElement("style");e.id=ym,e.textContent=`
54
+ .tiny-remoter-native-tooltip {
55
+ position: absolute;
56
+ z-index: 9999;
57
+ max-width: 200px;
58
+ padding: 6px 10px;
59
+ font-size: 12px;
60
+ line-height: 1.4;
61
+ color: #fff;
62
+ background: #191919;
63
+ border-radius: 4px;
64
+ pointer-events: none;
65
+ box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
66
+ }
67
+ .tiny-remoter-native-tooltip__arrow {
68
+ position: absolute;
69
+ width: 0; height: 0;
70
+ border: 6px solid transparent;
71
+ }
72
+ .tiny-remoter-native-tooltip--top
73
+ .tiny-remoter-native-tooltip__arrow {
74
+ bottom: -12px;
75
+ left: 50%; transform:
76
+ translateX(-50%);
77
+ border-top-color: rgba(0,0,0,.75);
78
+ }
79
+ .tiny-remoter-native-tooltip--bottom
80
+ .tiny-remoter-native-tooltip__arrow {
81
+ top: -12px;
82
+ left: 50%; transform:
83
+ translateX(-50%);
84
+ border-bottom-color: rgba(0,0,0,.75);
85
+ }
86
+ .tiny-remoter-native-tooltip--left
87
+ .tiny-remoter-native-tooltip__arrow {
88
+ right: -12px;
89
+ top: 50%;
90
+ transform: translateY(-50%);
91
+ border-left-color: rgba(0,0,0,.75);
92
+ }
93
+ .tiny-remoter-native-tooltip--right
94
+ .tiny-remoter-native-tooltip__arrow {
95
+ left: -12px;
96
+ top: 50%;
97
+ transform: translateY(-50%);
98
+ border-right-color: rgba(0,0,0,.75);
99
+ }
100
+ `,document.head.appendChild(e)})();const DC="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",ZC="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",UC="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",qC="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",VC="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",FC="https://agent.opentiny.design/tiny-robot",vm="https://ai.opentiny.design/next-remoter",_m=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:qC},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:DC},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:UC},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:ZC}];class BC{constructor(t){if(this.isExpanded=!1,this.getImageUrl=n=>{if(!n)return;const r=new Image;return r.src=n,r},this.renderItem=()=>{this.menuItems.filter(n=>n.show!==!1).map(n=>{const r=document.getElementById(`tiny-remoter-icon-item-${n.action}`);if(!r)return;r.innerHTML="";const o=this.getImageUrl(n.icon);o&&r.appendChild(o)})},this.readyTips=n=>{const r=document.getElementById(n);r&&new zC(r,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||vm,remoteUrl:t.remoteUrl||FC},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){var t;return(t=this.options.qrCodeUrl)!=null&&t.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?_m(this.options).map(n=>{const r=t.find(o=>o.action===n.action);return r?{...n,...r,show:r.show!==void 0?r.show:n.show}:n}):_m(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
51
101
  <div class="tiny-remoter-floating-block__icon">
52
- <img style="display: block; width: 56px;" src="${Av}/svgs/logo-next-no-bg-left.svg" alt="icon" />
102
+ <img style="display: block; width: 56px;" src="${vm}/svgs/logo-next-no-bg-left.svg" alt="icon" />
53
103
  </div>
54
- `,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=>`
55
- <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
56
- <div class="tiny-remoter-dropdown-item__icon">
57
- ${r.icon}
104
+ `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(n=>n.show!==!1).map(n=>`
105
+ <div class="tiny-remoter-dropdown-item" data-action="${n.action}">
106
+ <div id="tiny-remoter-icon-item-${n.action}" class="tiny-remoter-dropdown-item__icon">
58
107
  </div>
59
- <span title="${r.tip}">${r.text}</span>
60
- ${r.showCopyIcon?`
61
- <div class="tiny-remoter-copy-icon" data-action="${r.action}">
62
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
63
- <path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/>
64
- </svg>
108
+ <div class="tiny-remoter-dropdown-item__content">
109
+ <div title="${n.tip}">${n.text}</div>
110
+ <div class="tiny-remoter-dropdown-item__desc-wrapper">
111
+ <div class="tiny-remoter-dropdown-item__desc ${n.active?"tiny-remoter-dropdown-item__desc--active":""} ${n.know?"tiny-remoter-dropdown-item__desc--know":""}">${n.desc}</div>
112
+ <div>
113
+ ${n.showCopyIcon?`
114
+ <div class="tiny-remoter-copy-icon" id="${n.action}" data-action="${n.action}">
115
+ <img src="${VC}"/>
116
+ </div>
117
+ `:""}
118
+ </div>
65
119
  </div>
66
- `:""}
120
+ </div>
67
121
  </div>
68
- `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),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 a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Nv((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
122
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const n=t.target,r=n.closest(".tiny-remoter-copy-icon");if(r){t.stopPropagation();const a=r.dataset.action;a&&this.handleAction(a);return}const o=n.closest(".tiny-remoter-dropdown-item"),s=o==null?void 0:o.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const n=t.target;!this.floatingBlock.contains(n)&&!this.dropdownMenu.contains(n)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.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(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-999999px",n.style.top="-999999px",document.body.appendChild(n),n.focus(),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(n){console.error("复制失败:",n),this.showCopyFeedback(!1)}}showCopyFeedback(t){const n=t?"复制成功!":"复制失败,请手动复制",r=document.createElement("div");r.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,r.textContent=n,document.body.appendChild(r),setTimeout(()=>r.classList.add("show"),10),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},300)},1500)}async showQRCode(){const n=await new gm((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),r=this.createModal("扫码前往智能遥控器",`
69
123
  <div style="text-align: center; padding: 32px;">
70
124
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
71
125
  <div style="
@@ -103,7 +157,7 @@ Minimum version required to store current data is: `+s+`.
103
157
  position: relative;
104
158
  z-index: 1;
105
159
  ">
106
- <img src="${r}" alt="二维码" style="
160
+ <img src="${n}" alt="二维码" style="
107
161
  width: 100%;
108
162
  height: 100%;
109
163
  object-fit: contain;
@@ -146,18 +200,18 @@ Minimum version required to store current data is: `+s+`.
146
200
  <span>支持微信、浏览器等多种方式</span>
147
201
  </div>
148
202
  </div>
149
- `);this.showModal(a)}showAIChat(){var e,r;(r=(e=this.options).onShowAIChat)==null||r.call(e)}createModal(e,r){const a=document.createElement("div");a.className="tiny-remoter-floating-modal",a.innerHTML=`
203
+ `);this.showModal(r)}showAIChat(){var t,n;(n=(t=this.options).onShowAIChat)==null||n.call(t)}createModal(t,n){const r=document.createElement("div");r.className="tiny-remoter-floating-modal",r.innerHTML=`
150
204
  <div class="tiny-remoter-modal-overlay"></div>
151
205
  <div class="tiny-remoter-modal-content">
152
206
  <div class="tiny-remoter-modal-header">
153
- <h3>${e}</h3>
207
+ <h3>${t}</h3>
154
208
  <button class="tiny-remoter-modal-close">&times;</button>
155
209
  </div>
156
210
  <div class="tiny-remoter-modal-body">
157
- ${r}
211
+ ${n}
158
212
  </div>
159
213
  </div>
160
- `;const n=a.querySelector(".tiny-remoter-modal-close"),s=a.querySelector(".tiny-remoter-modal-overlay");return n.addEventListener("click",()=>this.hideModal(a)),s.addEventListener("click",()=>this.hideModal(a)),a}showModal(e){document.body.appendChild(e),setTimeout(()=>e.classList.add("show"),10)}hideModal(e){e.classList.remove("show"),setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},100)}addStyles(){const e=document.createElement("style");e.textContent=`
214
+ `;const o=r.querySelector(".tiny-remoter-modal-close"),s=r.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(r)),s.addEventListener("click",()=>this.hideModal(r)),r}showModal(t){document.body.appendChild(t),setTimeout(()=>t.classList.add("show"),10)}hideModal(t){t.classList.remove("show"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},100)}addStyles(){const t=document.createElement("style");t.textContent=`
161
215
  /* 浮动块样式 */
162
216
  .tiny-remoter-floating-block {
163
217
  position: fixed;
@@ -195,15 +249,17 @@ Minimum version required to store current data is: `+s+`.
195
249
  bottom: 100px;
196
250
  right: 30px;
197
251
  background: white;
198
- border-radius: 16px;
252
+ border-radius: 18px;
199
253
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
200
- padding: 8px;
254
+ padding: 24px 24px 0px 24px;
201
255
  opacity: 0;
202
256
  visibility: hidden;
203
257
  transform: translateY(20px) scale(0.95);
204
258
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
205
259
  z-index: 999;
206
260
  min-width: 200px;
261
+ width: 223px;
262
+ height: auto;
207
263
  }
208
264
 
209
265
  .tiny-remoter-floating-dropdown.show {
@@ -215,12 +271,16 @@ Minimum version required to store current data is: `+s+`.
215
271
  .tiny-remoter-dropdown-item {
216
272
  display: flex;
217
273
  align-items: center;
218
- gap: 12px;
219
- padding: 12px 16px;
220
274
  border-radius: 12px;
221
275
  cursor: pointer;
222
276
  transition: all 0.2s ease;
223
277
  color: #333;
278
+ margin-bottom: 24px;
279
+ height: 40px;
280
+ }
281
+
282
+ .tiny-remoter-dropdown-item:last-child {
283
+ margin-bottom: 32px;
224
284
  }
225
285
 
226
286
  .tiny-remoter-dropdown-item > span {
@@ -231,22 +291,48 @@ Minimum version required to store current data is: `+s+`.
231
291
  white-space: nowrap;
232
292
  }
233
293
 
234
- .tiny-remoter-dropdown-item:hover {
235
- background: #f8f9fa;
236
- transform: translateX(4px);
237
- }
238
-
239
294
  .tiny-remoter-dropdown-item__icon {
240
295
  display: flex;
241
296
  align-items: center;
242
297
  justify-content: center;
243
- width: 32px;
244
- height: 32px;
298
+ width: 40px;
299
+ height: 40px;
245
300
  background: #f8f9fa;
246
301
  border-radius: 8px;
247
302
  color: #667eea;
248
303
  }
249
304
 
305
+ .tiny-remoter-dropdown-item__content {
306
+ flex: 1;
307
+ display: flex;
308
+ flex-direction: column;
309
+ gap: 4px;
310
+ overflow: hidden;
311
+ font-size: 12px;
312
+ margin-left: 16px;
313
+ }
314
+
315
+ .tiny-remoter-dropdown-item__desc-wrapper {
316
+ display: flex;
317
+ align-items: center;
318
+ gap: 4px;
319
+ }
320
+
321
+ .tiny-remoter-dropdown-item__desc {
322
+ color: #808080;
323
+ overflow: hidden;
324
+ white-space: nowrap;
325
+ text-overflow: ellipsis;
326
+ }
327
+
328
+ .tiny-remoter-dropdown-item__desc--active {
329
+ color: #1476ff;
330
+ }
331
+
332
+ .tiny-remoter-dropdown-item__desc--know {
333
+ color: #191919;
334
+ }
335
+
250
336
  /* 复制图标样式 */
251
337
  .tiny-remoter-copy-icon {
252
338
  display: flex;
@@ -435,13 +521,6 @@ Minimum version required to store current data is: `+s+`.
435
521
  color: white;
436
522
  }
437
523
 
438
- .tiny-remoter-dropdown-item:hover {
439
- background: #2a2a2a;
440
- }
441
-
442
- .tiny-remoter-dropdown-item__icon {
443
- background: #2a2a2a;
444
- }
445
524
 
446
525
  .tiny-remoter-copy-icon {
447
526
  background: #2a2a2a;
@@ -466,66 +545,43 @@ Minimum version required to store current data is: `+s+`.
466
545
  color: white;
467
546
  }
468
547
  }
469
- `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const GT=(t={})=>new JT(t);var jv="vercel.ai.error",KT=Symbol.for(jv),Dv,WT=class aw extends Error{constructor({name:e,message:r,cause:a}){super(r),this[Dv]=!0,this.name=e,this.cause=a}static isInstance(e){return aw.hasMarker(e,jv)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};Dv=KT;var Pe=WT,Lv="AI_APICallError",zv=`vercel.ai.error.${Lv}`,QT=Symbol.for(zv),Uv,Nt=class extends Pe{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:Lv,message:t,cause:o}),this[Uv]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return Pe.hasMarker(t,zv)}};Uv=QT;var qv="AI_EmptyResponseBodyError",Fv=`vercel.ai.error.${qv}`,YT=Symbol.for(Fv),Zv,XT=class extends Pe{constructor({message:t="Empty response body"}={}){super({name:qv,message:t}),this[Zv]=!0}static isInstance(t){return Pe.hasMarker(t,Fv)}};Zv=YT;function Wa(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Vv="AI_InvalidArgumentError",Hv=`vercel.ai.error.${Vv}`,eC=Symbol.for(Hv),Bv,Jv=class extends Pe{constructor({message:e,cause:r,argument:a}){super({name:Vv,message:e,cause:r}),this[Bv]=!0,this.argument=a}static isInstance(e){return Pe.hasMarker(e,Hv)}};Bv=eC;var Gv="AI_InvalidPromptError",Kv=`vercel.ai.error.${Gv}`,tC=Symbol.for(Kv),Wv,ea=class extends Pe{constructor({prompt:t,message:e,cause:r}){super({name:Gv,message:`Invalid prompt: ${e}`,cause:r}),this[Wv]=!0,this.prompt=t}static isInstance(t){return Pe.hasMarker(t,Kv)}};Wv=tC;var Qv="AI_InvalidResponseDataError",Yv=`vercel.ai.error.${Qv}`,rC=Symbol.for(Yv),Xv,Xs=class extends Pe{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Qv,message:e}),this[Xv]=!0,this.data=t}static isInstance(t){return Pe.hasMarker(t,Yv)}};Xv=rC;var eg="AI_JSONParseError",tg=`vercel.ai.error.${eg}`,nC=Symbol.for(tg),rg,tl=class extends Pe{constructor({text:t,cause:e}){super({name:eg,message:`JSON parsing failed: Text: ${t}.
470
- Error message: ${Wa(e)}`,cause:e}),this[rg]=!0,this.text=t}static isInstance(t){return Pe.hasMarker(t,tg)}};rg=nC;var ng="AI_LoadAPIKeyError",ag=`vercel.ai.error.${ng}`,aC=Symbol.for(ag),sg,rl=class extends Pe{constructor({message:t}){super({name:ng,message:t}),this[sg]=!0}static isInstance(t){return Pe.hasMarker(t,ag)}};sg=aC;var og="AI_NoSuchModelError",ig=`vercel.ai.error.${og}`,sC=Symbol.for(ig),lg,Pd=class extends Pe{constructor({errorName:t=og,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[lg]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return Pe.hasMarker(t,ig)}};lg=sC;var cg="AI_TooManyEmbeddingValuesForCallError",ug=`vercel.ai.error.${cg}`,oC=Symbol.for(ug),dg,iC=class extends Pe{constructor(t){super({name:cg,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[dg]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Pe.hasMarker(t,ug)}};dg=oC;var pg="AI_TypeValidationError",fg=`vercel.ai.error.${pg}`,lC=Symbol.for(fg),hg,cC=class Sp extends Pe{constructor({value:e,cause:r}){super({name:pg,message:`Type validation failed: Value: ${JSON.stringify(e)}.
471
- Error message: ${Wa(r)}`,cause:r}),this[hg]=!0,this.value=e}static isInstance(e){return Pe.hasMarker(e,fg)}static wrap({value:e,cause:r}){return Sp.isInstance(r)&&r.value===e?r:new Sp({value:e,cause:r})}};hg=lC;var eo=cC,mg="AI_UnsupportedFunctionalityError",vg=`vercel.ai.error.${mg}`,uC=Symbol.for(vg),gg,Ar=class extends Pe{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:mg,message:e}),this[gg]=!0,this.functionality=t}static isInstance(t){return Pe.hasMarker(t,vg)}};gg=uC;function B(t,e,r){function a(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(t),e(i,l);for(const u in o.prototype)u in i||Object.defineProperty(i,u,{value:o.prototype[u].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const c=r!=null&&r.Parent?new s:this;a(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,c;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(c=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class to extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const yg={};function Mn(t){return yg}function _g(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function dC(t,e){return typeof e=="bigint"?e.toString():e}function kd(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function xd(t){return t==null}function Id(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pC(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function Ge(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function nl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ro(t){return JSON.stringify(t)}const wg=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function al(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const fC=kd(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function sl(t){if(al(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(al(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const hC=new Set(["string","number","symbol"]);function no(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ta(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function fe(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0: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 mC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const vC={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 gC(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return ta(t,{...t._zod.def,shape:r,checks:[]})}function yC(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return ta(t,{...t._zod.def,shape:r,checks:[]})}function _C(t,e){if(!sl(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return nl(this,"shape",a),a},checks:[]};return ta(t,r)}function wC(t,e){return ta(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return nl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function bC(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return ta(e,{...e._zod.def,shape:n,checks:[]})}function EC(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return ta(e,{...e._zod.def,shape:n,checks:[]})}function ao(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function ra(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function ol(t){return typeof t=="string"?t:t==null?void 0:t.message}function jn(t,e,r){var n,s,o,i,l,c;const a={...t,path:t.path??[]};if(!t.message){const u=ol((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??ol((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??ol((l=r.customError)==null?void 0:l.call(r,t))??ol((c=r.localeError)==null?void 0:c.call(r,t))??"Invalid input";a.message=u}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function Td(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function so(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const bg=(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,dC,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Eg=B("$ZodError",bg),Sg=B("$ZodError",bg,{Parent:Error});function SC(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function $C(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(t),a}const PC=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new to;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>jn(l,s,Mn())));throw wg(i,n==null?void 0:n.callee),i}return o.value},kC=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>jn(l,s,Mn())));throw wg(i,n==null?void 0:n.callee),i}return o.value},$g=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new to;return s.issues.length?{success:!1,error:new(t??Eg)(s.issues.map(o=>jn(o,n,Mn())))}:{success:!0,data:s.value}},xC=$g(Sg),Pg=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>jn(o,n,Mn())))}:{success:!0,data:s.value}},IC=Pg(Sg),TC=/^[cC][^\s-]{8,}$/,CC=/^[0-9a-z]+$/,RC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,OC=/^[0-9a-vA-V]{20}$/,NC=/^[A-Za-z0-9]{27}$/,AC=/^[a-zA-Z0-9_-]{21}$/,MC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jC=/^([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})$/,kg=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)$/,DC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,LC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function zC(){return new RegExp(LC,"u")}const UC=/^(?:(?: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])$/,qC=/^(([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})$/,FC=/^((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])$/,ZC=/^(([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])$/,VC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xg=/^[A-Za-z0-9_-]*$/,HC=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,BC=/^\+(?:[0-9]){6,14}[0-9]$/,Ig="(?:(?:\\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])))",JC=new RegExp(`^${Ig}$`);function Tg(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 GC(t){return new RegExp(`^${Tg(t)}$`)}function KC(t){const e=Tg({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Ig}T(?:${a})$`)}const WC=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},QC=/^\d+$/,YC=/^-?\d+(?:\.\d+)?/i,XC=/true|false/i,eR=/null/i,tR=/^[^A-Z]*$/,rR=/^[^a-z]*$/,rr=B("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Cg={number:"number",bigint:"bigint",object:"date"},Rg=B("$ZodCheckLessThan",(t,e)=>{rr.init(t,e);const r=Cg[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Og=B("$ZodCheckGreaterThan",(t,e)=>{rr.init(t,e);const r=Cg[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),nR=B("$ZodCheckMultipleOf",(t,e)=>{rr.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.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):pC(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})}}),aR=B("$ZodCheckNumberFormat",(t,e)=>{var o;rr.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=vC[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=QC)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),sR=B("$ZodCheckMaxLength",(t,e)=>{var r;rr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!xd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=Td(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),oR=B("$ZodCheckMinLength",(t,e)=>{var r;rr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!xd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=Td(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),iR=B("$ZodCheckLengthEquals",(t,e)=>{var r;rr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!xd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=Td(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),il=B("$ZodCheckStringFormat",(t,e)=>{var r,a;rr.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),lR=B("$ZodCheckRegex",(t,e)=>{il.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})}}),cR=B("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=tR),il.init(t,e)}),uR=B("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=rR),il.init(t,e)}),dR=B("$ZodCheckIncludes",(t,e)=>{rr.init(t,e);const r=no(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),pR=B("$ZodCheckStartsWith",(t,e)=>{rr.init(t,e);const r=new RegExp(`^${no(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),fR=B("$ZodCheckEndsWith",(t,e)=>{rr.init(t,e);const r=new RegExp(`.*${no(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),hR=B("$ZodCheckOverwrite",(t,e)=>{rr.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class mR{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 a=e.split(`
472
- `).filter(o=>o),n=Math.min(...a.map(o=>o.length-o.trimStart().length)),s=a.map(o=>o.slice(n)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,n=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
473
- `))}}const vR={major:4,minor:0,patch:0},et=B("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=vR;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let c=ao(o),u;for(const f of i){if(f._zod.def.when){if(!f._zod.def.when(o))continue}else if(c)continue;const g=o.issues.length,d=f._zod.check(o);if(d instanceof Promise&&(l==null?void 0:l.async)===!1)throw new to;if(u||d instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await d,o.issues.length!==g&&(c||(c=ao(o,g)))});else{if(o.issues.length===g)continue;c||(c=ao(o,g))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new to;return l.then(c=>s(c,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=xC(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return IC(t,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Cd=B("$ZodString",(t,e)=>{var r;et.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??WC(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),ct=B("$ZodStringFormat",(t,e)=>{il.init(t,e),Cd.init(t,e)}),gR=B("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jC),ct.init(t,e)}),yR=B("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=kg(a))}else e.pattern??(e.pattern=kg());ct.init(t,e)}),_R=B("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=DC),ct.init(t,e)}),wR=B("$ZodURL",(t,e)=>{ct.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:HC.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),bR=B("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=zC()),ct.init(t,e)}),ER=B("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=AC),ct.init(t,e)}),SR=B("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=TC),ct.init(t,e)}),$R=B("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=CC),ct.init(t,e)}),PR=B("$ZodULID",(t,e)=>{e.pattern??(e.pattern=RC),ct.init(t,e)}),kR=B("$ZodXID",(t,e)=>{e.pattern??(e.pattern=OC),ct.init(t,e)}),xR=B("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=NC),ct.init(t,e)}),IR=B("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=KC(e)),ct.init(t,e)}),TR=B("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=JC),ct.init(t,e)}),CR=B("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=GC(e)),ct.init(t,e)}),RR=B("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=MC),ct.init(t,e)}),OR=B("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=UC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),NR=B("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=qC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.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})}}}),AR=B("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=FC),ct.init(t,e)}),MR=B("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ZC),ct.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Ng(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const jR=B("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=VC),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Ng(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function DR(t){if(!xg.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ng(r)}const LR=B("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xg),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{DR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),zR=B("$ZodE164",(t,e)=>{e.pattern??(e.pattern=BC),ct.init(t,e)});function UR(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const qR=B("$ZodJWT",(t,e)=>{ct.init(t,e),t._zod.check=r=>{UR(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ag=B("$ZodNumber",(t,e)=>{et.init(t,e),t._zod.pattern=t._zod.bag.pattern??YC,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),FR=B("$ZodNumber",(t,e)=>{aR.init(t,e),Ag.init(t,e)}),ZR=B("$ZodBoolean",(t,e)=>{et.init(t,e),t._zod.pattern=XC,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),VR=B("$ZodNull",(t,e)=>{et.init(t,e),t._zod.pattern=eR,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),HR=B("$ZodAny",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),BR=B("$ZodUnknown",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),JR=B("$ZodNever",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Mg(t,e,r){t.issues.length&&e.issues.push(...ra(r,t.issues)),e.value[r]=t.value}const GR=B("$ZodArray",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(c=>Mg(c,r,o))):Mg(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function ll(t,e,r){t.issues.length&&e.issues.push(...ra(r,t.issues)),e.value[r]=t.value}function jg(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ra(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const KR=B("$ZodObject",(t,e)=>{et.init(t,e);const r=kd(()=>{const f=Object.keys(e.shape);for(const d of f)if(!(e.shape[d]instanceof et))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const g=mC(e.shape);return{shape:e.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(g)}});Ge(t._zod,"propValues",()=>{const f=e.shape,g={};for(const d in f){const m=f[d]._zod;if(m.values){g[d]??(g[d]=new Set);for(const v of m.values)g[d].add(v)}}return g});const a=f=>{const g=new mR(["shape","payload","ctx"]),d=r.value,m=_=>{const w=ro(_);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};g.write("const input = payload.value;");const v=Object.create(null);let h=0;for(const _ of d.keys)v[_]=`key_${h++}`;g.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const w=v[_];g.write(`const ${w} = ${m(_)};`);const b=ro(_);g.write(`
474
- if (${w}.issues.length) {
475
- if (input[${b}] === undefined) {
476
- if (${b} in input) {
477
- newResult[${b}] = undefined;
478
- }
479
- } else {
480
- payload.issues = payload.issues.concat(
481
- ${w}.issues.map((iss) => ({
482
- ...iss,
483
- path: iss.path ? [${b}, ...iss.path] : [${b}],
484
- }))
485
- );
486
- }
487
- } else if (${w}.value === undefined) {
488
- if (${b} in input) newResult[${b}] = undefined;
489
- } else {
490
- newResult[${b}] = ${w}.value;
491
- }
492
- `)}else{const w=v[_];g.write(`const ${w} = ${m(_)};`),g.write(`
493
- if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
494
- ...iss,
495
- path: iss.path ? [${ro(_)}, ...iss.path] : [${ro(_)}]
496
- })));`),g.write(`newResult[${ro(_)}] = ${w}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const p=g.compile();return(_,w)=>p(f,_,w)};let n;const s=al,o=!yg.jitless,l=o&&fC.value,c=e.catchall;let u;t._zod.parse=(f,g)=>{u??(u=r.value);const d=f.value;if(!s(d))return f.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),f;const m=[];if(o&&l&&(g==null?void 0:g.async)===!1&&g.jitless!==!0)n||(n=a(e.shape)),f=n(f,g);else{f.value={};const w=u.shape;for(const b of u.keys){const S=w[b],x=S._zod.run({value:d[b],issues:[]},g),k=S._zod.optin==="optional"&&S._zod.optout==="optional";x instanceof Promise?m.push(x.then(A=>k?jg(A,f,b,d):ll(A,f,b))):k?jg(x,f,b,d):ll(x,f,b)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const v=[],h=u.keySet,p=c._zod,_=p.def.type;for(const w of Object.keys(d)){if(h.has(w))continue;if(_==="never"){v.push(w);continue}const b=p.run({value:d[w],issues:[]},g);b instanceof Promise?m.push(b.then(S=>ll(S,f,w))):ll(b,f,w)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:t}),m.length?Promise.all(m).then(()=>f):f}});function Dg(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>jn(s,a,Mn())))}),e}const Lg=B("$ZodUnion",(t,e)=>{et.init(t,e),Ge(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ge(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ge(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ge(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>Id(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>Dg(o,r,t,a)):Dg(s,r,t,a)}}),WR=B("$ZodDiscriminatedUnion",(t,e)=>{Lg.init(t,e);const r=t._zod.parse;Ge(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const c of l)n[i].add(c)}}return n});const a=kd(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!al(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),QR=B("$ZodIntersection",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,c])=>zg(r,l,c)):zg(r,s,o)}});function Rd(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(sl(t)&&sl(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=Rd(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=Rd(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function zg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ao(t))return t;const a=Rd(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const YR=B("$ZodRecord",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!sl(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:n[l],issues:[]},a);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ra(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...ra(l,c.issues)),r.value[l]=c.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>jn(c,a,Mn())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...ra(o,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...ra(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),XR=B("$ZodEnum",(t,e)=>{et.init(t,e);const r=_g(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>hC.has(typeof a)).map(a=>typeof a=="string"?no(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),eO=B("$ZodLiteral",(t,e)=>{et.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?no(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),tO=B("$ZodTransform",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new to;return r.value=n,r}}),rO=B("$ZodOptional",(t,e)=>{et.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ge(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ge(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Id(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),nO=B("$ZodNullable",(t,e)=>{et.init(t,e),Ge(t._zod,"optin",()=>e.innerType._zod.optin),Ge(t._zod,"optout",()=>e.innerType._zod.optout),Ge(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Id(r.source)}|null)$`):void 0}),Ge(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),aO=B("$ZodDefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>Ug(s,e)):Ug(n,e)}});function Ug(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const sO=B("$ZodPrefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),oO=B("$ZodNonOptional",(t,e)=>{et.init(t,e),Ge(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>qg(s,t)):qg(n,t)}});function qg(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 iO=B("$ZodCatch",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"optout",()=>e.innerType._zod.optout),Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>jn(o,a,Mn()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>jn(s,a,Mn()))},input:r.value}),r.issues=[]),r)}}),lO=B("$ZodPipe",(t,e)=>{et.init(t,e),Ge(t._zod,"values",()=>e.in._zod.values),Ge(t._zod,"optin",()=>e.in._zod.optin),Ge(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>Fg(s,e,a)):Fg(n,e,a)}});function Fg(t,e,r){return ao(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const cO=B("$ZodReadonly",(t,e)=>{et.init(t,e),Ge(t._zod,"propValues",()=>e.innerType._zod.propValues),Ge(t._zod,"values",()=>e.innerType._zod.values),Ge(t._zod,"optin",()=>e.innerType._zod.optin),Ge(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(Zg):Zg(n)}});function Zg(t){return t.value=Object.freeze(t.value),t}const uO=B("$ZodLazy",(t,e)=>{et.init(t,e),Ge(t._zod,"innerType",()=>e.getter()),Ge(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Ge(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Ge(t._zod,"optin",()=>t._zod.innerType._zod.optin),Ge(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),dO=B("$ZodCustom",(t,e)=>{rr.init(t,e),et.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>Vg(s,r,a,t));Vg(n,r,a,t)}});function Vg(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(so(n))}}class Hg{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.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 a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function pO(){return new Hg}const oo=pO();function fO(t,e){return new t({type:"string",...fe(e)})}function hO(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...fe(e)})}function Bg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...fe(e)})}function mO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(e)})}function vO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(e)})}function gO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(e)})}function yO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(e)})}function _O(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...fe(e)})}function wO(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(e)})}function bO(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(e)})}function EO(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(e)})}function SO(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(e)})}function $O(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(e)})}function PO(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...fe(e)})}function kO(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(e)})}function xO(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(e)})}function IO(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(e)})}function TO(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(e)})}function CO(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(e)})}function Jg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...fe(e)})}function RO(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(e)})}function OO(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...fe(e)})}function NO(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(e)})}function AO(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(e)})}function MO(t,e){return new t({type:"string",format:"date",check:"string_format",...fe(e)})}function jO(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...fe(e)})}function DO(t,e){return new t({type:"string",format:"duration",check:"string_format",...fe(e)})}function LO(t,e){return new t({type:"number",checks:[],...fe(e)})}function zO(t,e){return new t({type:"number",coerce:!0,checks:[],...fe(e)})}function UO(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(e)})}function qO(t,e){return new t({type:"boolean",...fe(e)})}function FO(t,e){return new t({type:"null",...fe(e)})}function ZO(t){return new t({type:"any"})}function VO(t){return new t({type:"unknown"})}function HO(t,e){return new t({type:"never",...fe(e)})}function Gg(t,e){return new Rg({check:"less_than",...fe(e),value:t,inclusive:!1})}function Od(t,e){return new Rg({check:"less_than",...fe(e),value:t,inclusive:!0})}function Kg(t,e){return new Og({check:"greater_than",...fe(e),value:t,inclusive:!1})}function Nd(t,e){return new Og({check:"greater_than",...fe(e),value:t,inclusive:!0})}function Wg(t,e){return new nR({check:"multiple_of",...fe(e),value:t})}function Qg(t,e){return new sR({check:"max_length",...fe(e),maximum:t})}function cl(t,e){return new oR({check:"min_length",...fe(e),minimum:t})}function Yg(t,e){return new iR({check:"length_equals",...fe(e),length:t})}function BO(t,e){return new lR({check:"string_format",format:"regex",...fe(e),pattern:t})}function JO(t){return new cR({check:"string_format",format:"lowercase",...fe(t)})}function GO(t){return new uR({check:"string_format",format:"uppercase",...fe(t)})}function KO(t,e){return new dR({check:"string_format",format:"includes",...fe(e),includes:t})}function WO(t,e){return new pR({check:"string_format",format:"starts_with",...fe(e),prefix:t})}function QO(t,e){return new fR({check:"string_format",format:"ends_with",...fe(e),suffix:t})}function io(t){return new hR({check:"overwrite",tx:t})}function YO(t){return io(e=>e.normalize(t))}function XO(){return io(t=>t.trim())}function e2(){return io(t=>t.toLowerCase())}function t2(){return io(t=>t.toUpperCase())}function r2(t,e,r){return new t({type:"array",element:e,...fe(r)})}function n2(t,e,r){const a=fe(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function a2(t,e,r){return new t({type:"custom",check:"custom",fn:e,...fe(r)})}class Xg{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??oo,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var f,g,d;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(g=(f=e._zod).toJSONSchema)==null?void 0:g.call(f);if(l)i.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,e],path:r.path},v=e._zod.parent;if(v)i.ref=v,this.process(v,m),this.seen.get(v).isParent=!0;else{const h=i.schema;switch(n.type){case"string":{const p=h;p.type="string";const{minimum:_,maximum:w,format:b,patterns:S,contentEncoding:x}=e._zod.bag;if(typeof _=="number"&&(p.minLength=_),typeof w=="number"&&(p.maxLength=w),b&&(p.format=s[b]??b,p.format===""&&delete p.format),x&&(p.contentEncoding=x),S&&S.size>0){const k=[...S];k.length===1?p.pattern=k[0].source:k.length>1&&(i.schema.allOf=[...k.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{const p=h,{minimum:_,maximum:w,format:b,multipleOf:S,exclusiveMaximum:x,exclusiveMinimum:k}=e._zod.bag;typeof b=="string"&&b.includes("int")?p.type="integer":p.type="number",typeof k=="number"&&(p.exclusiveMinimum=k),typeof _=="number"&&(p.minimum=_,typeof k=="number"&&(k>=_?delete p.minimum:delete p.exclusiveMinimum)),typeof x=="number"&&(p.exclusiveMaximum=x),typeof w=="number"&&(p.maximum=w,typeof x=="number"&&(x<=w?delete p.maximum:delete p.exclusiveMaximum)),typeof S=="number"&&(p.multipleOf=S);break}case"boolean":{const p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=h,{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(p.minItems=_),typeof w=="number"&&(p.maxItems=w),p.type="array",p.items=this.process(n.element,{...m,path:[...m.path,"items"]});break}case"object":{const p=h;p.type="object",p.properties={};const _=n.shape;for(const S in _)p.properties[S]=this.process(_[S],{...m,path:[...m.path,"properties",S]});const w=new Set(Object.keys(_)),b=new Set([...w].filter(S=>{const x=n.shape[S]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));b.size>0&&(p.required=Array.from(b)),((d=n.catchall)==null?void 0:d._zod.def.type)==="never"?p.additionalProperties=!1:n.catchall?n.catchall&&(p.additionalProperties=this.process(n.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=h;p.anyOf=n.options.map((_,w)=>this.process(_,{...m,path:[...m.path,"anyOf",w]}));break}case"intersection":{const p=h,_=this.process(n.left,{...m,path:[...m.path,"allOf",0]}),w=this.process(n.right,{...m,path:[...m.path,"allOf",1]}),b=x=>"allOf"in x&&Object.keys(x).length===1,S=[...b(_)?_.allOf:[_],...b(w)?w.allOf:[w]];p.allOf=S;break}case"tuple":{const p=h;p.type="array";const _=n.items.map((S,x)=>this.process(S,{...m,path:[...m.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=_:p.items=_,n.rest){const S=this.process(n.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?p.items=S:p.additionalItems=S}n.rest&&(p.items=this.process(n.rest,{...m,path:[...m.path,"items"]}));const{minimum:w,maximum:b}=e._zod.bag;typeof w=="number"&&(p.minItems=w),typeof b=="number"&&(p.maxItems=b);break}case"record":{const p=h;p.type="object",p.propertyNames=this.process(n.keyType,{...m,path:[...m.path,"propertyNames"]}),p.additionalProperties=this.process(n.valueType,{...m,path:[...m.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 p=h,_=_g(n.entries);_.every(w=>typeof w=="number")&&(p.type="number"),_.every(w=>typeof w=="string")&&(p.type="string"),p.enum=_;break}case"literal":{const p=h,_=[];for(const w of n.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(w))}else _.push(w);if(_.length!==0)if(_.length===1){const w=_[0];p.type=w===null?"null":typeof w,p.const=w}else _.every(w=>typeof w=="number")&&(p.type="number"),_.every(w=>typeof w=="string")&&(p.type="string"),_.every(w=>typeof w=="boolean")&&(p.type="string"),_.every(w=>w===null)&&(p.type="null"),p.enum=_;break}case"file":{const p=h,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:b,mime:S}=e._zod.bag;w!==void 0&&(_.minLength=w),b!==void 0&&(_.maxLength=b),S?S.length===1?(_.contentMediaType=S[0],Object.assign(p,_)):p.anyOf=S.map(x=>({..._,contentMediaType:x})):Object.assign(p,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(n.innerType,m);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,m),i.ref=n.innerType;break}case"success":{const p=h;p.type="boolean";break}case"default":{this.process(n.innerType,m),i.ref=n.innerType,h.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,m),i.ref=n.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,m),i.ref=n.innerType;let p;try{p=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=h,_=e._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=_.source;break}case"pipe":{const p=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(p,m),i.ref=p;break}case"readonly":{this.process(n.innerType,m),i.ref=n.innerType,h.readOnly=!0;break}case"promise":{this.process(n.innerType,m),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,m),i.ref=n.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,m),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),this.io==="input"&&Rt(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var u,f,g,d,m,v;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=h=>{var S;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const x=(S=a.external.registry.get(h[0]))==null?void 0:S.id,k=a.external.uri??(O=>O);if(x)return{ref:k(x)};const A=h[1].defId??h[1].schema.id??`schema${this.counter++}`;return h[1].defId=A,{defId:A,ref:`${k("__shared")}#/${p}/${A}`}}if(h[1]===n)return{ref:"#"};const w=`#/${p}/`,b=h[1].schema.id??`__schema${this.counter++}`;return{defId:b,ref:w+b}},o=h=>{if(h[1].schema.$ref)return;const p=h[1],{ref:_,defId:w}=s(h);p.def={...p.schema},w&&(p.defId=w);const b=p.schema;for(const S in b)delete b[S];b.$ref=_};if(a.cycles==="throw")for(const h of this.seen.entries()){const p=h[1];if(p.cycle)throw new Error(`Cycle detected: #/${(u=p.cycle)==null?void 0:u.join("/")}/<root>
497
-
498
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const h of this.seen.entries()){const p=h[1];if(e===h[0]){o(h);continue}if(a.external){const w=(f=a.external.registry.get(h[0]))==null?void 0:f.id;if(e!==h[0]&&w){o(h);continue}}if((g=this.metadataRegistry.get(h[0]))==null?void 0:g.id){o(h);continue}if(p.cycle){o(h);continue}if(p.count>1&&a.reused==="ref"){o(h);continue}}const i=(h,p)=>{const _=this.seen.get(h),w=_.def??_.schema,b={...w};if(_.ref===null)return;const S=_.ref;if(_.ref=null,S){i(S,p);const x=this.seen.get(S).schema;x.$ref&&p.target==="draft-7"?(w.allOf=w.allOf??[],w.allOf.push(x)):(Object.assign(w,x),Object.assign(w,b))}_.isParent||this.override({zodSchema:h,jsonSchema:w,path:_.path??[]})};for(const h of[...this.seen.entries()].reverse())i(h[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(d=a.external)!=null&&d.uri){const h=(m=a.external.registry.get(e))==null?void 0:m.id;if(!h)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(h)}Object.assign(l,n.def);const c=((v=a.external)==null?void 0:v.defs)??{};for(const h of this.seen.entries()){const p=h[1];p.def&&p.defId&&(c[p.defId]=p.def)}a.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function s2(t,e){if(t instanceof Hg){const a=new Xg(e),n={};for(const i of t._idmap.entries()){const[l,c]=i;a.process(c)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,c]=i;s[l]=a.emit(c,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new Xg(e);return r.process(t),r.emit(t,e)}function Rt(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.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 Rt(n.element,r);case"object":{for(const s in n.shape)if(Rt(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(Rt(s,r))return!0;return!1}case"intersection":return Rt(n.left,r)||Rt(n.right,r);case"tuple":{for(const s of n.items)if(Rt(s,r))return!0;return!!(n.rest&&Rt(n.rest,r))}case"record":return Rt(n.keyType,r)||Rt(n.valueType,r);case"map":return Rt(n.keyType,r)||Rt(n.valueType,r);case"set":return Rt(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Rt(n.innerType,r);case"lazy":return Rt(n.getter(),r);case"default":return Rt(n.innerType,r);case"prefault":return Rt(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Rt(n.in,r)||Rt(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const o2=B("ZodISODateTime",(t,e)=>{IR.init(t,e),ft.init(t,e)});function i2(t){return AO(o2,t)}const l2=B("ZodISODate",(t,e)=>{TR.init(t,e),ft.init(t,e)});function c2(t){return MO(l2,t)}const u2=B("ZodISOTime",(t,e)=>{CR.init(t,e),ft.init(t,e)});function d2(t){return jO(u2,t)}const p2=B("ZodISODuration",(t,e)=>{RR.init(t,e),ft.init(t,e)});function f2(t){return DO(p2,t)}const ul=B("ZodError",(t,e)=>{Eg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>$C(t,r)},flatten:{value:r=>SC(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}),h2=PC(ul),m2=kC(ul),v2=$g(ul),ey=Pg(ul),ot=B("ZodType",(t,e)=>(et.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>ta(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>h2(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>v2(t,r,a),t.parseAsync=async(r,a)=>m2(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>ey(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(uN(r,a)),t.superRefine=r=>t.check(dN(r)),t.overwrite=r=>t.check(io(r)),t.optional=()=>xt(t),t.nullable=()=>cy(t),t.nullish=()=>xt(cy(t)),t.nonoptional=r=>tN(t,r),t.array=()=>oe(t),t.or=r=>He([t,r]),t.and=r=>H2(t,r),t.transform=r=>dy(t,K2(r)),t.default=r=>Y2(t,r),t.prefault=r=>eN(t,r),t.catch=r=>nN(t,r),t.pipe=r=>dy(t,r),t.readonly=()=>oN(t),t.describe=r=>{const a=t.clone();return oo.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=oo.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return oo.get(t);const a=t.clone();return oo.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ty=B("_ZodString",(t,e)=>{Cd.init(t,e),ot.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=(...a)=>t.check(BO(...a)),t.includes=(...a)=>t.check(KO(...a)),t.startsWith=(...a)=>t.check(WO(...a)),t.endsWith=(...a)=>t.check(QO(...a)),t.min=(...a)=>t.check(cl(...a)),t.max=(...a)=>t.check(Qg(...a)),t.length=(...a)=>t.check(Yg(...a)),t.nonempty=(...a)=>t.check(cl(1,...a)),t.lowercase=a=>t.check(JO(a)),t.uppercase=a=>t.check(GO(a)),t.trim=()=>t.check(XO()),t.normalize=(...a)=>t.check(YO(...a)),t.toLowerCase=()=>t.check(e2()),t.toUpperCase=()=>t.check(t2())}),g2=B("ZodString",(t,e)=>{Cd.init(t,e),ty.init(t,e),t.email=r=>t.check(hO(y2,r)),t.url=r=>t.check(_O(_2,r)),t.jwt=r=>t.check(NO(N2,r)),t.emoji=r=>t.check(wO(w2,r)),t.guid=r=>t.check(Bg(ry,r)),t.uuid=r=>t.check(mO(dl,r)),t.uuidv4=r=>t.check(vO(dl,r)),t.uuidv6=r=>t.check(gO(dl,r)),t.uuidv7=r=>t.check(yO(dl,r)),t.nanoid=r=>t.check(bO(b2,r)),t.guid=r=>t.check(Bg(ry,r)),t.cuid=r=>t.check(EO(E2,r)),t.cuid2=r=>t.check(SO(S2,r)),t.ulid=r=>t.check($O($2,r)),t.base64=r=>t.check(Jg(ny,r)),t.base64url=r=>t.check(RO(R2,r)),t.xid=r=>t.check(PO(P2,r)),t.ksuid=r=>t.check(kO(k2,r)),t.ipv4=r=>t.check(xO(x2,r)),t.ipv6=r=>t.check(IO(I2,r)),t.cidrv4=r=>t.check(TO(T2,r)),t.cidrv6=r=>t.check(CO(C2,r)),t.e164=r=>t.check(OO(O2,r)),t.datetime=r=>t.check(i2(r)),t.date=r=>t.check(c2(r)),t.time=r=>t.check(d2(r)),t.duration=r=>t.check(f2(r))});function E(t){return fO(g2,t)}const ft=B("ZodStringFormat",(t,e)=>{ct.init(t,e),ty.init(t,e)}),y2=B("ZodEmail",(t,e)=>{_R.init(t,e),ft.init(t,e)}),ry=B("ZodGUID",(t,e)=>{gR.init(t,e),ft.init(t,e)}),dl=B("ZodUUID",(t,e)=>{yR.init(t,e),ft.init(t,e)}),_2=B("ZodURL",(t,e)=>{wR.init(t,e),ft.init(t,e)}),w2=B("ZodEmoji",(t,e)=>{bR.init(t,e),ft.init(t,e)}),b2=B("ZodNanoID",(t,e)=>{ER.init(t,e),ft.init(t,e)}),E2=B("ZodCUID",(t,e)=>{SR.init(t,e),ft.init(t,e)}),S2=B("ZodCUID2",(t,e)=>{$R.init(t,e),ft.init(t,e)}),$2=B("ZodULID",(t,e)=>{PR.init(t,e),ft.init(t,e)}),P2=B("ZodXID",(t,e)=>{kR.init(t,e),ft.init(t,e)}),k2=B("ZodKSUID",(t,e)=>{xR.init(t,e),ft.init(t,e)}),x2=B("ZodIPv4",(t,e)=>{OR.init(t,e),ft.init(t,e)}),I2=B("ZodIPv6",(t,e)=>{NR.init(t,e),ft.init(t,e)}),T2=B("ZodCIDRv4",(t,e)=>{AR.init(t,e),ft.init(t,e)}),C2=B("ZodCIDRv6",(t,e)=>{MR.init(t,e),ft.init(t,e)}),ny=B("ZodBase64",(t,e)=>{jR.init(t,e),ft.init(t,e)});function ay(t){return Jg(ny,t)}const R2=B("ZodBase64URL",(t,e)=>{LR.init(t,e),ft.init(t,e)}),O2=B("ZodE164",(t,e)=>{zR.init(t,e),ft.init(t,e)}),N2=B("ZodJWT",(t,e)=>{qR.init(t,e),ft.init(t,e)}),Ad=B("ZodNumber",(t,e)=>{Ag.init(t,e),ot.init(t,e),t.gt=(a,n)=>t.check(Kg(a,n)),t.gte=(a,n)=>t.check(Nd(a,n)),t.min=(a,n)=>t.check(Nd(a,n)),t.lt=(a,n)=>t.check(Gg(a,n)),t.lte=(a,n)=>t.check(Od(a,n)),t.max=(a,n)=>t.check(Od(a,n)),t.int=a=>t.check(sy(a)),t.safe=a=>t.check(sy(a)),t.positive=a=>t.check(Kg(0,a)),t.nonnegative=a=>t.check(Nd(0,a)),t.negative=a=>t.check(Gg(0,a)),t.nonpositive=a=>t.check(Od(0,a)),t.multipleOf=(a,n)=>t.check(Wg(a,n)),t.step=(a,n)=>t.check(Wg(a,n)),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 Z(t){return LO(Ad,t)}const A2=B("ZodNumberFormat",(t,e)=>{FR.init(t,e),Ad.init(t,e)});function sy(t){return UO(A2,t)}const M2=B("ZodBoolean",(t,e)=>{ZR.init(t,e),ot.init(t,e)});function Pt(t){return qO(M2,t)}const j2=B("ZodNull",(t,e)=>{VR.init(t,e),ot.init(t,e)});function D2(t){return FO(j2,t)}const L2=B("ZodAny",(t,e)=>{HR.init(t,e),ot.init(t,e)});function _r(){return ZO(L2)}const z2=B("ZodUnknown",(t,e)=>{BR.init(t,e),ot.init(t,e)});function Mr(){return VO(z2)}const U2=B("ZodNever",(t,e)=>{JR.init(t,e),ot.init(t,e)});function q2(t){return HO(U2,t)}const F2=B("ZodArray",(t,e)=>{GR.init(t,e),ot.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(cl(r,a)),t.nonempty=r=>t.check(cl(1,r)),t.max=(r,a)=>t.check(Qg(r,a)),t.length=(r,a)=>t.check(Yg(r,a)),t.unwrap=()=>t.element});function oe(t,e){return r2(F2,t,e)}const oy=B("ZodObject",(t,e)=>{KR.init(t,e),ot.init(t,e),Ge(t,"shape",()=>e.shape),t.keyof=()=>ht(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Mr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Mr()}),t.strict=()=>t.clone({...t._zod.def,catchall:q2()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>_C(t,r),t.merge=r=>wC(t,r),t.pick=r=>gC(t,r),t.omit=r=>yC(t,r),t.partial=(...r)=>bC(ly,t,r[0]),t.required=(...r)=>EC(uy,t,r[0])});function I(t,e){const r={type:"object",get shape(){return nl(this,"shape",{...t}),this.shape},...fe(e)};return new oy(r)}function Qa(t,e){return new oy({type:"object",get shape(){return nl(this,"shape",{...t}),this.shape},catchall:Mr(),...fe(e)})}const iy=B("ZodUnion",(t,e)=>{Lg.init(t,e),ot.init(t,e),t.options=e.options});function He(t,e){return new iy({type:"union",options:t,...fe(e)})}const Z2=B("ZodDiscriminatedUnion",(t,e)=>{iy.init(t,e),WR.init(t,e)});function nr(t,e,r){return new Z2({type:"union",options:e,discriminator:t,...fe(r)})}const V2=B("ZodIntersection",(t,e)=>{QR.init(t,e),ot.init(t,e)});function H2(t,e){return new V2({type:"intersection",left:t,right:e})}const B2=B("ZodRecord",(t,e)=>{YR.init(t,e),ot.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function kt(t,e,r){return new B2({type:"record",keyType:t,valueType:e,...fe(r)})}const Md=B("ZodEnum",(t,e)=>{XR.init(t,e),ot.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Md({...e,checks:[],...fe(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Md({...e,checks:[],...fe(n),entries:s})}});function ht(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new Md({type:"enum",entries:r,...fe(e)})}const J2=B("ZodLiteral",(t,e)=>{eO.init(t,e),ot.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 W(t,e){return new J2({type:"literal",values:Array.isArray(t)?t:[t],...fe(e)})}const G2=B("ZodTransform",(t,e)=>{tO.init(t,e),ot.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(so(s,r.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(so(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function K2(t){return new G2({type:"transform",transform:t})}const ly=B("ZodOptional",(t,e)=>{rO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xt(t){return new ly({type:"optional",innerType:t})}const W2=B("ZodNullable",(t,e)=>{nO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cy(t){return new W2({type:"nullable",innerType:t})}const Q2=B("ZodDefault",(t,e)=>{aO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Y2(t,e){return new Q2({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const X2=B("ZodPrefault",(t,e)=>{sO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function eN(t,e){return new X2({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const uy=B("ZodNonOptional",(t,e)=>{oO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function tN(t,e){return new uy({type:"nonoptional",innerType:t,...fe(e)})}const rN=B("ZodCatch",(t,e)=>{iO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function nN(t,e){return new rN({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const aN=B("ZodPipe",(t,e)=>{lO.init(t,e),ot.init(t,e),t.in=e.in,t.out=e.out});function dy(t,e){return new aN({type:"pipe",in:t,out:e})}const sN=B("ZodReadonly",(t,e)=>{cO.init(t,e),ot.init(t,e)});function oN(t){return new sN({type:"readonly",innerType:t})}const iN=B("ZodLazy",(t,e)=>{uO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.getter()});function py(t){return new iN({type:"lazy",getter:t})}const jd=B("ZodCustom",(t,e)=>{dO.init(t,e),ot.init(t,e)});function lN(t){const e=new rr({check:"custom"});return e._zod.check=t,e}function cN(t,e){return n2(jd,t??(()=>!0),e)}function uN(t,e={}){return a2(jd,t,e)}function dN(t){const e=lN(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(so(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(so(n))}},t(r.value,r)));return e}function pl(t,e={error:`Input not instance of ${t.name}`}){const r=new jd({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...fe(e)});return r._zod.bag.Class=t,r}function pN(t){return zO(Ad,t)}function Gt(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function fN(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(fy());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(fy())};r==null||r.addEventListener("abort",i)})}function fy(){return new DOMException("Delay was aborted","AbortError")}function Ya(t){return Object.fromEntries([...t.headers])}var lo=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new Jv({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},ar=lo();function Dd(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function na(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var hN=["fetch failed","failed to fetch"];function hy({error:t,url:e,requestBodyValues:r}){if(na(t))return t;if(t instanceof TypeError&&hN.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Nt({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function Ld(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function mN(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function aa(t,...e){const r=mN(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var my="3.0.12",vN=()=>globalThis.fetch,vy=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=vN()})=>{try{const o=await s(t,{method:"GET",headers:aa(e,`ai-sdk/provider-utils/${my}`,Ld()),signal:n}),i=Ya(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(c){throw na(c)||Nt.isInstance(c)?c:new Nt({message:"Failed to process error response",cause:c,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(na(l)||Nt.isInstance(l))?l:new Nt({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw hy({error:o,url:t,requestBodyValues:{}})}};function gN({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function gy({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new rl({message:`${a} API key must be a string.`});if(typeof process>"u")throw new rl({message:`${a} 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 rl({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new rl({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function co({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 yN(t){var e;const[r,a=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[a])!=null?e:a}var _N=/"__proto__"\s*:/,wN=/"constructor"\s*:/;function bN(t){const e=JSON.parse(t);return e===null||typeof e!="object"||_N.test(t)===!1&&wN.test(t)===!1?e:EN(e)}function EN(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function zd(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return bN(t)}finally{Error.stackTraceLimit=e}}var fl=Symbol.for("vercel.ai.validator");function SN(t){return{[fl]:!0,validate:t}}function $N(t){return typeof t=="object"&&t!==null&&fl in t&&t[fl]===!0&&"validate"in t}function _t(t){let e;return()=>(e==null&&(e=t()),e)}function PN(t){return $N(t)?t:typeof t=="function"?t():kN(t)}function kN(t){return SN(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new eo({value:e,cause:r.issues})}})}async function en({value:t,schema:e}){const r=await jr({value:t,schema:e});if(!r.success)throw eo.wrap({value:t,cause:r.error});return r.value}async function jr({value:t,schema:e}){const r=PN(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:eo.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:eo.wrap({value:t,cause:a}),rawValue:t}}}async function xN({text:t,schema:e}){try{const r=zd(t);return e==null?r:en({value:r,schema:e})}catch(r){throw tl.isInstance(r)||eo.isInstance(r)?r:new tl({text:t,cause:r})}}async function sa({text:t,schema:e}){try{const r=zd(t);return e==null?{success:!0,value:r,rawValue:r}:await jr({value:r,schema:e})}catch(r){return{success:!1,error:tl.isInstance(r)?r:new tl({text:t,cause:r}),rawValue:void 0}}}function hl(t){try{return zd(t),!0}catch{return!1}}function IN({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Fm).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await sa({text:r,schema:e}))}}))}async function tn({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await jr({value:e[t],schema:r});if(!a.success)throw new Jv({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var TN=()=>globalThis.fetch,sr=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>yy({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),CN=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>yy({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),yy=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=TN()})=>{try{const i=await o(t,{method:"POST",headers:aa(e,`ai-sdk/provider-utils/${my}`,Ld()),body:r.content,signal:s}),l=Ya(i);if(!i.ok){let c;try{c=await n({response:i,url:t,requestBodyValues:r.values})}catch(u){throw na(u)||Nt.isInstance(u)?u:new Nt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(na(c)||Nt.isInstance(c))?c:new Nt({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw hy({error:i,url:t,requestBodyValues:r.values})}};function x3(t){return t}function RN(t){return{...t,type:"dynamic"}}function Xa({id:t,name:e,inputSchema:r,outputSchema:a}){return({execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:t,name:e,args:c,inputSchema:r,outputSchema:a,execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}async function Dn(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var oa=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=Ya(a);if(o.trim()==="")return{responseHeaders:i,value:new Nt({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await xN({text:o,schema:t});return{responseHeaders:i,value:new Nt({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Nt({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},uo=t=>async({response:e})=>{const r=Ya(e);if(e.body==null)throw new XT({});return{responseHeaders:r,value:IN({stream:e.body,schema:t})}},Dr=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await sa({text:n,schema:t}),o=Ya(e);if(!s.success)throw new Nt({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},ON=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=Ya(t);if(!t.body)throw new Nt({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new Nt({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},NN=(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("/")},AN=Symbol("Let zodToJsonSchema decide on which parser to use"),_y={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"},MN=t=>typeof t=="string"?{..._y,name:t}:{..._y,...t};function pr(){return{}}function jN(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==V.ZodAny&&(s.items=We(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function DN(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 LN(){return{type:"boolean"}}function wy(t,e){return We(t.type._def,e)}var zN=(t,e)=>We(t.innerType._def,e);function by(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>by(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return UN(t)}}var UN=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 qN(t,e){return{...We(t.innerType._def,e),default:t.defaultValue()}}function FN(t,e){return e.effectStrategy==="input"?We(t.schema._def,e):pr()}function ZN(t){return{type:"string",enum:Array.from(t.values)}}var VN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function HN(t,e){const r=[We(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),We(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(VN(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function BN(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 Ud=void 0,Lr={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:()=>(Ud===void 0&&(Ud=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ud),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 Ey(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":zr(r,"email",a.message,e);break;case"format:idn-email":zr(r,"idn-email",a.message,e);break;case"pattern:zod":Kt(r,Lr.email,a.message,e);break}break;case"url":zr(r,"uri",a.message,e);break;case"uuid":zr(r,"uuid",a.message,e);break;case"regex":Kt(r,a.regex,a.message,e);break;case"cuid":Kt(r,Lr.cuid,a.message,e);break;case"cuid2":Kt(r,Lr.cuid2,a.message,e);break;case"startsWith":Kt(r,RegExp(`^${qd(a.value,e)}`),a.message,e);break;case"endsWith":Kt(r,RegExp(`${qd(a.value,e)}$`),a.message,e);break;case"datetime":zr(r,"date-time",a.message,e);break;case"date":zr(r,"date",a.message,e);break;case"time":zr(r,"time",a.message,e);break;case"duration":zr(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{Kt(r,RegExp(qd(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&zr(r,"ipv4",a.message,e),a.version!=="v4"&&zr(r,"ipv6",a.message,e);break}case"base64url":Kt(r,Lr.base64url,a.message,e);break;case"jwt":Kt(r,Lr.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Kt(r,Lr.ipv4Cidr,a.message,e),a.version!=="v4"&&Kt(r,Lr.ipv6Cidr,a.message,e);break}case"emoji":Kt(r,Lr.emoji(),a.message,e);break;case"ulid":{Kt(r,Lr.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{zr(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Kt(r,Lr.base64,a.message,e);break}}break}case"nanoid":Kt(r,Lr.nanoid,a.message,e)}return r}function qd(t,e){return e.patternStrategy==="escape"?GN(t):t}var JN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function GN(t){let e="";for(let r=0;r<t.length;r++)JN.has(t[r])||(e+="\\"),e+=t[r];return e}function zr(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function Kt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Sy(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Sy(e,a)}function Sy(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(a.i){if(i){if(n[c].match(/[a-z]/)){l?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&((r=n[c+2])!=null&&r.match(/[a-z]/))?(s+=n[c],l=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(a.m){if(n[c]==="^"){s+=`(^|(?<=[\r
499
- ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
500
- ]))`;continue}}if(a.s&&n[c]==="."){s+=i?`${n[c]}\r
501
- `:`[${n[c]}\r
502
- ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function $y(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=We(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:c,...u}=Ey(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===V.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=wy(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function KN(t,e){if(e.mapStrategy==="record")return $y(t,e);const r=We(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||pr(),a=We(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||pr();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function WN(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function QN(){return{not:pr()}}function YN(){return{type:"null"}}var Fd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function XN(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Fd&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Fd[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return eA(t,e)}var eA=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>We(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function tA(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Fd[t.innerType._def.typeName],"null"]};const r=We(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function rA(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 nA(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=sA(i),c=We(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});c!==void 0&&(r.properties[o]=c,l||a.push(o))}a.length&&(r.required=a);const s=aA(t,e);return s!==void 0&&(r.additionalProperties=s),r}function aA(t,e){if(t.catchall._def.typeName!=="ZodNever")return We(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 sA(t){try{return t.isOptional()}catch{return!0}}var oA=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return We(t.innerType._def,e);const a=We(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:pr()},a]}:pr()},iA=(t,e)=>{if(e.pipeStrategy==="input")return We(t.in._def,e);if(e.pipeStrategy==="output")return We(t.out._def,e);const r=We(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=We(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function lA(t,e){return We(t.type._def,e)}function cA(t,e){const a={type:"array",uniqueItems:!0,items:We(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function uA(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>We(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:We(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>We(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function dA(){return{not:pr()}}function pA(){return pr()}var fA=(t,e)=>We(t.innerType._def,e),hA=(t,e,r)=>{switch(e){case V.ZodString:return Ey(t,r);case V.ZodNumber:return rA(t);case V.ZodObject:return nA(t,r);case V.ZodBigInt:return DN(t);case V.ZodBoolean:return LN();case V.ZodDate:return by(t,r);case V.ZodUndefined:return dA();case V.ZodNull:return YN();case V.ZodArray:return jN(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return XN(t,r);case V.ZodIntersection:return HN(t,r);case V.ZodTuple:return uA(t,r);case V.ZodRecord:return $y(t,r);case V.ZodLiteral:return BN(t);case V.ZodEnum:return ZN(t);case V.ZodNativeEnum:return WN(t);case V.ZodNullable:return tA(t,r);case V.ZodOptional:return oA(t,r);case V.ZodMap:return KN(t,r);case V.ZodSet:return cA(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return lA(t,r);case V.ZodNaN:case V.ZodNever:return QN();case V.ZodEffects:return FN(t,r);case V.ZodAny:return pr();case V.ZodUnknown:return pA();case V.ZodDefault:return qN(t,r);case V.ZodBranded:return wy(t,r);case V.ZodReadonly:return fA(t,r);case V.ZodCatch:return zN(t,r);case V.ZodPipeline:return iA(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function We(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==AN)return l}if(n&&!r){const l=mA(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=hA(t,t.typeName,e),i=typeof o=="function"?We(o(),e):o;if(i&&vA(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var mA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:NN(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),pr()):e.$refStrategy==="seen"?pr():void 0}},vA=(t,e,r)=>(t.description&&(r.description=t.description),r),gA=t=>{const e=MN(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(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},yA=(t,e)=>{var r;const a=gA(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,f])=>{var g;return{...c,[u]:(g=We(f._def,{...a,currentPath:[...a.basePath,a.definitionPath,u]},!0))!=null?g:pr()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=We(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:pr(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},_A=yA;function wA(t,e){var r;const a=(r=void 0)!=null?r:!1;return ml(()=>_A(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function bA(t,e){var r;const a=(r=void 0)!=null?r:!1;return ml(()=>s2(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await ey(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function EA(t){return"_zod"in t}function De(t,e){return EA(t)?bA(t):wA(t)}var Zd=Symbol.for("vercel.ai.schema");function Vt(t){let e;return()=>(e==null&&(e=t()),e)}function ml(t,{validate:e}={}){return{[Zd]:!0,_type:void 0,[fl]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function SA(t){return typeof t=="object"&&t!==null&&Zd in t&&t[Zd]===!0&&"jsonSchema"in t&&"validate"in t}function vl(t){return t==null?ml({properties:{},additionalProperties:!1}):SA(t)?t:typeof t=="function"?t():De(t)}var{btoa:$A,atob:PA}=globalThis;function gl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=PA(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function yl(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return $A(e)}function ia(t){return t instanceof Uint8Array?yl(t):t}function Vd(t){return t==null?void 0:t.replace(/\/$/,"")}function kA(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Py({execute:t,input:e,options:r}){const a=t(e,r);if(kA(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var Hd=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,IA=Object.getOwnPropertyNames,TA=Object.prototype.hasOwnProperty,CA=(t,e)=>{for(var r in e)Hd(t,r,{get:e[r],enumerable:!0})},RA=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of IA(e))!TA.call(t,n)&&n!==r&&Hd(t,n,{get:()=>e[n],enumerable:!(a=xA(e,n))||a.enumerable});return t},OA=t=>RA(Hd({},"__esModule",{value:!0}),t),ky={};CA(ky,{SYMBOL_FOR_REQ_CONTEXT:()=>xy,getContext:()=>AA});var NA=OA(ky);const xy=Symbol.for("@vercel/request-context");function AA(){var e,r;return((r=(e=globalThis[xy])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var Bd=Object.defineProperty,MA=Object.getOwnPropertyDescriptor,jA=Object.getOwnPropertyNames,DA=Object.prototype.hasOwnProperty,LA=(t,e)=>{for(var r in e)Bd(t,r,{get:e[r],enumerable:!0})},zA=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of jA(e))!DA.call(t,n)&&n!==r&&Bd(t,n,{get:()=>e[n],enumerable:!(a=MA(e,n))||a.enumerable});return t},UA=t=>zA(Bd({},"__esModule",{value:!0}),t),Iy={};LA(Iy,{getContext:()=>qA.getContext,getVercelOidcToken:()=>FA,getVercelOidcTokenSync:()=>ZA});var Ty=UA(Iy),qA=NA;async function FA(){return""}function ZA(){return""}var VA="vercel.ai.gateway.error",Jd=Symbol.for(VA),Cy,Ry,fr=class sw extends(Ry=Error,Cy=Jd,Ry){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[Cy]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return sw.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&Jd in e&&e[Jd]===!0}},Oy="GatewayAuthenticationError",HA=`vercel.ai.gateway.error.${Oy}`,Ny=Symbol.for(HA),Ay,My,Gd=class ow extends(My=fr,Ay=Ny,My){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[Ay]=!0,this.name=Oy,this.type="authentication_error"}static isInstance(e){return fr.hasMarker(e)&&Ny in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
548
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const HC=(e={})=>new BC(e);var wm="vercel.ai.error",JC=Symbol.for(wm),bm,WC=class ly extends Error{constructor({name:t,message:n,cause:r}){super(n),this[bm]=!0,this.name=t,this.cause=r}static isInstance(t){return ly.hasMarker(t,wm)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};bm=JC;var se=WC,Sm="AI_APICallError",Cm=`vercel.ai.error.${Sm}`,GC=Symbol.for(Cm),$m,Ve=class extends se{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:Sm,message:e,cause:a}),this[$m]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return se.hasMarker(e,Cm)}};$m=GC;var km="AI_EmptyResponseBodyError",Tm=`vercel.ai.error.${km}`,KC=Symbol.for(Tm),xm,Em=class extends se{constructor({message:e="Empty response body"}={}){super({name:km,message:e}),this[xm]=!0}static isInstance(e){return se.hasMarker(e,Tm)}};xm=KC;function _o(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Im="AI_InvalidArgumentError",Pm=`vercel.ai.error.${Im}`,YC=Symbol.for(Pm),Rm,ju=class extends se{constructor({message:t,cause:n,argument:r}){super({name:Im,message:t,cause:n}),this[Rm]=!0,this.argument=r}static isInstance(t){return se.hasMarker(t,Pm)}};Rm=YC;var Om="AI_InvalidPromptError",Nm=`vercel.ai.error.${Om}`,QC=Symbol.for(Nm),Am,Ir=class extends se{constructor({prompt:e,message:t,cause:n}){super({name:Om,message:`Invalid prompt: ${t}`,cause:n}),this[Am]=!0,this.prompt=e}static isInstance(e){return se.hasMarker(e,Nm)}};Am=QC;var Mm="AI_InvalidResponseDataError",jm=`vercel.ai.error.${Mm}`,XC=Symbol.for(jm),Lm,Is=class extends se{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Mm,message:t}),this[Lm]=!0,this.data=e}static isInstance(e){return se.hasMarker(e,jm)}};Lm=XC;var zm="AI_JSONParseError",Dm=`vercel.ai.error.${zm}`,e$=Symbol.for(Dm),Zm,cr=class extends se{constructor({text:e,cause:t}){super({name:zm,message:`JSON parsing failed: Text: ${e}.
549
+ Error message: ${_o(t)}`,cause:t}),this[Zm]=!0,this.text=e}static isInstance(e){return se.hasMarker(e,Dm)}};Zm=e$;var Um="AI_LoadAPIKeyError",qm=`vercel.ai.error.${Um}`,t$=Symbol.for(qm),Vm,_i=class extends se{constructor({message:e}){super({name:Um,message:e}),this[Vm]=!0}static isInstance(e){return se.hasMarker(e,qm)}};Vm=t$;var Fm="AI_NoSuchModelError",Bm=`vercel.ai.error.${Fm}`,n$=Symbol.for(Bm),Hm,Lu=class extends se{constructor({errorName:e=Fm,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[Hm]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return se.hasMarker(e,Bm)}};Hm=n$;var Jm="AI_TooManyEmbeddingValuesForCallError",Wm=`vercel.ai.error.${Jm}`,r$=Symbol.for(Wm),Gm,o$=class extends se{constructor(e){super({name:Jm,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Gm]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return se.hasMarker(e,Wm)}};Gm=r$;var Km="AI_TypeValidationError",Ym=`vercel.ai.error.${Km}`,s$=Symbol.for(Ym),Qm,a$=class jd extends se{constructor({value:t,cause:n}){super({name:Km,message:`Type validation failed: Value: ${JSON.stringify(t)}.
550
+ Error message: ${_o(n)}`,cause:n}),this[Qm]=!0,this.value=t}static isInstance(t){return se.hasMarker(t,Ym)}static wrap({value:t,cause:n}){return jd.isInstance(n)&&n.value===t?n:new jd({value:t,cause:n})}};Qm=s$;var En=a$,Xm="AI_UnsupportedFunctionalityError",e2=`vercel.ai.error.${Xm}`,i$=Symbol.for(e2),t2,cn=class extends se{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Xm,message:t}),this[t2]=!0,this.functionality=e}static isInstance(e){return se.hasMarker(e,e2)}};t2=i$;function zu(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function l$(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(n2());return}const s=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",i)},i=()=>{a(),o(n2())};n==null||n.addEventListener("abort",i)})}function n2(){return new DOMException("Delay was aborted","AbortError")}function Ps(e){return Object.fromEntries([...e.headers])}var Rs=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new ju({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},c$=Rs();function Du(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Pr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var u$=["fetch failed","failed to fetch"];function r2({error:e,url:t,requestBodyValues:n}){if(Pr(e))return e;if(e instanceof TypeError&&u$.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Ve({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Os(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function d$(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function Rr(e,...t){const n=d$(e??{}),r=new Headers(n),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r)}var o2="3.0.12",p$=()=>globalThis.fetch,s2=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=p$()})=>{try{const a=await s(e,{method:"GET",headers:Rr(t,`ai-sdk/provider-utils/${o2}`,Os()),signal:o}),i=Ps(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw Pr(c)||Ve.isInstance(c)?c:new Ve({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Pr(l)||Ve.isInstance(l))?l:new Ve({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw r2({error:a,url:e,requestBodyValues:{}})}};function f$({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}function wi({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var h$=/"__proto__"\s*:/,m$=/"constructor"\s*:/;function g$(e){const t=JSON.parse(e);return t===null||typeof t!="object"||h$.test(e)===!1&&m$.test(e)===!1?t:y$(t)}function y$(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}function a2(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return g$(e)}finally{Error.stackTraceLimit=t}}var bi=Symbol.for("vercel.ai.validator");function v$(e){return{[bi]:!0,validate:e}}function _$(e){return typeof e=="object"&&e!==null&&bi in e&&e[bi]===!0&&"validate"in e}function wo(e){let t;return()=>(t==null&&(t=e()),t)}function w$(e){return _$(e)?e:typeof e=="function"?e():b$(e)}function b$(e){return v$(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new En({value:t,cause:n.issues})}})}async function Zu({value:e,schema:t}){const n=await ur({value:e,schema:t});if(!n.success)throw En.wrap({value:e,cause:n.error});return n.value}async function ur({value:e,schema:t}){const n=w$(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:En.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:En.wrap({value:e,cause:r}),rawValue:e}}}async function S$({text:e,schema:t}){try{const n=a2(e);return t==null?n:Zu({value:n,schema:t})}catch(n){throw cr.isInstance(n)||En.isInstance(n)?n:new cr({text:e,cause:n})}}async function Or({text:e,schema:t}){try{const n=a2(e);return t==null?{success:!0,value:n,rawValue:n}:await ur({value:n,schema:t})}catch(n){return{success:!1,error:cr.isInstance(n)?n:new cr({text:e,cause:n}),rawValue:void 0}}}function C$({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ni).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Or({text:n,schema:t}))}}))}var $$=()=>globalThis.fetch,Uu=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>k$({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),k$=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=$$()})=>{try{const i=await a(e,{method:"POST",headers:Rr(t,`ai-sdk/provider-utils/${o2}`,Os()),body:n.content,signal:s}),l=Ps(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:n.values})}catch(u){throw Pr(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Pr(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw r2({error:i,url:e,requestBodyValues:n.values})}};function VO(e){return e}function i2(e){return{...e,type:"dynamic"}}async function dr(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Ns=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=Ps(r);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await S$({text:a,schema:e});return{responseHeaders:i,value:new Ve({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new Ve({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},T$=e=>async({response:t})=>{const n=Ps(t);if(t.body==null)throw new Em({});return{responseHeaders:n,value:C$({stream:t.body,schema:e})}},Si=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await Or({text:o,schema:e}),a=Ps(t);if(!s.success)throw new Ve({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},x$=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},E$=Symbol("Let zodToJsonSchema decide on which parser to use"),l2={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"},I$=e=>typeof e=="string"?{...l2,name:e}:{...l2,...e};function zt(){return{}}function P$(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==I.ZodAny&&(s.items=Le(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function R$(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function O$(){return{type:"boolean"}}function c2(e,t){return Le(e.type._def,t)}var N$=(e,t)=>Le(e.innerType._def,t);function u2(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>u2(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return A$(e)}}var A$=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function M$(e,t){return{...Le(e.innerType._def,t),default:e.defaultValue()}}function j$(e,t){return t.effectStrategy==="input"?Le(e.schema._def,t):zt()}function L$(e){return{type:"string",enum:Array.from(e.values)}}var z$=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function D$(e,t){const n=[Le(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Le(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(z$(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}r.push(s)}}),r.length?{allOf:r}:void 0}function Z$(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var qu=void 0,un={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:()=>(qu===void 0&&(qu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qu),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 d2(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":dn(n,"email",r.message,t);break;case"format:idn-email":dn(n,"idn-email",r.message,t);break;case"pattern:zod":_t(n,un.email,r.message,t);break}break;case"url":dn(n,"uri",r.message,t);break;case"uuid":dn(n,"uuid",r.message,t);break;case"regex":_t(n,r.regex,r.message,t);break;case"cuid":_t(n,un.cuid,r.message,t);break;case"cuid2":_t(n,un.cuid2,r.message,t);break;case"startsWith":_t(n,RegExp(`^${Vu(r.value,t)}`),r.message,t);break;case"endsWith":_t(n,RegExp(`${Vu(r.value,t)}$`),r.message,t);break;case"datetime":dn(n,"date-time",r.message,t);break;case"date":dn(n,"date",r.message,t);break;case"time":dn(n,"time",r.message,t);break;case"duration":dn(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{_t(n,RegExp(Vu(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&dn(n,"ipv4",r.message,t),r.version!=="v4"&&dn(n,"ipv6",r.message,t);break}case"base64url":_t(n,un.base64url,r.message,t);break;case"jwt":_t(n,un.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&_t(n,un.ipv4Cidr,r.message,t),r.version!=="v4"&&_t(n,un.ipv6Cidr,r.message,t);break}case"emoji":_t(n,un.emoji(),r.message,t);break;case"ulid":{_t(n,un.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{dn(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{_t(n,un.base64,r.message,t);break}}break}case"nanoid":_t(n,un.nanoid,r.message,t)}return n}function Vu(e,t){return t.patternStrategy==="escape"?q$(e):e}var U$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function q$(e){let t="";for(let n=0;n<e.length;n++)U$.has(e[n])||(t+="\\"),t+=e[n];return t}function dn(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function _t(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:p2(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=p2(t,r)}function p2(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
551
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
552
+ ]))`;continue}}if(r.s&&o[c]==="."){s+=i?`${o[c]}\r
553
+ `:`[${o[c]}\r
554
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function f2(e,t){var n,r,o,s,a,i;const l={type:"object",additionalProperties:(n=Le(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===I.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=d2(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===I.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===I.ZodBranded&&e.keyType._def.type._def.typeName===I.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=c2(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function V$(e,t){if(t.mapStrategy==="record")return f2(e,t);const n=Le(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||zt(),r=Le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||zt();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function F$(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function B$(){return{not:zt()}}function H$(){return{type:"null"}}var Fu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function J$(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Fu&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Fu[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return W$(e,t)}var W$=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>Le(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function G$(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Fu[e.innerType._def.typeName],"null"]};const n=Le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function K$(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Y$(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=X$(i),c=Le(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=Q$(e,t);return s!==void 0&&(n.additionalProperties=s),n}function Q$(e,t){if(e.catchall._def.typeName!=="ZodNever")return Le(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function X$(e){try{return e.isOptional()}catch{return!0}}var ek=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Le(e.innerType._def,t);const r=Le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:zt()},r]}:zt()},tk=(e,t)=>{if(t.pipeStrategy==="input")return Le(e.in._def,t);if(t.pipeStrategy==="output")return Le(e.out._def,t);const n=Le(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Le(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function nk(e,t){return Le(e.type._def,t)}function rk(e,t){const r={type:"array",uniqueItems:!0,items:Le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function ok(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Le(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function sk(){return{not:zt()}}function ak(){return zt()}var ik=(e,t)=>Le(e.innerType._def,t),lk=(e,t,n)=>{switch(t){case I.ZodString:return d2(e,n);case I.ZodNumber:return K$(e);case I.ZodObject:return Y$(e,n);case I.ZodBigInt:return R$(e);case I.ZodBoolean:return O$();case I.ZodDate:return u2(e,n);case I.ZodUndefined:return sk();case I.ZodNull:return H$();case I.ZodArray:return P$(e,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return J$(e,n);case I.ZodIntersection:return D$(e,n);case I.ZodTuple:return ok(e,n);case I.ZodRecord:return f2(e,n);case I.ZodLiteral:return Z$(e);case I.ZodEnum:return L$(e);case I.ZodNativeEnum:return F$(e);case I.ZodNullable:return G$(e,n);case I.ZodOptional:return ek(e,n);case I.ZodMap:return V$(e,n);case I.ZodSet:return rk(e,n);case I.ZodLazy:return()=>e.getter()._def;case I.ZodPromise:return nk(e,n);case I.ZodNaN:case I.ZodNever:return B$();case I.ZodEffects:return j$(e,n);case I.ZodAny:return zt();case I.ZodUnknown:return ak();case I.ZodDefault:return M$(e,n);case I.ZodBranded:return c2(e,n);case I.ZodReadonly:return ik(e,n);case I.ZodCatch:return N$(e,n);case I.ZodPipeline:return tk(e,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}};function Le(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==E$)return l}if(o&&!n){const l=ck(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=lk(e,e.typeName,t),i=typeof a=="function"?Le(a(),t):a;if(i&&uk(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var ck=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:x$(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),zt()):t.$refStrategy==="seen"?zt():void 0}},uk=(e,t,n)=>(e.description&&(n.description=e.description),n),dk=e=>{const t=I$(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},pk=(e,t)=>{var n;const r=dk(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var y;return{...c,[u]:(y=Le(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0))!=null?y:zt()}},{}):void 0;const s=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,a=(n=Le(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:zt(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},fk=pk;function hk(e,t){var n;const r=(n=void 0)!=null?n:!1;return As(()=>fk(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function mk(e,t){var n;const r=(n=void 0)!=null?n:!1;return As(()=>ic(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"}),{validate:async o=>{const s=await lc(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function gk(e){return"_zod"in e}function Nr(e,t){return gk(e)?mk(e):hk(e)}var Bu=Symbol.for("vercel.ai.schema");function As(e,{validate:t}={}){return{[Bu]:!0,_type:void 0,[bi]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function yk(e){return typeof e=="object"&&e!==null&&Bu in e&&e[Bu]===!0&&"jsonSchema"in e&&"validate"in e}function Ci(e){return e==null?As({properties:{},additionalProperties:!1}):yk(e)?e:typeof e=="function"?e():Nr(e)}var{btoa:vk,atob:_k}=globalThis;function Hu(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=_k(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Ju(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return vk(t)}function wk(e){return e==null?void 0:e.replace(/\/$/,"")}function bk(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*h2({execute:e,input:t,options:n}){const r=e(t,n);if(bk(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}var Wu=Object.defineProperty,Sk=Object.getOwnPropertyDescriptor,Ck=Object.getOwnPropertyNames,$k=Object.prototype.hasOwnProperty,kk=(e,t)=>{for(var n in t)Wu(e,n,{get:t[n],enumerable:!0})},Tk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ck(t))!$k.call(e,o)&&o!==n&&Wu(e,o,{get:()=>t[o],enumerable:!(r=Sk(t,o))||r.enumerable});return e},xk=e=>Tk(Wu({},"__esModule",{value:!0}),e),m2={};kk(m2,{SYMBOL_FOR_REQ_CONTEXT:()=>g2,getContext:()=>Ik});var Ek=xk(m2);const g2=Symbol.for("@vercel/request-context");function Ik(){var t,n;return((n=(t=globalThis[g2])==null?void 0:t.get)==null?void 0:n.call(t))??{}}var Gu=Object.defineProperty,Pk=Object.getOwnPropertyDescriptor,Rk=Object.getOwnPropertyNames,Ok=Object.prototype.hasOwnProperty,Nk=(e,t)=>{for(var n in t)Gu(e,n,{get:t[n],enumerable:!0})},Ak=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rk(t))!Ok.call(e,o)&&o!==n&&Gu(e,o,{get:()=>t[o],enumerable:!(r=Pk(t,o))||r.enumerable});return e},Mk=e=>Ak(Gu({},"__esModule",{value:!0}),e),y2={};Nk(y2,{getContext:()=>jk.getContext,getVercelOidcToken:()=>Lk,getVercelOidcTokenSync:()=>zk});var v2=Mk(y2),jk=Ek;async function Lk(){return""}function zk(){return""}var Dk="vercel.ai.gateway.error",Ku=Symbol.for(Dk),_2,w2,Dt=class cy extends(w2=Error,_2=Ku,w2){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[_2]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return cy.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Ku in t&&t[Ku]===!0}},b2="GatewayAuthenticationError",Zk=`vercel.ai.gateway.error.${b2}`,S2=Symbol.for(Zk),C2,$2,Yu=class uy extends($2=Dt,C2=S2,$2){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[C2]=!0,this.name=b2,this.type="authentication_error"}static isInstance(t){return Dt.hasMarker(t)&&S2 in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
503
555
 
504
556
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
505
557
 
506
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?o=`AI Gateway authentication failed: Invalid OIDC token.
558
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
507
559
 
508
560
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
509
561
 
510
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:o=`AI Gateway authentication failed: No authentication provided.
562
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
511
563
 
512
564
  Option 1 - API key:
513
565
  Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
514
566
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
515
567
 
516
568
  Option 2 - OIDC token:
517
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new ow({message:o,statusCode:n,cause:s})}},jy="GatewayInvalidRequestError",BA=`vercel.ai.gateway.error.${jy}`,Dy=Symbol.for(BA),Ly,zy,JA=class extends(zy=fr,Ly=Dy,zy){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Ly]=!0,this.name=jy,this.type="invalid_request_error"}static isInstance(t){return fr.hasMarker(t)&&Dy in t}},Uy="GatewayRateLimitError",GA=`vercel.ai.gateway.error.${Uy}`,qy=Symbol.for(GA),Fy,Zy,KA=class extends(Zy=fr,Fy=qy,Zy){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Fy]=!0,this.name=Uy,this.type="rate_limit_exceeded"}static isInstance(t){return fr.hasMarker(t)&&qy in t}},Vy="GatewayModelNotFoundError",WA=`vercel.ai.gateway.error.${Vy}`,Hy=Symbol.for(WA),QA=_t(()=>De(I({modelId:E()}))),By,Jy,Gy=class extends(Jy=fr,By=Hy,Jy){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[By]=!0,this.name=Vy,this.type="model_not_found",this.modelId=r}static isInstance(t){return fr.hasMarker(t)&&Hy in t}},Ky="GatewayInternalServerError",YA=`vercel.ai.gateway.error.${Ky}`,Wy=Symbol.for(YA),Qy,Yy,Xy=class extends(Yy=fr,Qy=Wy,Yy){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Qy]=!0,this.name=Ky,this.type="internal_server_error"}static isInstance(t){return fr.hasMarker(t)&&Wy in t}},e_="GatewayResponseError",XA=`vercel.ai.gateway.error.${e_}`,t_=Symbol.for(XA),r_,n_,e4=class extends(n_=fr,r_=t_,n_){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[r_]=!0,this.name=e_,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return fr.hasMarker(t)&&t_ in t}};async function a_({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await jr({value:t,schema:t4});if(!s.success)return new e4({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return Gd.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new JA({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new KA({message:l,statusCode:e,cause:a});case"model_not_found":{const c=await jr({value:o.error.param,schema:QA});return new Gy({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:a})}case"internal_server_error":return new Xy({message:l,statusCode:e,cause:a});default:return new Xy({message:l,statusCode:e,cause:a})}}var t4=_t(()=>De(I({error:I({message:E(),type:E().nullish(),param:Mr().nullish(),code:He([E(),Z()]).nullish()})})));function la(t,e){var r;return fr.isInstance(t)?t:Nt.isInstance(t)?a_({response:r4(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):a_({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function r4(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 s_="ai-gateway-auth-method";async function po(t){const e=await jr({value:t[s_],schema:n4});return e.success?e.value:void 0}var n4=_t(()=>De(He([W("api-key"),W("oidc")]))),o_=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await vy({url:`${this.config.baseURL}/config`,headers:await Dn(this.config.headers()),successfulResponseHandler:Dr(a4),failedResponseHandler:oa({errorSchema:_r(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await la(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await vy({url:`${t.origin}/v1/credits`,headers:await Dn(this.config.headers()),successfulResponseHandler:Dr(s4),failedResponseHandler:oa({errorSchema:_r(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await la(t)}}},a4=_t(()=>De(I({models:oe(I({id:E(),name:E(),description:E().nullish(),pricing:I({input:E(),output:E(),input_cache_read:E().nullish(),input_cache_write:E().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:I({specificationVersion:W("v2"),provider:E(),modelId:E()}),modelType:ht(["language","embedding","image"]).nullish()}))}))),s4=_t(()=>De(I({balance:E(),total_used:E()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),o4=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:a}=t,n=await Dn(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await sr({url:this.getUrl(),headers:Gt(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await Dn(this.config.o11yHeaders)),body:e,successfulResponseHandler:Dr(_r()),failedResponseHandler:oa({errorSchema:_r(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await la(s,await po(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await Dn(this.config.headers());try{const{value:s,responseHeaders:o}=await sr({url:this.getUrl(),headers:Gt(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await Dn(this.config.o11yHeaders)),body:e,successfulResponseHandler:uo(_r()),failedResponseHandler:oa({errorSchema:_r(),errorToMessage:i=>i}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await la(s,await po(n))}}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 a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}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)}}},i4=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:a}){var n;const s=await Dn(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await sr({url:this.getUrl(),headers:Gt(s,e??{},this.getModelConfigHeaders(),await Dn(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:Dr(l4),failedResponseHandler:oa({errorSchema:_r(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await la(o,await po(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},l4=_t(()=>De(I({embeddings:oe(oe(Z())),usage:I({tokens:Z()}).nullish(),providerMetadata:kt(E(),kt(E(),Mr())).optional()})));async function c4(){var t;return(t=Ty.getContext().headers)==null?void 0:t["x-vercel-id"]}var u4="2.0.0",d4="0.0.1";function p4(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=Vd(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const m=await h4(t);if(m)return aa({Authorization:`Bearer ${m.token}`,"ai-gateway-protocol-version":d4,[s_]:m.authMethod,...t.headers},`ai-sdk/gateway/${u4}`);throw Gd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const m=co({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=co({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),h=co({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const p=await c4();return{...m&&{"ai-o11y-deployment-id":m},...v&&{"ai-o11y-environment":v},...h&&{"ai-o11y-region":h},...p&&{"ai-o11y-request-id":p}}}},u=m=>new o4(m,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),f=async()=>{var m,v,h;const p=(h=(v=(m=t._internal)==null?void 0:m.currentDate)==null?void 0:v.call(m).getTime())!=null?h:Date.now();return(!a||p-o>s)&&(o=p,a=new o_({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(_=>(n=_,_)).catch(async _=>{throw await la(_,await po(await l()))})),n?Promise.resolve(n):a},g=async()=>new o_({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async m=>{throw await la(m,await po(await l()))}),d=function(m){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(m)};return d.getAvailableModels=f,d.getCredits=g,d.imageModel=m=>{throw new Pd({modelId:m,modelType:"imageModel"})},d.languageModel=u,d.textEmbeddingModel=m=>new i4(m,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d}var f4=p4();async function h4(t){const e=co({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await Ty.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var m4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},ca="1.9.0",i_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function v4(t){var e=new Set([t]),r=new Set,a=t.match(i_);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(i_);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||n.major!==u.major?s(l):n.major===0?n.minor===u.minor&&n.patch<=u.patch?o(l):s(l):n.minor<=u.minor?o(l):s(l)}}var g4=v4(ca),y4=ca.split(".")[0],fo=Symbol.for("opentelemetry.js.api."+y4),ho=m4;function mo(t,e,r,a){var n;a===void 0&&(a=!1);var s=ho[fo]=(n=ho[fo])!==null&&n!==void 0?n:{version:ca};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==ca){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+ca);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+ca+"."),!0}function ua(t){var e,r,a=(e=ho[fo])===null||e===void 0?void 0:e.version;if(!(!a||!g4(a)))return(r=ho[fo])===null||r===void 0?void 0:r[t]}function vo(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+ca+".");var r=ho[fo];r&&delete r[t]}var _4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},w4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},b4=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 go("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return go("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return go("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return go("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return go("verbose",this._namespace,e)},t}();function go(t,e,r){var a=ua("diag");if(a)return r.unshift(e),a[t].apply(a,w4([],_4(r),!1))}var hr;(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"})(hr||(hr={}));function E4(t,e){t<hr.NONE?t=hr.NONE:t>hr.ALL&&(t=hr.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",hr.ERROR),warn:r("warn",hr.WARN),info:r("info",hr.INFO),debug:r("debug",hr.DEBUG),verbose:r("verbose",hr.VERBOSE)}}var S4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},$4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},P4="diag",rn=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=ua("diag");if(i)return i[n].apply(i,$4([],S4(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:hr.INFO}),n===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=ua("diag"),f=E4((i=s.logLevel)!==null&&i!==void 0?i:hr.INFO,n);if(u&&!s.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+g),f.warn("Current logger will overwrite one already registered from "+g)}return mo("diag",f,r,!0)};r.setLogger=a,r.disable=function(){vo(P4,r)},r.createComponentLogger=function(n){return new b4(n)},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}(),k4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},x4=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},I4=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=k4(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},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,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=x4(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(c){e={error:c}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();rn.instance();function T4(t){return t===void 0&&(t={}),new I4(new Map(Object.entries(t)))}function l_(t){return Symbol.for(t)}var C4=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),R4=new C4,da=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},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 a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),O4=function(){function t(){}return t.prototype.createGauge=function(e,r){return F4},t.prototype.createHistogram=function(e,r){return Z4},t.prototype.createCounter=function(e,r){return q4},t.prototype.createUpDownCounter=function(e,r){return V4},t.prototype.createObservableGauge=function(e,r){return B4},t.prototype.createObservableCounter=function(e,r){return H4},t.prototype.createObservableUpDownCounter=function(e,r){return J4},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),_l=function(){function t(){}return t}(),N4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(_l),A4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(_l),M4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(_l),j4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(_l),Kd=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),D4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Kd),L4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Kd),z4=function(t){da(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Kd),U4=new O4,q4=new N4,F4=new M4,Z4=new j4,V4=new A4,H4=new D4,B4=new L4,J4=new z4,G4={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},K4={set:function(t,e,r){t!=null&&(t[e]=r)}},W4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Q4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},Y4=function(){function t(){}return t.prototype.active=function(){return R4},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,Q4([a],W4(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),X4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},eM=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},Wd="context",tM=new Y4,wl=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return mo(Wd,e,rn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,eM([e,r,a],X4(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return ua(Wd)||tM},t.prototype.disable=function(){this._getContextManager().disable(),vo(Wd,rn.instance())},t}(),Qd;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Qd||(Qd={}));var c_="0000000000000000",u_="00000000000000000000000000000000",rM={traceId:u_,spanId:c_,traceFlags:Qd.NONE},yo=function(){function t(e){e===void 0&&(e=rM),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}(),Yd=l_("OpenTelemetry Context Key SPAN");function Xd(t){return t.getValue(Yd)||void 0}function nM(){return Xd(wl.getInstance().active())}function ep(t,e){return t.setValue(Yd,e)}function aM(t){return t.deleteValue(Yd)}function sM(t,e){return ep(t,new yo(e))}function d_(t){var e;return(e=Xd(t))===null||e===void 0?void 0:e.spanContext()}var oM=/^([0-9a-f]{32})$/i,iM=/^[0-9a-f]{16}$/i;function lM(t){return oM.test(t)&&t!==u_}function cM(t){return iM.test(t)&&t!==c_}function p_(t){return lM(t.traceId)&&cM(t.spanId)}function uM(t){return new yo(t)}var tp=wl.getInstance(),f_=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=tp.active());var n=!!(r!=null&&r.root);if(n)return new yo;var s=a&&d_(a);return dM(s)&&p_(s)?new yo(s):new yo},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??tp.active(),c=this.startSpan(e,s,l),u=ep(l,c);return tp.with(u,i,void 0,c)}},t}();function dM(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var pM=new f_,fM=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,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):pM},t}(),hM=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new f_},t}(),mM=new hM,h_=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new fM(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:mM},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),bl;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(bl||(bl={})),wl.getInstance(),rn.instance();var vM=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return U4},t}(),gM=new vM,rp="metrics",yM=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return mo(rp,e,rn.instance())},t.prototype.getMeterProvider=function(){return ua(rp)||gM},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){vo(rp,rn.instance())},t}();yM.getInstance();var _M=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),np=l_("OpenTelemetry Baggage Key");function m_(t){return t.getValue(np)||void 0}function wM(){return m_(wl.getInstance().active())}function bM(t,e){return t.setValue(np,e)}function EM(t){return t.deleteValue(np)}var ap="propagation",SM=new _M,$M=function(){function t(){this.createBaggage=T4,this.getBaggage=m_,this.getActiveBaggage=wM,this.setBaggage=bM,this.deleteBaggage=EM}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return mo(ap,e,rn.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=K4),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=G4),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){vo(ap,rn.instance())},t.prototype._getGlobalPropagator=function(){return ua(ap)||SM},t}();$M.getInstance();var sp="trace",PM=function(){function t(){this._proxyTracerProvider=new h_,this.wrapSpanContext=uM,this.isSpanContextValid=p_,this.deleteSpan=aM,this.getSpan=Xd,this.getActiveSpan=nM,this.getSpanContext=d_,this.setSpan=ep,this.setSpanContext=sM}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=mo(sp,this._proxyTracerProvider,rn.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return ua(sp)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){vo(sp,rn.instance()),this._proxyTracerProvider=new h_},t}(),kM=PM.getInstance(),xM=Object.defineProperty,IM=(t,e)=>{for(var r in e)xM(t,r,{get:e[r],enumerable:!0})},v_="AI_NoOutputSpecifiedError",g_=`vercel.ai.error.${v_}`,TM=Symbol.for(g_),y_,__=class extends Pe{constructor({message:t="No output specified."}={}){super({name:v_,message:t}),this[y_]=!0}static isInstance(t){return Pe.hasMarker(t,g_)}};y_=TM;function CM(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 a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var RM="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",w_=!1,b_=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}w_||(w_=!0,console.info(RM));for(const r of t)console.warn(CM(r))}},E_="AI_InvalidArgumentError",S_=`vercel.ai.error.${E_}`,OM=Symbol.for(S_),$_,nn=class extends Pe{constructor({parameter:t,value:e,message:r}){super({name:E_,message:`Invalid argument for parameter ${t}: ${r}`}),this[$_]=!0,this.parameter=t,this.value=e}static isInstance(t){return Pe.hasMarker(t,S_)}};$_=OM;var P_="AI_InvalidToolInputError",k_=`vercel.ai.error.${P_}`,NM=Symbol.for(k_),x_,I_=class extends Pe{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${Wa(r)}`}){super({name:P_,message:a,cause:r}),this[x_]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return Pe.hasMarker(t,k_)}};x_=NM;var T_="AI_NoObjectGeneratedError",C_=`vercel.ai.error.${T_}`,AM=Symbol.for(C_),R_,O_=class extends Pe{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:T_,message:t,cause:e}),this[R_]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return Pe.hasMarker(t,C_)}};R_=AM;var N_="AI_NoOutputGeneratedError",A_=`vercel.ai.error.${N_}`,MM=Symbol.for(A_),M_,jM=class extends Pe{constructor({message:t="No output generated.",cause:e}={}){super({name:N_,message:t,cause:e}),this[M_]=!0}static isInstance(t){return Pe.hasMarker(t,A_)}};M_=MM;var j_="AI_NoSuchToolError",D_=`vercel.ai.error.${j_}`,DM=Symbol.for(D_),L_,op=class extends Pe{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:j_,message:r}),this[L_]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return Pe.hasMarker(t,D_)}};L_=DM;var z_="AI_ToolCallRepairError",U_=`vercel.ai.error.${z_}`,LM=Symbol.for(U_),q_,zM=class extends Pe{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Wa(t)}`}){super({name:z_,message:r,cause:t}),this[q_]=!0,this.originalError=e}static isInstance(t){return Pe.hasMarker(t,U_)}};q_=LM;var UM=class extends Pe{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}},F_="AI_InvalidMessageRoleError",Z_=`vercel.ai.error.${F_}`,qM=Symbol.for(Z_),V_,FM=class extends Pe{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:F_,message:e}),this[V_]=!0,this.role=t}static isInstance(t){return Pe.hasMarker(t,Z_)}};V_=qM;var H_="AI_DownloadError",B_=`vercel.ai.error.${H_}`,ZM=Symbol.for(B_),J_,ip=class extends Pe{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:H_,message:n,cause:a}),this[J_]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return Pe.hasMarker(t,B_)}};J_=ZM;var G_="AI_RetryError",K_=`vercel.ai.error.${G_}`,VM=Symbol.for(K_),W_,Q_=class extends Pe{constructor({message:t,reason:e,errors:r}){super({name:G_,message:t}),this[W_]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Pe.hasMarker(t,K_)}};W_=VM;function El(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new UM({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return HM().languageModel(t)}function HM(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:f4}var BM=[{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]}],JM=t=>{const e=typeof t=="string"?gl(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function GM(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?JM(t):t}function KM({data:t,signatures:e}){const r=GM(t),a=typeof r=="string"?gl(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var Y_="5.0.76",WM=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:aa({},`ai-sdk/${Y_}`,Ld())});if(!a.ok)throw new ip({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw ip.isInstance(a)?a:new ip({url:r,cause:a})}},QM=(t=WM)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function YM(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 X_=He([E(),pl(Uint8Array),pl(ArrayBuffer),cN(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function e0(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}=YM(t.toString());if(e==null||r==null)throw new Pe({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function XM(t){return typeof t=="string"?t:t instanceof ArrayBuffer?yl(new Uint8Array(t)):yl(t)}async function t0({prompt:t,supportedUrls:e,download:r=QM()}){const a=await tj(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>ej({message:n,downloadedAssets:a}))]}function ej({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(a=>rj(a,e)).filter(a=>a.type!=="text"||a.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(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=e0(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new FM({role:a})}}}async function tj(t,e,r){const a=t.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const i=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&gN({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function rj(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=e0(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const c=e[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=KM({data:l,signatures:BM}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,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:l,providerOptions:t.providerOptions}}}}function lp({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new nn({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new nn({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new nn({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new nn({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new nn({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new nn({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new nn({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new nn({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function nj(t){return t!=null&&Object.keys(t).length>0}function r0({tools:t,toolChoice:e,activeTools:r}){return nj(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:vl(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;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 _o=py(()=>He([D2(),E(),Z(),Pt(),kt(E(),_o),oe(_o)])),an=kt(E(),kt(E(),_o)),n0=I({type:W("text"),text:E(),providerOptions:an.optional()}),aj=I({type:W("image"),image:He([X_,pl(URL)]),mediaType:E().optional(),providerOptions:an.optional()}),a0=I({type:W("file"),data:He([X_,pl(URL)]),filename:E().optional(),mediaType:E(),providerOptions:an.optional()}),sj=I({type:W("reasoning"),text:E(),providerOptions:an.optional()}),oj=I({type:W("tool-call"),toolCallId:E(),toolName:E(),input:Mr(),providerOptions:an.optional(),providerExecuted:Pt().optional()}),ij=nr("type",[I({type:W("text"),value:E()}),I({type:W("json"),value:_o}),I({type:W("error-text"),value:E()}),I({type:W("error-json"),value:_o}),I({type:W("content"),value:oe(He([I({type:W("text"),text:E()}),I({type:W("media"),data:E(),mediaType:E()})]))})]),s0=I({type:W("tool-result"),toolCallId:E(),toolName:E(),output:ij,providerOptions:an.optional()}),lj=I({role:W("system"),content:E(),providerOptions:an.optional()}),cj=I({role:W("user"),content:He([E(),oe(He([n0,aj,a0]))]),providerOptions:an.optional()}),uj=I({role:W("assistant"),content:He([E(),oe(He([n0,a0,sj,oj,s0]))]),providerOptions:an.optional()}),dj=I({role:W("tool"),content:oe(s0),providerOptions:an.optional()}),pj=He([lj,cj,uj,dj]);async function o0(t){if(t.prompt==null&&t.messages==null)throw new ea({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new ea({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new ea({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 ea({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new ea({prompt:t,message:"messages must not be empty"});const r=await jr({value:e,schema:oe(pj)});if(!r.success)throw new ea({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 i0(t){return Gd.isInstance(t)||Gy.isInstance(t)?new Pe({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 es({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function l0({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var fj={startSpan(){return Sl},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(Sl);if(typeof r=="function")return r(Sl);if(typeof a=="function")return a(Sl)}},Sl={spanContext(){return hj},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}},hj={traceId:"",spanId:"",traceFlags:0};function c0({isEnabled:t=!1,tracer:e}={}){return t?e||kM.getTracer("ai"):fj}function ts({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{cp(s,o)}finally{s.end()}throw o}})}function cp(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:bl.ERROR,message:e.message})):t.setStatus({code:bl.ERROR})}function wr({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function u0(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?XM(r.data):r.data}:r)})))}function d0(t,e){return{inputTokens:wo(t.inputTokens,e.inputTokens),outputTokens:wo(t.outputTokens,e.outputTokens),totalTokens:wo(t.totalTokens,e.totalTokens),reasoningTokens:wo(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:wo(t.cachedInputTokens,e.cachedInputTokens)}}function wo(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function up(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function mj({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var vj=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>p0(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function p0(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(na(o)||e===0)throw o;const i=Dd(o),l=[...s,o],c=l.length;if(c>e)throw new Q_({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Nt.isInstance(o)&&o.isRetryable===!0&&c<=e)return await fN(mj({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),p0(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw c===1?o:new Q_({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function f0({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new nn({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new nn({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:vj({maxRetries:r,abortSignal:e})}}function h0(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var m0=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=yl(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=gl(this.base64Data)),this.uint8ArrayData}},gj=class extends m0{constructor(t){super(t),this.type="file"}};async function v0({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new op({toolName:t.toolName});try{return await g0({toolCall:t,tools:e})}catch(s){if(r==null||!(op.isInstance(s)||I_.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return vl(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new zM({cause:i,originalError:s})}if(o==null)throw s;return await g0({toolCall:o,tools:e})}}catch(s){const o=await sa({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function g0({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new op({toolName:t.toolName,availableTools:Object.keys(e)});const n=vl(a.inputSchema),s=t.input.trim()===""?await jr({value:{},schema:n}):await sa({text:t.input,schema:n});if(s.success===!1)throw new I_({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var y0=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}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 dp(t){return({steps:e})=>e.length===t}async function _0({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function pp({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Wa(t)}:r==="json"?{type:"error-json",value:w0(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:w0(t)}}function w0(t){return t===void 0?null:t}function fp({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:pp({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:pp({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:pp({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var yj=lo({prefix:"aitxt",size:24});async function _j({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=dp(1),experimental_output:u,experimental_telemetry:f,providerOptions:g,experimental_activeTools:d,activeTools:m=d,experimental_prepareStep:v,prepareStep:h=v,experimental_repairToolCall:p,experimental_download:_,experimental_context:w,_internal:{generateId:b=yj,currentDate:S=()=>new Date}={},onStepFinish:x,...k}){const A=El(t),O=up(c),{maxRetries:H,retry:J}=f0({maxRetries:o,abortSignal:i}),K=lp(k),z=aa(l??{},`ai/${Y_}`),U=l0({model:A,telemetry:f,headers:z,settings:{...K,maxRetries:H}}),G=await o0({system:a,prompt:n,messages:s}),se=c0(f);try{return await ts({name:"ai.generateText",attributes:wr({telemetry:f,attributes:{...es({operationId:"ai.generateText",telemetry:f}),...U,"ai.model.provider":A.provider,"ai.model.id":A.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:se,fn:async ne=>{var ce,pe,M,R,D,N,y;const P=lp(k);let j,Q=[],ee=[];const Se=[],de=[];do{const Te=[...G.messages,...Se],me=await(h==null?void 0:h({model:A,steps:de,stepNumber:de.length,messages:Te})),Ne=El((ce=me==null?void 0:me.model)!=null?ce:A),Ae=await t0({prompt:{system:(pe=me==null?void 0:me.system)!=null?pe:G.system,messages:(M=me==null?void 0:me.messages)!=null?M:Te},supportedUrls:await Ne.supportedUrls,download:_}),{toolChoice:ke,tools:tt}=r0({tools:e,toolChoice:(R=me==null?void 0:me.toolChoice)!=null?R:r,activeTools:(D=me==null?void 0:me.activeTools)!=null?D:m});j=await J(()=>{var Ee;return ts({name:"ai.generateText.doGenerate",attributes:wr({telemetry:f,attributes:{...es({operationId:"ai.generateText.doGenerate",telemetry:f}),...U,"ai.model.provider":Ne.provider,"ai.model.id":Ne.modelId,"ai.prompt.messages":{input:()=>u0(Ae)},"ai.prompt.tools":{input:()=>tt==null?void 0:tt.map(Qe=>JSON.stringify(Qe))},"ai.prompt.toolChoice":{input:()=>ke!=null?JSON.stringify(ke):void 0},"gen_ai.system":Ne.provider,"gen_ai.request.model":Ne.modelId,"gen_ai.request.frequency_penalty":k.frequencyPenalty,"gen_ai.request.max_tokens":k.maxOutputTokens,"gen_ai.request.presence_penalty":k.presencePenalty,"gen_ai.request.stop_sequences":k.stopSequences,"gen_ai.request.temperature":(Ee=k.temperature)!=null?Ee:void 0,"gen_ai.request.top_k":k.topK,"gen_ai.request.top_p":k.topP}}),tracer:se,fn:async Qe=>{var or,At,wt,ir,Mt,lr,_n,pa;const ut=await Ne.doGenerate({...P,tools:tt,toolChoice:ke,responseFormat:u==null?void 0:u.responseFormat,prompt:Ae,providerOptions:g,abortSignal:i,headers:z}),br={id:(At=(or=ut.response)==null?void 0:or.id)!=null?At:b(),timestamp:(ir=(wt=ut.response)==null?void 0:wt.timestamp)!=null?ir:S(),modelId:(lr=(Mt=ut.response)==null?void 0:Mt.modelId)!=null?lr:Ne.modelId,headers:(_n=ut.response)==null?void 0:_n.headers,body:(pa=ut.response)==null?void 0:pa.body};return Qe.setAttributes(wr({telemetry:f,attributes:{"ai.response.finishReason":ut.finishReason,"ai.response.text":{output:()=>h0(ut.content)},"ai.response.toolCalls":{output:()=>{const Ur=b0(ut.content);return Ur==null?void 0:JSON.stringify(Ur)}},"ai.response.id":br.id,"ai.response.model":br.modelId,"ai.response.timestamp":br.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ut.providerMetadata),"ai.usage.promptTokens":ut.usage.inputTokens,"ai.usage.completionTokens":ut.usage.outputTokens,"gen_ai.response.finish_reasons":[ut.finishReason],"gen_ai.response.id":br.id,"gen_ai.response.model":br.modelId,"gen_ai.usage.input_tokens":ut.usage.inputTokens,"gen_ai.usage.output_tokens":ut.usage.outputTokens}})),{...ut,response:br}}})});const Ve=await Promise.all(j.content.filter(Ee=>Ee.type==="tool-call").map(Ee=>v0({toolCall:Ee,tools:e,repairToolCall:p,system:a,messages:Te})));for(const Ee of Ve){if(Ee.invalid)continue;const Qe=e[Ee.toolName];(Qe==null?void 0:Qe.onInputAvailable)!=null&&await Qe.onInputAvailable({input:Ee.input,toolCallId:Ee.toolCallId,messages:Te,abortSignal:i,experimental_context:w})}const re=Ve.filter(Ee=>Ee.invalid&&Ee.dynamic);ee=[];for(const Ee of re)ee.push({type:"tool-error",toolCallId:Ee.toolCallId,toolName:Ee.toolName,input:Ee.input,error:Dd(Ee.error),dynamic:!0});Q=Ve.filter(Ee=>!Ee.providerExecuted),e!=null&&ee.push(...await wj({toolCalls:Q.filter(Ee=>!Ee.invalid),tools:e,tracer:se,telemetry:f,messages:Te,abortSignal:i,experimental_context:w}));const ze=Ej({content:j.content,toolCalls:Ve,toolOutputs:ee});Se.push(...fp({content:ze,tools:e}));const Be=new y0({content:ze,finishReason:j.finishReason,usage:j.usage,warnings:j.warnings,providerMetadata:j.providerMetadata,request:(N=j.request)!=null?N:{},response:{...j.response,messages:structuredClone(Se)}});b_((y=j.warnings)!=null?y:[]),de.push(Be),await(x==null?void 0:x(Be))}while(Q.length>0&&ee.length===Q.length&&!await _0({stopConditions:O,steps:de}));ne.setAttributes(wr({telemetry:f,attributes:{"ai.response.finishReason":j.finishReason,"ai.response.text":{output:()=>h0(j.content)},"ai.response.toolCalls":{output:()=>{const Te=b0(j.content);return Te==null?void 0:JSON.stringify(Te)}},"ai.response.providerMetadata":JSON.stringify(j.providerMetadata),"ai.usage.promptTokens":j.usage.inputTokens,"ai.usage.completionTokens":j.usage.outputTokens}}));const ge=de[de.length-1];let vt;return ge.finishReason==="stop"&&(vt=await(u==null?void 0:u.parseOutput({text:ge.text},{response:ge.response,usage:ge.usage,finishReason:ge.finishReason}))),new bj({steps:de,resolvedOutput:vt})}})}catch(ne){throw i0(ne)}}async function wj({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:c,input:u})=>{const f=e[c];if((f==null?void 0:f.execute)!=null)return ts({name:"ai.toolCall",attributes:wr({telemetry:a,attributes:{...es({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async g=>{try{const d=Py({execute:f.execute.bind(f),input:u,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let m;for await(const v of d)v.type==="final"&&(m=v.output);try{g.setAttributes(wr({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(m)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:m,dynamic:f.type==="dynamic"}}catch(d){return cp(g,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:f.type==="dynamic"}}}})}))).filter(l=>l!=null)}var bj=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)=>d0(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 __;return this.resolvedOutput}};function b0(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 Ej({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new m0(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function $l(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function Sj({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:$l(r,{"content-type":"text/plain; charset=utf-8"})})}function E0({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function $j({response:t,status:e,statusText:r,headers:a,textStream:n}){E0({response:t,status:e,statusText:r,headers:Object.fromEntries($l(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var S0=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 uy({message:a,statusCode:o,cause:s})}},k2="GatewayInvalidRequestError",Uk=`vercel.ai.gateway.error.${k2}`,T2=Symbol.for(Uk),x2,E2,qk=class extends(E2=Dt,x2=T2,E2){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[x2]=!0,this.name=k2,this.type="invalid_request_error"}static isInstance(e){return Dt.hasMarker(e)&&T2 in e}},I2="GatewayRateLimitError",Vk=`vercel.ai.gateway.error.${I2}`,P2=Symbol.for(Vk),R2,O2,Fk=class extends(O2=Dt,R2=P2,O2){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[R2]=!0,this.name=I2,this.type="rate_limit_exceeded"}static isInstance(e){return Dt.hasMarker(e)&&P2 in e}},N2="GatewayModelNotFoundError",Bk=`vercel.ai.gateway.error.${N2}`,A2=Symbol.for(Bk),Hk=wo(()=>Nr(C({modelId:p()}))),M2,j2,L2=class extends(j2=Dt,M2=A2,j2){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[M2]=!0,this.name=N2,this.type="model_not_found",this.modelId=n}static isInstance(e){return Dt.hasMarker(e)&&A2 in e}},z2="GatewayInternalServerError",Jk=`vercel.ai.gateway.error.${z2}`,D2=Symbol.for(Jk),Z2,U2,q2=class extends(U2=Dt,Z2=D2,U2){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Z2]=!0,this.name=z2,this.type="internal_server_error"}static isInstance(e){return Dt.hasMarker(e)&&D2 in e}},V2="GatewayResponseError",Wk=`vercel.ai.gateway.error.${V2}`,F2=Symbol.for(Wk),B2,H2,Gk=class extends(H2=Dt,B2=F2,H2){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[B2]=!0,this.name=V2,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return Dt.hasMarker(e)&&F2 in e}};async function J2({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const s=await ur({value:e,schema:Kk});if(!s.success)return new Gk({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const a=s.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return Yu.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new qk({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new Fk({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await ur({value:a.error.param,schema:Hk});return new L2({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new q2({message:l,statusCode:t,cause:r});default:return new q2({message:l,statusCode:t,cause:r})}}var Kk=wo(()=>Nr(C({error:C({message:p(),type:p().nullish(),param:Ze().nullish(),code:ne([p(),O()]).nullish()})})));function Ar(e,t){var n;return Dt.isInstance(e)?e:Ve.isInstance(e)?J2({response:Yk(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):J2({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function Yk(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var W2="ai-gateway-auth-method";async function Ms(e){const t=await ur({value:e[W2],schema:Qk});return t.success?t.value:void 0}var Qk=wo(()=>Nr(ne([N("api-key"),N("oidc")]))),G2=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await s2({url:`${this.config.baseURL}/config`,headers:await dr(this.config.headers()),successfulResponseHandler:Si(Xk),failedResponseHandler:Ns({errorSchema:Mt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Ar(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await s2({url:`${e.origin}/v1/credits`,headers:await dr(this.config.headers()),successfulResponseHandler:Si(eT),failedResponseHandler:Ns({errorSchema:Mt(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await Ar(e)}}},Xk=wo(()=>Nr(C({models:A(C({id:p(),name:p(),description:p().nullish(),pricing:C({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:C({specificationVersion:N("v2"),provider:p(),modelId:p()}),modelType:Se(["language","embedding","image"]).nullish()}))}))),eT=wo(()=>Nr(C({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),tT=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await dr(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Uu({url:this.getUrl(),headers:zu(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await dr(this.config.o11yHeaders)),body:t,successfulResponseHandler:Si(Mt()),failedResponseHandler:Ns({errorSchema:Mt(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:n}}catch(s){throw await Ar(s,await Ms(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await dr(this.config.headers());try{const{value:s,responseHeaders:a}=await Uu({url:this.getUrl(),headers:zu(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await dr(this.config.o11yHeaders)),body:t,successfulResponseHandler:T$(Mt()),failedResponseHandler:Ns({errorSchema:Mt(),errorToMessage:i=>i}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){n.length>0&&i.enqueue({type:"stream-start",warnings:n})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await Ar(s,await Ms(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),s=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},nT=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const s=await dr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Uu({url:this.getUrl(),headers:zu(s,t??{},this.getModelConfigHeaders(),await dr(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Si(rT),failedResponseHandler:Ns({errorSchema:Mt(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await Ar(a,await Ms(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},rT=wo(()=>Nr(C({embeddings:A(A(O())),usage:C({tokens:O()}).nullish(),providerMetadata:fe(p(),fe(p(),Ze())).optional()})));async function oT(){var e;return(e=v2.getContext().headers)==null?void 0:e["x-vercel-id"]}var sT="2.0.0",aT="0.0.1";function iT(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(n=wk(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const g=await cT(e);if(g)return Rr({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":aT,[W2]:g.authMethod,...e.headers},`ai-sdk/gateway/${sT}`);throw Yu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const g=wi({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=wi({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=wi({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const d=await oT();return{...g&&{"ai-o11y-deployment-id":g},...v&&{"ai-o11y-environment":v},...m&&{"ai-o11y-region":m},...d&&{"ai-o11y-request-id":d}}}},u=g=>new tT(g,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var g,v,m;const d=(m=(v=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:v.call(g).getTime())!=null?m:Date.now();return(!r||d-a>s)&&(a=d,r=new G2({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(w=>(o=w,w)).catch(async w=>{throw await Ar(w,await Ms(await l()))})),o?Promise.resolve(o):r},y=async()=>new G2({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async g=>{throw await Ar(g,await Ms(await l()))}),f=function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(g)};return f.getAvailableModels=h,f.getCredits=y,f.imageModel=g=>{throw new Lu({modelId:g,modelType:"imageModel"})},f.languageModel=u,f.textEmbeddingModel=g=>new nT(g,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f}var lT=iT();async function cT(e){const t=wi({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await v2.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var uT=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Mr="1.9.0",K2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function dT(e){var t=new Set([e]),n=new Set,r=e.match(K2);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return n.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(K2);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var pT=dT(Mr),fT=Mr.split(".")[0],js=Symbol.for("opentelemetry.js.api."+fT),Ls=uT;function zs(e,t,n,r){var o;r===void 0&&(r=!1);var s=Ls[js]=(o=Ls[js])!==null&&o!==void 0?o:{version:Mr};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==Mr){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Mr);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Mr+"."),!0}function jr(e){var t,n,r=(t=Ls[js])===null||t===void 0?void 0:t.version;if(!(!r||!pT(r)))return(n=Ls[js])===null||n===void 0?void 0:n[e]}function Ds(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Mr+".");var n=Ls[js];n&&delete n[e]}var hT=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},mT=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},gT=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Zs("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Zs("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Zs("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Zs("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Zs("verbose",this._namespace,t)},e}();function Zs(e,t,n){var r=jr("diag");if(r)return n.unshift(t),r[e].apply(r,mT([],hT(n),!1))}var Zt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Zt||(Zt={}));function yT(e,t){e<Zt.NONE?e=Zt.NONE:e>Zt.ALL&&(e=Zt.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:n("error",Zt.ERROR),warn:n("warn",Zt.WARN),info:n("info",Zt.INFO),debug:n("debug",Zt.DEBUG),verbose:n("verbose",Zt.VERBOSE)}}var vT=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},_T=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},wT="diag",In=function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=jr("diag");if(i)return i[o].apply(i,_T([],vT(s),!1))}}var n=this,r=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:Zt.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=jr("diag"),h=yT((i=s.logLevel)!==null&&i!==void 0?i:Zt.INFO,o);if(u&&!s.suppressOverrideMessage){var y=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+y),h.warn("Current logger will overwrite one already registered from "+y)}return zs("diag",h,n,!0)};n.setLogger=r,n.disable=function(){Ds(wT,n)},n.createComponentLogger=function(o){return new gT(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),bT=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},ST=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},CT=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=bT(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var a=ST(r),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();In.instance();function $T(e){return e===void 0&&(e={}),new CT(new Map(Object.entries(e)))}function Y2(e){return Symbol.for(e)}var kT=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e}(),TT=new kT,Lr=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),xT=function(){function e(){}return e.prototype.createGauge=function(t,n){return LT},e.prototype.createHistogram=function(t,n){return zT},e.prototype.createCounter=function(t,n){return jT},e.prototype.createUpDownCounter=function(t,n){return DT},e.prototype.createObservableGauge=function(t,n){return UT},e.prototype.createObservableCounter=function(t,n){return ZT},e.prototype.createObservableUpDownCounter=function(t,n){return qT},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e}(),$i=function(){function e(){}return e}(),ET=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}($i),IT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}($i),PT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}($i),RT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}($i),Qu=function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e}(),OT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Qu),NT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Qu),AT=function(e){Lr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Qu),MT=new xT,jT=new ET,LT=new PT,zT=new RT,DT=new IT,ZT=new OT,UT=new NT,qT=new AT,VT={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},FT={set:function(e,t,n){e!=null&&(e[t]=n)}},BT=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},HT=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},JT=function(){function e(){}return e.prototype.active=function(){return TT},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,HT([r],BT(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),WT=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},GT=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},Xu="context",KT=new JT,ki=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return zs(Xu,t,In.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,GT([t,n,r],WT(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return jr(Xu)||KT},e.prototype.disable=function(){this._getContextManager().disable(),Ds(Xu,In.instance())},e}(),ed;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ed||(ed={}));var Q2="0000000000000000",X2="00000000000000000000000000000000",YT={traceId:X2,spanId:Q2,traceFlags:ed.NONE},Us=function(){function e(t){t===void 0&&(t=YT),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e}(),td=Y2("OpenTelemetry Context Key SPAN");function nd(e){return e.getValue(td)||void 0}function QT(){return nd(ki.getInstance().active())}function rd(e,t){return e.setValue(td,t)}function XT(e){return e.deleteValue(td)}function ex(e,t){return rd(e,new Us(t))}function eg(e){var t;return(t=nd(e))===null||t===void 0?void 0:t.spanContext()}var tx=/^([0-9a-f]{32})$/i,nx=/^[0-9a-f]{16}$/i;function rx(e){return tx.test(e)&&e!==X2}function ox(e){return nx.test(e)&&e!==Q2}function tg(e){return rx(e.traceId)&&ox(e.spanId)}function sx(e){return new Us(e)}var od=ki.getInstance(),ng=function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=od.active());var o=!!(n!=null&&n.root);if(o)return new Us;var s=r&&eg(r);return ax(s)&&tg(s)?new Us(s):new Us},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=n:arguments.length===3?(s=n,i=r):(s=n,a=r,i=o);var l=a??od.active(),c=this.startSpan(t,s,l),u=rd(l,c);return od.with(u,i,void 0,c)}},e}();function ax(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var ix=new ng,lx=function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):ix},e}(),cx=function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new ng},e}(),ux=new cx,rg=function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new lx(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:ux},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e}(),Ti;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ti||(Ti={})),ki.getInstance(),In.instance();var dx=function(){function e(){}return e.prototype.getMeter=function(t,n,r){return MT},e}(),px=new dx,sd="metrics",fx=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return zs(sd,t,In.instance())},e.prototype.getMeterProvider=function(){return jr(sd)||px},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Ds(sd,In.instance())},e}();fx.getInstance();var hx=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}(),ad=Y2("OpenTelemetry Baggage Key");function og(e){return e.getValue(ad)||void 0}function mx(){return og(ki.getInstance().active())}function gx(e,t){return e.setValue(ad,t)}function yx(e){return e.deleteValue(ad)}var id="propagation",vx=new hx,_x=function(){function e(){this.createBaggage=$T,this.getBaggage=og,this.getActiveBaggage=mx,this.setBaggage=gx,this.deleteBaggage=yx}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return zs(id,t,In.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=FT),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=VT),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Ds(id,In.instance())},e.prototype._getGlobalPropagator=function(){return jr(id)||vx},e}();_x.getInstance();var ld="trace",wx=function(){function e(){this._proxyTracerProvider=new rg,this.wrapSpanContext=sx,this.isSpanContextValid=tg,this.deleteSpan=XT,this.getSpan=nd,this.getActiveSpan=QT,this.getSpanContext=eg,this.setSpan=rd,this.setSpanContext=ex}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=zs(ld,this._proxyTracerProvider,In.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return jr(ld)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Ds(ld,In.instance()),this._proxyTracerProvider=new rg},e}(),bx=wx.getInstance(),Sx=Object.defineProperty,Cx=(e,t)=>{for(var n in t)Sx(e,n,{get:t[n],enumerable:!0})},sg="AI_NoOutputSpecifiedError",ag=`vercel.ai.error.${sg}`,$x=Symbol.for(ag),ig,lg=class extends se{constructor({message:e="No output specified."}={}){super({name:sg,message:e}),this[ig]=!0}static isInstance(e){return se.hasMarker(e,ag)}};ig=$x;function kx(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var Tx="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",cg=!1,ug=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}cg||(cg=!0,console.info(Tx));for(const n of e)console.warn(kx(n))}},dg="AI_InvalidArgumentError",pg=`vercel.ai.error.${dg}`,xx=Symbol.for(pg),fg,Pn=class extends se{constructor({parameter:e,value:t,message:n}){super({name:dg,message:`Invalid argument for parameter ${e}: ${n}`}),this[fg]=!0,this.parameter=e,this.value=t}static isInstance(e){return se.hasMarker(e,pg)}};fg=xx;var hg="AI_InvalidToolInputError",mg=`vercel.ai.error.${hg}`,Ex=Symbol.for(mg),gg,yg=class extends se{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${_o(n)}`}){super({name:hg,message:r,cause:n}),this[gg]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return se.hasMarker(e,mg)}};gg=Ex;var Ix="AI_MCPClientError",vg=`vercel.ai.error.${Ix}`,Px=Symbol.for(vg),_g,ot=class extends se{constructor({name:e="MCPClientError",message:t,cause:n,data:r,code:o}){super({name:e,message:t,cause:n}),this[_g]=!0,this.data=r,this.code=o}static isInstance(e){return se.hasMarker(e,vg)}};_g=Px;var wg="AI_NoObjectGeneratedError",bg=`vercel.ai.error.${wg}`,Rx=Symbol.for(bg),Sg,Cg=class extends se{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:s}){super({name:wg,message:e,cause:t}),this[Sg]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=s}static isInstance(e){return se.hasMarker(e,bg)}};Sg=Rx;var $g="AI_NoOutputGeneratedError",kg=`vercel.ai.error.${$g}`,Ox=Symbol.for(kg),Tg,Nx=class extends se{constructor({message:e="No output generated.",cause:t}={}){super({name:$g,message:e,cause:t}),this[Tg]=!0}static isInstance(e){return se.hasMarker(e,kg)}};Tg=Ox;var xg="AI_NoSuchToolError",Eg=`vercel.ai.error.${xg}`,Ax=Symbol.for(Eg),Ig,cd=class extends se{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:xg,message:n}),this[Ig]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return se.hasMarker(e,Eg)}};Ig=Ax;var Pg="AI_ToolCallRepairError",Rg=`vercel.ai.error.${Pg}`,Mx=Symbol.for(Rg),Og,jx=class extends se{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${_o(e)}`}){super({name:Pg,message:n,cause:e}),this[Og]=!0,this.originalError=t}static isInstance(e){return se.hasMarker(e,Rg)}};Og=Mx;var Lx=class extends se{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Ng="AI_InvalidMessageRoleError",Ag=`vercel.ai.error.${Ng}`,zx=Symbol.for(Ag),Mg,Dx=class extends se{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ng,message:t}),this[Mg]=!0,this.role=e}static isInstance(e){return se.hasMarker(e,Ag)}};Mg=zx;var jg="AI_DownloadError",Lg=`vercel.ai.error.${jg}`,Zx=Symbol.for(Lg),zg,ud=class extends se{constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:jg,message:o,cause:r}),this[zg]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return se.hasMarker(e,Lg)}};zg=Zx;var Dg="AI_RetryError",Zg=`vercel.ai.error.${Dg}`,Ux=Symbol.for(Zg),Ug,qg=class extends se{constructor({message:e,reason:t,errors:n}){super({name:Dg,message:e}),this[Ug]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return se.hasMarker(e,Zg)}};Ug=Ux;function xi(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new Lx({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return qx().languageModel(e)}function qx(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:lT}var Vx=[{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]}],Fx=e=>{const t=typeof e=="string"?Hu(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Bx(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Fx(e):e}function Hx({data:e,signatures:t}){const n=Bx(e),r=typeof n=="string"?Hu(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}var Ei="5.0.76",Jx=async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Rr({},`ai-sdk/${Ei}`,Os())});if(!r.ok)throw new ud({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw ud.isInstance(r)?r:new ud({url:n,cause:r})}},Wx=(e=Jx)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function Gx(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Vg=ne([p(),Ma(Uint8Array),Ma(ArrayBuffer),vh(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Fg(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=Gx(e.toString());if(t==null||n==null)throw new se({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Kx(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Ju(new Uint8Array(e)):Ju(e)}async function Bg({prompt:e,supportedUrls:t,download:n=Wx()}){const r=await Qx(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>Yx({message:o,downloadedAssets:r}))]}function Yx({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Xx(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=Fg(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new Dx({role:r})}}}async function Qx(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&f$({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Xx(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=Fg(r);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(n=Hx({data:l,signatures:Vx}))!=null?n:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function dd({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new Pn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Pn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Pn({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Pn({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new Pn({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Pn({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Pn({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Pn({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function eE(e){return e!=null&&Object.keys(e).length>0}function Hg({tools:e,toolChoice:t,activeTools:n}){return eE(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Ci(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var qs=yh(()=>ne([F5(),p(),O(),le(),fe(p(),qs),A(qs)])),Rn=fe(p(),fe(p(),qs)),Jg=C({type:N("text"),text:p(),providerOptions:Rn.optional()}),tE=C({type:N("image"),image:ne([Vg,Ma(URL)]),mediaType:p().optional(),providerOptions:Rn.optional()}),Wg=C({type:N("file"),data:ne([Vg,Ma(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Rn.optional()}),nE=C({type:N("reasoning"),text:p(),providerOptions:Rn.optional()}),rE=C({type:N("tool-call"),toolCallId:p(),toolName:p(),input:Ze(),providerOptions:Rn.optional(),providerExecuted:le().optional()}),oE=rt("type",[C({type:N("text"),value:p()}),C({type:N("json"),value:qs}),C({type:N("error-text"),value:p()}),C({type:N("error-json"),value:qs}),C({type:N("content"),value:A(ne([C({type:N("text"),text:p()}),C({type:N("media"),data:p(),mediaType:p()})]))})]),Gg=C({type:N("tool-result"),toolCallId:p(),toolName:p(),output:oE,providerOptions:Rn.optional()}),sE=C({role:N("system"),content:p(),providerOptions:Rn.optional()}),aE=C({role:N("user"),content:ne([p(),A(ne([Jg,tE,Wg]))]),providerOptions:Rn.optional()}),iE=C({role:N("assistant"),content:ne([p(),A(ne([Jg,Wg,nE,rE,Gg]))]),providerOptions:Rn.optional()}),lE=C({role:N("tool"),content:A(Gg),providerOptions:Rn.optional()}),cE=ne([sE,aE,iE,lE]);async function Kg(e){if(e.prompt==null&&e.messages==null)throw new Ir({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Ir({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Ir({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Ir({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Ir({prompt:e,message:"messages must not be empty"});const n=await ur({value:t,schema:A(cE)});if(!n.success)throw new Ir({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function Yg(e){return Yu.isInstance(e)||L2.isInstance(e)?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:e}):e}function bo({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Qg({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>(s[`ai.settings.${a}`]=i,s),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(r??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var uE={startSpan(){return Ii},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Ii);if(typeof n=="function")return n(Ii);if(typeof r=="function")return r(Ii)}},Ii={spanContext(){return dE},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}},dE={traceId:"",spanId:"",traceFlags:0};function Xg({isEnabled:e=!1,tracer:t}={}){return e?t||bx.getTracer("ai"):uE}function So({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async s=>{try{const a=await r(s);return o&&s.end(),a}catch(a){try{pd(s,a)}finally{s.end()}throw a}})}function pd(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ti.ERROR,message:t.message})):e.setStatus({code:Ti.ERROR})}function Ht({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const s=o.input();return s==null?n:{...n,[r]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const s=o.output();return s==null?n:{...n,[r]:s}}return{...n,[r]:o}},{})}function e1(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Kx(n.data):n.data}:n)})))}function t1(e,t){return{inputTokens:Vs(e.inputTokens,t.inputTokens),outputTokens:Vs(e.outputTokens,t.outputTokens),totalTokens:Vs(e.totalTokens,t.totalTokens),reasoningTokens:Vs(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Vs(e.cachedInputTokens,t.cachedInputTokens)}}function Vs(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function fd(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function pE({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var fE=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>n1(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function n1(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Pr(a)||t===0)throw a;const i=Du(a),l=[...s,a],c=l.length;if(c>t)throw new qg({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Ve.isInstance(a)&&a.isRetryable===!0&&c<=t)return await l$(pE({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),n1(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new qg({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function r1({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Pn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Pn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:fE({maxRetries:n,abortSignal:t})}}function o1(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var s1=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Ju(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Hu(this.base64Data)),this.uint8ArrayData}},hE=class extends s1{constructor(e){super(e),this.type="file"}};async function a1({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new cd({toolName:e.toolName});try{return await i1({toolCall:e,tools:t})}catch(s){if(n==null||!(cd.isInstance(s)||yg.isInstance(s)))throw s;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return Ci(l).jsonSchema},system:r,messages:o,error:s})}catch(i){throw new jx({cause:i,originalError:s})}if(a==null)throw s;return await i1({toolCall:a,tools:t})}}catch(s){const a=await Or({text:e.input}),i=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function i1({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new cd({toolName:e.toolName,availableTools:Object.keys(t)});const o=Ci(r.inputSchema),s=e.input.trim()===""?await ur({value:{},schema:o}):await Or({text:e.input,schema:o});if(s.success===!1)throw new yg({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var l1=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=s,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function hd(e){return({steps:t})=>t.length===e}async function c1({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function md({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:_o(e)}:n==="json"?{type:"error-json",value:u1(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:u1(e)}}function u1(e){return e===void 0?null:e}function gd({content:e,tools:t}){const n=[],r=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:md({tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:md({tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:md({tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return o.length>0&&n.push({role:"tool",content:o}),n}var mE=Rs({prefix:"aitxt",size:24});async function gE({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=hd(1),experimental_output:u,experimental_telemetry:h,providerOptions:y,experimental_activeTools:f,activeTools:g=f,experimental_prepareStep:v,prepareStep:m=v,experimental_repairToolCall:d,experimental_download:w,experimental_context:_,_internal:{generateId:b=mE,currentDate:T=()=>new Date}={},onStepFinish:P,...E}){const Z=xi(e),U=fd(c),{maxRetries:W,retry:V}=r1({maxRetries:a,abortSignal:i}),B=dd(E),J=Rr(l??{},`ai/${Ei}`),H=Qg({model:Z,telemetry:h,headers:J,settings:{...B,maxRetries:W}}),ue=await Kg({system:r,prompt:o,messages:s}),Ce=Xg(h);try{return await So({name:"ai.generateText",attributes:Ht({telemetry:h,attributes:{...bo({operationId:"ai.generateText",telemetry:h}),...H,"ai.model.provider":Z.provider,"ai.model.id":Z.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:s})}}}),tracer:Ce,fn:async ae=>{var ye,he,L,x,M,R,$;const k=dd(E);let S,z=[],D=[];const ve=[],ce=[];do{const He=[...ue.messages,...ve],$e=await(m==null?void 0:m({model:Z,steps:ce,stepNumber:ce.length,messages:He})),Pe=xi((ye=$e==null?void 0:$e.model)!=null?ye:Z),Ge=await Bg({prompt:{system:(he=$e==null?void 0:$e.system)!=null?he:ue.system,messages:(L=$e==null?void 0:$e.messages)!=null?L:He},supportedUrls:await Pe.supportedUrls,download:w}),{toolChoice:we,tools:nt}=Hg({tools:t,toolChoice:(x=$e==null?void 0:$e.toolChoice)!=null?x:n,activeTools:(M=$e==null?void 0:$e.activeTools)!=null?M:g});S=await V(()=>{var Me;return So({name:"ai.generateText.doGenerate",attributes:Ht({telemetry:h,attributes:{...bo({operationId:"ai.generateText.doGenerate",telemetry:h}),...H,"ai.model.provider":Pe.provider,"ai.model.id":Pe.modelId,"ai.prompt.messages":{input:()=>e1(Ge)},"ai.prompt.tools":{input:()=>nt==null?void 0:nt.map(Ot=>JSON.stringify(Ot))},"ai.prompt.toolChoice":{input:()=>we!=null?JSON.stringify(we):void 0},"gen_ai.system":Pe.provider,"gen_ai.request.model":Pe.modelId,"gen_ai.request.frequency_penalty":E.frequencyPenalty,"gen_ai.request.max_tokens":E.maxOutputTokens,"gen_ai.request.presence_penalty":E.presencePenalty,"gen_ai.request.stop_sequences":E.stopSequences,"gen_ai.request.temperature":(Me=E.temperature)!=null?Me:void 0,"gen_ai.request.top_k":E.topK,"gen_ai.request.top_p":E.topP}}),tracer:Ce,fn:async Ot=>{var Fn,Nt,dt,Kt,fr,hr,$o,Li;const st=await Pe.doGenerate({...k,tools:nt,toolChoice:we,responseFormat:u==null?void 0:u.responseFormat,prompt:Ge,providerOptions:y,abortSignal:i,headers:J}),Bn={id:(Nt=(Fn=st.response)==null?void 0:Fn.id)!=null?Nt:b(),timestamp:(Kt=(dt=st.response)==null?void 0:dt.timestamp)!=null?Kt:T(),modelId:(hr=(fr=st.response)==null?void 0:fr.modelId)!=null?hr:Pe.modelId,headers:($o=st.response)==null?void 0:$o.headers,body:(Li=st.response)==null?void 0:Li.body};return Ot.setAttributes(Ht({telemetry:h,attributes:{"ai.response.finishReason":st.finishReason,"ai.response.text":{output:()=>o1(st.content)},"ai.response.toolCalls":{output:()=>{const Hn=d1(st.content);return Hn==null?void 0:JSON.stringify(Hn)}},"ai.response.id":Bn.id,"ai.response.model":Bn.modelId,"ai.response.timestamp":Bn.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":Bn.id,"gen_ai.response.model":Bn.modelId,"gen_ai.usage.input_tokens":st.usage.inputTokens,"gen_ai.usage.output_tokens":st.usage.outputTokens}})),{...st,response:Bn}}})});const Rt=await Promise.all(S.content.filter(Me=>Me.type==="tool-call").map(Me=>a1({toolCall:Me,tools:t,repairToolCall:d,system:r,messages:He})));for(const Me of Rt){if(Me.invalid)continue;const Ot=t[Me.toolName];(Ot==null?void 0:Ot.onInputAvailable)!=null&&await Ot.onInputAvailable({input:Me.input,toolCallId:Me.toolCallId,messages:He,abortSignal:i,experimental_context:_})}const G=Rt.filter(Me=>Me.invalid&&Me.dynamic);D=[];for(const Me of G)D.push({type:"tool-error",toolCallId:Me.toolCallId,toolName:Me.toolName,input:Me.input,error:Du(Me.error),dynamic:!0});z=Rt.filter(Me=>!Me.providerExecuted),t!=null&&D.push(...await yE({toolCalls:z.filter(Me=>!Me.invalid),tools:t,tracer:Ce,telemetry:h,messages:He,abortSignal:i,experimental_context:_}));const Ae=_E({content:S.content,toolCalls:Rt,toolOutputs:D});ve.push(...gd({content:Ae,tools:t}));const Gt=new l1({content:Ae,finishReason:S.finishReason,usage:S.usage,warnings:S.warnings,providerMetadata:S.providerMetadata,request:(R=S.request)!=null?R:{},response:{...S.response,messages:structuredClone(ve)}});ug(($=S.warnings)!=null?$:[]),ce.push(Gt),await(P==null?void 0:P(Gt))}while(z.length>0&&D.length===z.length&&!await c1({stopConditions:U,steps:ce}));ae.setAttributes(Ht({telemetry:h,attributes:{"ai.response.finishReason":S.finishReason,"ai.response.text":{output:()=>o1(S.content)},"ai.response.toolCalls":{output:()=>{const He=d1(S.content);return He==null?void 0:JSON.stringify(He)}},"ai.response.providerMetadata":JSON.stringify(S.providerMetadata),"ai.usage.promptTokens":S.usage.inputTokens,"ai.usage.completionTokens":S.usage.outputTokens}}));const Te=ce[ce.length-1];let Wt;return Te.finishReason==="stop"&&(Wt=await(u==null?void 0:u.parseOutput({text:Te.text},{response:Te.response,usage:Te.usage,finishReason:Te.finishReason}))),new vE({steps:ce,resolvedOutput:Wt})}})}catch(ae){throw Yg(ae)}}async function yE({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:u})=>{const h=t[c];if((h==null?void 0:h.execute)!=null)return So({name:"ai.toolCall",attributes:Ht({telemetry:r,attributes:{...bo({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:n,fn:async y=>{try{const f=h2({execute:h.execute.bind(h),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let g;for await(const v of f)v.type==="final"&&(g=v.output);try{y.setAttributes(Ht({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(g)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:g,dynamic:h.type==="dynamic"}}catch(f){return pd(y,f),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:f,dynamic:h.type==="dynamic"}}}})}))).filter(l=>l!=null)}var vE=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.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((e,t)=>t1(e,t.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 lg;return this.resolvedOutput}};function d1(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function _E({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new s1(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}function Pi(e,t){const n=new Headers(e??{});for(const[r,o]of Object.entries(t))n.has(r)||n.set(r,o);return n}function wE({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Pi(n,{"content-type":"text/plain; charset=utf-8"})})}function p1({response:e,status:t,statusText:n,headers:r,stream:o}){e.writeHead(t??200,n,r);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)||await new Promise(u=>{e.once("drain",u)})}}catch(i){throw i}finally{e.end()}})()}function bE({response:e,status:t,statusText:n,headers:r,textStream:o}){p1({response:e,status:t,statusText:n,headers:Object.fromEntries(Pi(r,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var f1=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
518
570
 
519
- `)},flush(t){t.enqueue(`data: [DONE]
571
+ `)},flush(e){e.enqueue(`data: [DONE]
520
572
 
521
- `)}})}},$0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Pj({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new S0);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:$l(r,$0)})}function kj({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function xj(t){return t.type.startsWith("data-")}function P0(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 a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=P0(s,n):r[a]=n}return r}function Ij(t){const e=["ROOT"];let r=-1,a=null;function n(l,c,u){switch(l){case'"':{r=c,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,a=c,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=c,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function o(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":n(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const f=t.substring(a,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(a,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 k0(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await sa({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await sa({text:Ij(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function hp(t){return t.type.startsWith("tool-")}function x0(t){return t.type.split("-").slice(1).join("-")}function Tj({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Cj({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:c,write:u})=>{var f,g,d,m;function v(b){const x=c.message.parts.filter(hp).find(k=>k.toolCallId===b);if(x==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return x}function h(b){const x=c.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===b);if(x==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return x}function p(b){var S;const x=c.message.parts.find(O=>hp(O)&&O.toolCallId===b.toolCallId),k=b,A=x;x!=null?(x.state=b.state,A.input=k.input,A.output=k.output,A.errorText=k.errorText,A.rawInput=k.rawInput,A.preliminary=k.preliminary,A.providerExecuted=(S=k.providerExecuted)!=null?S:x.providerExecuted,k.providerMetadata!=null&&x.state==="input-available"&&(x.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function _(b){var S;const x=c.message.parts.find(O=>O.type==="dynamic-tool"&&O.toolCallId===b.toolCallId),k=b,A=x;x!=null?(x.state=b.state,A.toolName=b.toolName,A.input=k.input,A.output=k.output,A.errorText=k.errorText,A.rawInput=(S=k.rawInput)!=null?S:A.rawInput,A.preliminary=k.preliminary,k.providerMetadata!=null&&x.state==="input-available"&&(x.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function w(b){if(b!=null){const S=c.message.metadata!=null?P0(c.message.metadata,b):b;e!=null&&await en({value:S,schema:e}),c.message.metadata=S}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(g=i.providerMetadata)!=null?g:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(m=i.providerMetadata)!=null?m:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(hp);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:S}=await k0(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}):p({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({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=h(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:x0(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=h(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText})}else{const b=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:x0(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await w(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{await w(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await w(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(xj(i)){(r==null?void 0:r[i.type])!=null&&await en({value:i.data,schema:r[i.type]});const b=i;if(b.transient){o==null||o(b);break}const S=b.id!=null?c.message.parts.find(x=>b.type===x.type&&b.id===x.id):void 0;S!=null?S.data=b.data:c.message.parts.push(b),o==null||o(b),u()}}l.enqueue(i)})}}))}function Rj({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(g,d){if(g.type==="start"){const m=g;m.messageId==null&&t!=null&&(m.messageId=t)}g.type==="abort"&&(o=!0),d.enqueue(g)}}));if(r==null)return i;const l=Tj({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),c=async g=>{await g({state:l,write:()=>{}})};let u=!1;const f=async()=>{if(u||!r)return;u=!0;const g=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:g,responseMessage:l.message,messages:[...g?e.slice(0,-1):e,l.message]})};return Cj({stream:i,runUpdateMessageJob:c,onError:a}).pipeThrough(new TransformStream({transform(g,d){d.enqueue(g)},async cancel(){await f()},async flush(){await f()}}))}function Oj({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new S0);if(s){const[i,l]=o.tee();o=i,s({stream:l})}E0({response:t,status:e,statusText:r,headers:Object.fromEntries($l(a,$0).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function Pl(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function Nj({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function I0(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function Aj(){let t=[],e=null,r=!1,a=I0();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=I0(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var kl=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))}};function Mj(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function jj({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(p){c=p}}),f=new Set,g=new Map;let d=!1,m;function v(){d&&f.size===0&&(m!=null&&c.enqueue(m),c.close())}const h=new TransformStream({async transform(p,_){const w=p.type;switch(w){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":{_.enqueue(p);break}case"file":{_.enqueue({type:"file",file:new gj({data:p.data,mediaType:p.mediaType})});break}case"finish":{m={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const b=await v0({toolCall:p,tools:t,repairToolCall:i,system:n,messages:s});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Dd(b.error),dynamic:!0});break}const S=t[b.toolName];if(g.set(b.toolCallId,b.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:o,experimental_context:l}),S.execute!=null&&b.providerExecuted!==!0){const x=ar();f.add(x),ts({name:"ai.toolCall",attributes:wr({telemetry:a,attributes:{...es({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async k=>{let A;try{const O=Py({execute:S.execute.bind(S),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const H of O)c.enqueue({...b,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(A=H.output)}catch(O){cp(k,O),c.enqueue({...b,type:"tool-error",error:O}),f.delete(x),v();return}f.delete(x),v();try{k.setAttributes(wr({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(A)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=p.toolName;p.isError?c.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:b,input:g.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):_.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:b,input:g.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const b=w;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,v()}});return new ReadableStream({async start(p){return Promise.all([e.pipeThrough(h).pipeTo(new WritableStream({write(_){p.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){p.enqueue(_)},close(){p.close()}}))])}})}var Dj=lo({prefix:"aitxt",size:24});function Lj({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=dp(1),experimental_output:u,experimental_telemetry:f,prepareStep:g,providerOptions:d,experimental_activeTools:m,activeTools:v=m,experimental_repairToolCall:h,experimental_transform:p,experimental_download:_,includeRawChunks:w=!1,onChunk:b,onError:S=({error:U})=>{console.error(U)},onFinish:x,onAbort:k,onStepFinish:A,experimental_context:O,_internal:{now:H=Mj,generateId:J=Dj,currentDate:K=()=>new Date}={},...z}){return new Uj({model:El(t),telemetry:f,headers:l,settings:z,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:up(p),activeTools:v,repairToolCall:h,stopConditions:up(c),output:u,providerOptions:d,prepareStep:g,includeRawChunks:w,onChunk:b,onError:S,onFinish:x,onAbort:k,onStepFinish:A,now:H,currentDate:K,generateId:J,experimental_context:O,download:_})}function zj(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==n&&(s({controller:i,partialOutput:l.partial}),n=c)}}})}var Uj=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:c,toolChoice:u,transforms:f,activeTools:g,repairToolCall:d,stopConditions:m,output:v,providerOptions:h,prepareStep:p,includeRawChunks:_,now:w,currentDate:b,generateId:S,onChunk:x,onError:k,onFinish:A,onAbort:O,onStepFinish:H,experimental_context:J,download:K}){this._totalUsage=new kl,this._finishReason=new kl,this._steps=new kl,this.output=v,this.includeRawChunks=_,this.tools=c;let z,U=[];const G=[];let se,ne,ce={},pe=[];const M=[];let R,D={},N={};const y=new TransformStream({async transform(me,Ne){var Ae,ke,tt,Ve;Ne.enqueue(me);const{part:re}=me;if((re.type==="text-delta"||re.type==="reasoning-delta"||re.type==="source"||re.type==="tool-call"||re.type==="tool-result"||re.type==="tool-input-start"||re.type==="tool-input-delta"||re.type==="raw")&&await(x==null?void 0:x({chunk:re})),re.type==="error"&&await k({error:i0(re.error)}),re.type==="text-start"&&(D[re.id]={type:"text",text:"",providerMetadata:re.providerMetadata},U.push(D[re.id])),re.type==="text-delta"){const ze=D[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}ze.text+=re.text,ze.providerMetadata=(Ae=re.providerMetadata)!=null?Ae:ze.providerMetadata}if(re.type==="text-end"){const ze=D[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(ke=re.providerMetadata)!=null?ke:ze.providerMetadata,delete D[re.id]}if(re.type==="reasoning-start"&&(N[re.id]={type:"reasoning",text:"",providerMetadata:re.providerMetadata},U.push(N[re.id])),re.type==="reasoning-delta"){const ze=N[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}ze.text+=re.text,ze.providerMetadata=(tt=re.providerMetadata)!=null?tt:ze.providerMetadata}if(re.type==="reasoning-end"){const ze=N[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(Ve=re.providerMetadata)!=null?Ve:ze.providerMetadata,delete N[re.id]}if(re.type==="file"&&U.push({type:"file",file:re.file}),re.type==="source"&&U.push(re),re.type==="tool-call"&&U.push(re),re.type==="tool-result"&&!re.preliminary&&U.push(re),re.type==="tool-error"&&U.push(re),re.type==="start-step"&&(ce=re.request,pe=re.warnings),re.type==="finish-step"){const ze=fp({content:U,tools:c}),Be=new y0({content:U,finishReason:re.finishReason,usage:re.usage,warnings:pe,request:ce,response:{...re.response,messages:[...G,...ze]},providerMetadata:re.providerMetadata});await(H==null?void 0:H(Be)),b_(pe),M.push(Be),U=[],N={},D={},G.push(...ze),z.resolve()}re.type==="finish"&&(ne=re.totalUsage,se=re.finishReason)},async flush(me){try{if(M.length===0){const tt=new jM({message:"No output generated. Check the stream for errors."});Te._finishReason.reject(tt),Te._totalUsage.reject(tt),Te._steps.reject(tt);return}const Ne=se??"unknown",Ae=ne??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Te._finishReason.resolve(Ne),Te._totalUsage.resolve(Ae),Te._steps.resolve(M);const ke=M[M.length-1];await(A==null?void 0:A({finishReason:Ne,totalUsage:Ae,usage:ke.usage,content:ke.content,text:ke.text,reasoningText:ke.reasoningText,reasoning:ke.reasoning,files:ke.files,sources:ke.sources,toolCalls:ke.toolCalls,staticToolCalls:ke.staticToolCalls,dynamicToolCalls:ke.dynamicToolCalls,toolResults:ke.toolResults,staticToolResults:ke.staticToolResults,dynamicToolResults:ke.dynamicToolResults,request:ke.request,response:ke.response,warnings:ke.warnings,providerMetadata:ke.providerMetadata,steps:M})),R.setAttributes(wr({telemetry:e,attributes:{"ai.response.finishReason":Ne,"ai.response.text":{output:()=>ke.text},"ai.response.toolCalls":{output:()=>{var tt;return(tt=ke.toolCalls)!=null&&tt.length?JSON.stringify(ke.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ke.providerMetadata),"ai.usage.inputTokens":Ae.inputTokens,"ai.usage.outputTokens":Ae.outputTokens,"ai.usage.totalTokens":Ae.totalTokens,"ai.usage.reasoningTokens":Ae.reasoningTokens,"ai.usage.cachedInputTokens":Ae.cachedInputTokens}}))}catch(Ne){me.error(Ne)}finally{R.end()}}}),P=Aj();this.addStream=P.addStream,this.closeStream=P.close;const j=P.stream.getReader();let Q=new ReadableStream({async start(me){me.enqueue({type:"start"})},async pull(me){function Ne(){O==null||O({steps:M}),me.enqueue({type:"abort"}),me.close()}try{const{done:Ae,value:ke}=await j.read();if(Ae){me.close();return}if(s!=null&&s.aborted){Ne();return}me.enqueue(ke)}catch(Ae){na(Ae)&&(s!=null&&s.aborted)?Ne():me.error(Ae)}},cancel(me){return P.stream.cancel(me)}});for(const me of f)Q=Q.pipeThrough(me({tools:c,stopStream(){P.terminate()}}));this.baseStream=Q.pipeThrough(zj(v)).pipeThrough(y);const{maxRetries:ee,retry:Se}=f0({maxRetries:n,abortSignal:s}),de=c0(e),ge=lp(a),vt=l0({model:t,telemetry:e,headers:r,settings:{...ge,maxRetries:ee}}),Te=this;ts({name:"ai.streamText",attributes:wr({telemetry:e,attributes:{...es({operationId:"ai.streamText",telemetry:e}),...vt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:de,endWhenDone:!1,fn:async me=>{R=me;async function Ne({currentStep:Ae,responseMessages:ke,usage:tt}){var Ve,re,ze,Be,Ee;const Qe=Te.includeRawChunks;z=new kl;const or=await o0({system:o,prompt:i,messages:l}),At=[...or.messages,...ke],wt=await(p==null?void 0:p({model:t,steps:M,stepNumber:M.length,messages:At})),ir=El((Ve=wt==null?void 0:wt.model)!=null?Ve:t),Mt=await t0({prompt:{system:(re=wt==null?void 0:wt.system)!=null?re:or.system,messages:(ze=wt==null?void 0:wt.messages)!=null?ze:At},supportedUrls:await ir.supportedUrls,download:K}),{toolChoice:lr,tools:_n}=r0({tools:c,toolChoice:(Be=wt==null?void 0:wt.toolChoice)!=null?Be:u,activeTools:(Ee=wt==null?void 0:wt.activeTools)!=null?Ee:g}),{result:{stream:pa,response:ut,request:br},doStreamSpan:Ur,startTimestampMs:So}=await Se(()=>ts({name:"ai.streamText.doStream",attributes:wr({telemetry:e,attributes:{...es({operationId:"ai.streamText.doStream",telemetry:e}),...vt,"ai.model.provider":ir.provider,"ai.model.id":ir.modelId,"ai.prompt.messages":{input:()=>u0(Mt)},"ai.prompt.tools":{input:()=>_n==null?void 0:_n.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>lr!=null?JSON.stringify(lr):void 0},"gen_ai.system":ir.provider,"gen_ai.request.model":ir.modelId,"gen_ai.request.frequency_penalty":ge.frequencyPenalty,"gen_ai.request.max_tokens":ge.maxOutputTokens,"gen_ai.request.presence_penalty":ge.presencePenalty,"gen_ai.request.stop_sequences":ge.stopSequences,"gen_ai.request.temperature":ge.temperature,"gen_ai.request.top_k":ge.topK,"gen_ai.request.top_p":ge.topP}}),tracer:de,endWhenDone:!1,fn:async we=>({startTimestampMs:w(),doStreamSpan:we,result:await ir.doStream({...ge,tools:_n,toolChoice:lr,responseFormat:v==null?void 0:v.responseFormat,prompt:Mt,providerOptions:h,abortSignal:s,headers:r,includeRawChunks:Qe})})})),Er=jj({tools:c,generatorStream:pa,tracer:de,telemetry:e,system:o,messages:At,repairToolCall:d,abortSignal:s,experimental_context:J}),_p=br??{},rs=[],$o=[];let Po;const ko={};let Ln="unknown",jt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},xo,Io=!0,Sr={id:S(),timestamp:b(),modelId:t.modelId},ns="";Te.addStream(Er.pipeThrough(new TransformStream({async transform(we,Ot){var zn,fa,ha,T;if(we.type==="stream-start"){Po=we.warnings;return}if(Io){const C=w()-So;Io=!1,Ur.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":C}),Ur.setAttributes({"ai.response.msToFirstChunk":C}),Ot.enqueue({type:"start-step",request:_p,warnings:Po??[]})}const $=we.type;switch($){case"text-start":case"text-end":{Ot.enqueue(we);break}case"text-delta":{we.delta.length>0&&(Ot.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),ns+=we.delta);break}case"reasoning-start":case"reasoning-end":{Ot.enqueue(we);break}case"reasoning-delta":{Ot.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{Ot.enqueue(we),rs.push(we);break}case"tool-result":{Ot.enqueue(we),we.preliminary||$o.push(we);break}case"tool-error":{Ot.enqueue(we),$o.push(we);break}case"response-metadata":{Sr={id:(zn=we.id)!=null?zn:Sr.id,timestamp:(fa=we.timestamp)!=null?fa:Sr.timestamp,modelId:(ha=we.modelId)!=null?ha:Sr.modelId};break}case"finish":{jt=we.usage,Ln=we.finishReason,xo=we.providerMetadata;const C=w()-So;Ur.addEvent("ai.stream.finish"),Ur.setAttributes({"ai.response.msToFinish":C,"ai.response.avgOutputTokensPerSecond":1e3*((T=jt.outputTokens)!=null?T:0)/C});break}case"file":{Ot.enqueue(we);break}case"source":{Ot.enqueue(we);break}case"tool-input-start":{ko[we.id]=we.toolName;const C=c==null?void 0:c[we.toolName];(C==null?void 0:C.onInputStart)!=null&&await C.onInputStart({toolCallId:we.id,messages:At,abortSignal:s,experimental_context:J}),Ot.enqueue({...we,dynamic:(C==null?void 0:C.type)==="dynamic"});break}case"tool-input-end":{delete ko[we.id],Ot.enqueue(we);break}case"tool-input-delta":{const C=ko[we.id],q=c==null?void 0:c[C];(q==null?void 0:q.onInputDelta)!=null&&await q.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:At,abortSignal:s,experimental_context:J}),Ot.enqueue(we);break}case"error":{Ot.enqueue(we),Ln="error";break}case"raw":{Qe&&Ot.enqueue(we);break}default:{const C=$;throw new Error(`Unknown chunk type: ${C}`)}}},async flush(we){const Ot=rs.length>0?JSON.stringify(rs):void 0;try{Ur.setAttributes(wr({telemetry:e,attributes:{"ai.response.finishReason":Ln,"ai.response.text":{output:()=>ns},"ai.response.toolCalls":{output:()=>Ot},"ai.response.id":Sr.id,"ai.response.model":Sr.modelId,"ai.response.timestamp":Sr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(xo),"ai.usage.inputTokens":jt.inputTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":jt.reasoningTokens,"ai.usage.cachedInputTokens":jt.cachedInputTokens,"gen_ai.response.finish_reasons":[Ln],"gen_ai.response.id":Sr.id,"gen_ai.response.model":Sr.modelId,"gen_ai.usage.input_tokens":jt.inputTokens,"gen_ai.usage.output_tokens":jt.outputTokens}}))}catch{}finally{Ur.end()}we.enqueue({type:"finish-step",finishReason:Ln,usage:jt,providerMetadata:xo,response:{...Sr,headers:ut==null?void 0:ut.headers}});const zn=d0(tt,jt);await z.promise;const fa=rs.filter(T=>T.providerExecuted!==!0),ha=$o.filter(T=>T.providerExecuted!==!0);if(fa.length>0&&ha.length===fa.length&&!await _0({stopConditions:m,steps:M})){ke.push(...fp({content:M[M.length-1].content,tools:c}));try{await Ne({currentStep:Ae+1,responseMessages:ke,usage:zn})}catch(T){we.enqueue({type:"error",error:T}),Te.closeStream()}}else we.enqueue({type:"finish",finishReason:Ln,totalUsage:zn}),Te.closeStream()}})))}await Ne({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(me=>{Te.addStream(new ReadableStream({start(Ne){Ne.enqueue({type:"error",error:me}),Ne.close()}})),Te.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 Pl(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return Pl(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await Nj({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new __;return Pl(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=Wa}={}){const c=e!=null?kj({originalMessages:t,responseMessageId:e}):void 0,u={},f=d=>{var m,v;const h=u[d];return((v=(m=this.tools)==null?void 0:m[h])==null?void 0:v.type)==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(d,m)=>{const v=a==null?void 0:a({part:d}),h=d.type;switch(h){case"text-start":{m.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{m.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{n&&m.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{m.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&m.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 p=f(d.id);m.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const p=f(d.toolCallId);d.invalid?m.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}:{},...p!=null?{dynamic:p}:{},errorText:l(d.error)}):m.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}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=f(d.toolCallId);m.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=f(d.toolCallId);m.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{m.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{o&&m.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&m.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{m.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const p=h;throw new Error(`Unknown chunk type: ${p}`)}}v!=null&&h!=="start"&&h!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:v})}}));return Pl(Rj({stream:g,messageId:c??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c,...u}={}){Oj({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(t,e){$j({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...c}={}){return Pj({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...c})}toTextStreamResponse(t){return Sj({textStream:this.textStream,...t})}};lo({prefix:"aiobj",size:24}),lo({prefix:"aiobj",size:24});var qj={};IM(qj,{object:()=>Zj,text:()=>Fj});var Fj=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),Zj=({schema:t})=>{const e=vl(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await k0(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await sa({text:r});if(!n.success)throw new O_({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await jr({value:n.value,schema:e});if(!s.success)throw new O_({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},Vj=Qa({name:E(),version:E()}),mp=Qa({_meta:xt(I({}).loose())}),bo=mp,Hj=I({method:E(),params:xt(mp)}),Bj=Qa({experimental:xt(I({}).loose()),logging:xt(I({}).loose()),prompts:xt(Qa({listChanged:xt(Pt())})),resources:xt(Qa({subscribe:xt(Pt()),listChanged:xt(Pt())})),tools:xt(Qa({listChanged:xt(Pt())}))});bo.extend({protocolVersion:E(),capabilities:Bj,serverInfo:Vj,instructions:xt(E())});var Jj=bo.extend({nextCursor:xt(E())}),Gj=I({name:E(),description:xt(E()),inputSchema:I({type:W("object"),properties:xt(I({}).loose())}).loose()}).loose();Jj.extend({tools:oe(Gj)});var Kj=I({type:W("text"),text:E()}).loose(),Wj=I({type:W("image"),data:ay(),mimeType:E()}).loose(),T0=I({uri:E(),mimeType:xt(E())}).loose(),Qj=T0.extend({text:E()}),Yj=T0.extend({blob:ay()}),Xj=I({type:W("resource"),resource:He([Qj,Yj])}).loose();bo.extend({content:oe(He([Kj,Wj,Xj])),isError:Pt().default(!1).optional()}).or(bo.extend({toolResult:Mr()}));var xl="2.0",e9=I({jsonrpc:W(xl),id:He([E(),Z().int()])}).merge(Hj).strict(),t9=I({jsonrpc:W(xl),id:He([E(),Z().int()]),result:bo}).strict(),r9=I({jsonrpc:W(xl),id:He([E(),Z().int()]),error:I({code:Z().int(),message:E(),data:xt(Mr())})}).strict(),n9=I({jsonrpc:W(xl)}).merge(I({method:E(),params:xt(mp)})).strict();He([e9,n9,t9,r9]);var vp=I({error:I({message:E(),type:E().nullish(),param:_r().nullish(),code:He([E(),Z()]).nullish()})}),sn=oa({errorSchema:vp,errorToMessage:t=>t.error.message});function a9({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,c,u;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const f=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${f};base64,${ia(o.data)}`,detail:(c=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new Ar({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:ia(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:ia(o.data),format:"mp3"}};default:throw new Ar({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new Ar({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(u=o.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${ia(o.data)}`}}}else throw new Ar({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function C0({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 R0(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 s9=_t(()=>De(I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({message:I({role:W("assistant").nullish(),content:E().nullish(),tool_calls:oe(I({id:E().nullish(),type:W("function"),function:I({name:E(),arguments:E()})})).nullish(),annotations:oe(I({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()})).nullish()}),index:Z(),logprobs:I({content:oe(I({token:E(),logprob:Z(),top_logprobs:oe(I({token:E(),logprob:Z()}))})).nullish()}).nullish(),finish_reason:E().nullish()})),usage:I({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:I({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:I({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish()}))),o9=_t(()=>De(He([I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({delta:I({role:ht(["assistant"]).nullish(),content:E().nullish(),tool_calls:oe(I({index:Z(),id:E().nullish(),type:W("function").nullish(),function:I({name:E().nullish(),arguments:E().nullish()})})).nullish(),annotations:oe(I({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()})).nullish()}).nullish(),logprobs:I({content:oe(I({token:E(),logprob:Z(),top_logprobs:oe(I({token:E(),logprob:Z()}))})).nullish()}).nullish(),finish_reason:E().nullish(),index:Z()})),usage:I({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:I({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:I({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish()}),vp]))),i9=_t(()=>De(I({logitBias:kt(pN(),Z()).optional(),logprobs:He([Pt(),Z()]).optional(),parallelToolCalls:Pt().optional(),user:E().optional(),reasoningEffort:ht(["minimal","low","medium","high"]).optional(),maxCompletionTokens:Z().optional(),store:Pt().optional(),metadata:kt(E().max(64),E().max(512)).optional(),prediction:kt(E(),_r()).optional(),structuredOutputs:Pt().optional(),serviceTier:ht(["auto","flex","priority","default"]).optional(),strictJsonSchema:Pt().optional(),textVerbosity:ht(["low","medium","high"]).optional(),promptCacheKey:E().optional(),safetyIdentifier:E().optional()})));function l9({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;default:n.push({type:"unsupported-tool",tool:i});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:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new Ar({functionality:`tool choice type: ${i}`})}}}var c9=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:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:f,providerOptions:g}){var d,m,v,h;const p=[],_=(d=await tn({provider:"openai",providerOptions:g,schema:i9}))!=null?d:{},w=(m=_.structuredOutputs)!=null?m:!0;n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!w&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:S}=a9({prompt:t,systemMessageMode:p9(this.modelId)});p.push(...S);const x=(v=_.strictJsonSchema)!=null?v:!1,k={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?w&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:x,name:(h=l.name)!=null?h:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,safety_identifier:_.safetyIdentifier,messages:b};O0(this.modelId)?(k.temperature!=null&&(k.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!u9(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),_.serviceTier==="priority"&&!d9(this.modelId)&&(p.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"}),k.service_tier=void 0);const{tools:A,toolChoice:O,toolWarnings:H}=l9({tools:u,toolChoice:f,structuredOutputs:w,strictJsonSchema:x});return{args:{...k,tools:A,tool_choice:O},warnings:[...p,...H]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,m;const{args:v,warnings:h}=await this.getArgs(t),{responseHeaders:p,value:_,rawValue:w}=await sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:v,failedResponseHandler:sn,successfulResponseHandler:Dr(s9),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=_.choices[0],S=[],x=b.message.content;x!=null&&x.length>0&&S.push({type:"text",text:x});for(const H of(e=b.message.tool_calls)!=null?e:[])S.push({type:"tool-call",toolCallId:(r=H.id)!=null?r:ar(),toolName:H.function.name,input:H.function.arguments});for(const H of(a=b.message.annotations)!=null?a:[])S.push({type:"source",sourceType:"url",id:ar(),url:H.url,title:H.title});const k=(n=_.usage)==null?void 0:n.completion_tokens_details,A=(s=_.usage)==null?void 0:s.prompt_tokens_details,O={openai:{}};return(k==null?void 0:k.accepted_prediction_tokens)!=null&&(O.openai.acceptedPredictionTokens=k==null?void 0:k.accepted_prediction_tokens),(k==null?void 0:k.rejected_prediction_tokens)!=null&&(O.openai.rejectedPredictionTokens=k==null?void 0:k.rejected_prediction_tokens),((o=b.logprobs)==null?void 0:o.content)!=null&&(O.openai.logprobs=b.logprobs.content),{content:S,finishReason:R0(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(g=(f=_.usage)==null?void 0:f.total_tokens)!=null?g:void 0,reasoningTokens:(d=k==null?void 0:k.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(m=A==null?void 0:A.cached_tokens)!=null?m:void 0},request:{body:v},response:{...C0(_),headers:p,body:w},warnings:h,providerMetadata:O}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:a,failedResponseHandler:sn,successfulResponseHandler:uo(o9),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,d){var m,v,h,p,_,w,b,S,x,k,A,O,H,J,K,z,U,G,se,ne,ce,pe,M,R;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){i="error",d.enqueue({type:"error",error:g.error});return}const D=g.value;if("error"in D){i="error",d.enqueue({type:"error",error:D.error});return}c&&(c=!1,d.enqueue({type:"response-metadata",...C0(D)})),D.usage!=null&&(l.inputTokens=(m=D.usage.prompt_tokens)!=null?m:void 0,l.outputTokens=(v=D.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(h=D.usage.total_tokens)!=null?h:void 0,l.reasoningTokens=(_=(p=D.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(w=D.usage.prompt_tokens_details)==null?void 0:w.cached_tokens)!=null?b:void 0,((S=D.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(x=D.usage.completion_tokens_details)==null?void 0:x.accepted_prediction_tokens),((k=D.usage.completion_tokens_details)==null?void 0:k.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(A=D.usage.completion_tokens_details)==null?void 0:A.rejected_prediction_tokens));const N=D.choices[0];if((N==null?void 0:N.finish_reason)!=null&&(i=R0(N.finish_reason)),((O=N==null?void 0:N.logprobs)==null?void 0:O.content)!=null&&(f.openai.logprobs=N.logprobs.content),(N==null?void 0:N.delta)==null)return;const y=N.delta;if(y.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:y.content})),y.tool_calls!=null)for(const P of y.tool_calls){const j=P.index;if(o[j]==null){if(P.type!=="function")throw new Xs({data:P,message:"Expected 'function' type."});if(P.id==null)throw new Xs({data:P,message:"Expected 'id' to be a string."});if(((H=P.function)==null?void 0:H.name)==null)throw new Xs({data:P,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:P.id,toolName:P.function.name}),o[j]={id:P.id,type:"function",function:{name:P.function.name,arguments:(J=P.function.arguments)!=null?J:""},hasFinished:!1};const ee=o[j];((K=ee.function)==null?void 0:K.name)!=null&&((z=ee.function)==null?void 0:z.arguments)!=null&&(ee.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:ee.id,delta:ee.function.arguments}),hl(ee.function.arguments)&&(d.enqueue({type:"tool-input-end",id:ee.id}),d.enqueue({type:"tool-call",toolCallId:(U=ee.id)!=null?U:ar(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0));continue}const Q=o[j];Q.hasFinished||(((G=P.function)==null?void 0:G.arguments)!=null&&(Q.function.arguments+=(ne=(se=P.function)==null?void 0:se.arguments)!=null?ne:""),d.enqueue({type:"tool-input-delta",id:Q.id,delta:(ce=P.function.arguments)!=null?ce:""}),((pe=Q.function)==null?void 0:pe.name)!=null&&((M=Q.function)==null?void 0:M.arguments)!=null&&hl(Q.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Q.id}),d.enqueue({type:"tool-call",toolCallId:(R=Q.id)!=null?R:ar(),toolName:Q.function.name,input:Q.function.arguments}),Q.hasFinished=!0))}if(y.annotations!=null)for(const P of y.annotations)d.enqueue({type:"source",sourceType:"url",id:ar(),url:P.url,title:P.title})},flush(g){u&&g.enqueue({type:"text-end",id:"0"}),g.enqueue({type:"finish",finishReason:i,usage:l,...f!=null?{providerMetadata:f}:{}})}})),request:{body:a},response:{headers:n}}}};function O0(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function u9(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function d9(t){return 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")}function p9(t){var e,r;return O0(t)?(r=(e=f9[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var f9={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function h9({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
573
+ `)}})}},h1={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function SE({status:e,statusText:t,headers:n,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new f1);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Pi(n,h1)})}function CE({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t=="function"?t():t}function $E(e){return e.type.startsWith("data-")}function m1(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?n[r]=m1(s,o):n[r]=o}return n}function kE(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,u){switch(l){case'"':{n=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const h=e.substring(r,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let i=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(r,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function g1(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Or({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Or({text:kE(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function yd(e){return e.type.startsWith("tool-")}function y1(e){return e.type.split("-").slice(1).join("-")}function TE({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function xE({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await r(async({state:c,write:u})=>{var h,y,f,g;function v(b){const P=c.message.parts.filter(yd).find(E=>E.toolCallId===b);if(P==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return P}function m(b){const P=c.message.parts.filter(E=>E.type==="dynamic-tool").find(E=>E.toolCallId===b);if(P==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return P}function d(b){var T;const P=c.message.parts.find(U=>yd(U)&&U.toolCallId===b.toolCallId),E=b,Z=P;P!=null?(P.state=b.state,Z.input=E.input,Z.output=E.output,Z.errorText=E.errorText,Z.rawInput=E.rawInput,Z.preliminary=E.preliminary,Z.providerExecuted=(T=E.providerExecuted)!=null?T:P.providerExecuted,E.providerMetadata!=null&&P.state==="input-available"&&(P.callProviderMetadata=E.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:E.input,output:E.output,rawInput:E.rawInput,errorText:E.errorText,providerExecuted:E.providerExecuted,preliminary:E.preliminary,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}function w(b){var T;const P=c.message.parts.find(U=>U.type==="dynamic-tool"&&U.toolCallId===b.toolCallId),E=b,Z=P;P!=null?(P.state=b.state,Z.toolName=b.toolName,Z.input=E.input,Z.output=E.output,Z.errorText=E.errorText,Z.rawInput=(T=E.rawInput)!=null?T:Z.rawInput,Z.preliminary=E.preliminary,E.providerMetadata!=null&&P.state==="input-available"&&(P.callProviderMetadata=E.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function _(b){if(b!=null){const T=c.message.metadata!=null?m1(c.message.metadata,b):b;t!=null&&await Zu({value:T,schema:t}),c.message.metadata=T}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(y=i.providerMetadata)!=null?y:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(g=i.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(yd);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):d({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:T}=await g1(b.text);b.dynamic?w({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:T}):d({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:T}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):d({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):d({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=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);d({toolCallId:i.toolCallId,toolName:y1(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=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText})}else{const b=v(i.toolCallId);d({toolCallId:i.toolCallId,toolName:y1(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o==null||o(new Error(i.errorText));break}default:if($E(i)){(n==null?void 0:n[i.type])!=null&&await Zu({value:i.data,schema:n[i.type]});const b=i;if(b.transient){a==null||a(b);break}const T=b.id!=null?c.message.parts.find(P=>b.type===P.type&&b.id===P.id):void 0;T!=null?T.data=b.data:c.message.parts.push(b),a==null||a(b),u()}}l.enqueue(i)})}}))}function EE({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:o}){let s=t==null?void 0:t[t.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(y,f){if(y.type==="start"){const g=y;g.messageId==null&&e!=null&&(g.messageId=e)}y.type==="abort"&&(a=!0),f.enqueue(y)}}));if(n==null)return i;const l=TE({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async y=>{await y({state:l,write:()=>{}})};let u=!1;const h=async()=>{if(u||!n)return;u=!0;const y=l.message.id===(s==null?void 0:s.id);await n({isAborted:a,isContinuation:y,responseMessage:l.message,messages:[...y?t.slice(0,-1):t,l.message]})};return xE({stream:i,runUpdateMessageJob:c,onError:r}).pipeThrough(new TransformStream({transform(y,f){f.enqueue(y)},async cancel(){await h()},async flush(){await h()}}))}function IE({response:e,status:t,statusText:n,headers:r,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new f1);if(s){const[i,l]=a.tee();a=i,s({stream:l})}p1({response:e,status:t,statusText:n,headers:Object.fromEntries(Pi(r,h1).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ri(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let r=!1;async function o(s){var a;r=!0;try{s&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(r)return{done:!0,value:void 0};const{done:s,value:a}=await n.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function PE({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}function v1(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function RE(){let e=[],t=null,n=!1,r=v1();const o=()=>{n=!0,r.resolve(),e.forEach(a=>a.cancel()),e=[],t==null||t.close()},s=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return r=v1(),await r.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():n&&(t==null||t.close())):t==null||t.enqueue(a)}catch(a){t==null||t.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&(t==null||t.close())},terminate:o}}var Oi=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function OE(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function NE({tools:e,generatorStream:t,tracer:n,telemetry:r,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(d){c=d}}),h=new Set,y=new Map;let f=!1,g;function v(){f&&h.size===0&&(g!=null&&c.enqueue(g),c.close())}const m=new TransformStream({async transform(d,w){const _=d.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":{w.enqueue(d);break}case"file":{w.enqueue({type:"file",file:new hE({data:d.data,mediaType:d.mediaType})});break}case"finish":{g={type:"finish",finishReason:d.finishReason,usage:d.usage,providerMetadata:d.providerMetadata};break}case"tool-call":{try{const b=await a1({toolCall:d,tools:e,repairToolCall:i,system:o,messages:s});if(w.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Du(b.error),dynamic:!0});break}const T=e[b.toolName];if(y.set(b.toolCallId,b.input),T.onInputAvailable!=null&&await T.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}),T.execute!=null&&b.providerExecuted!==!0){const P=c$();h.add(P),So({name:"ai.toolCall",attributes:Ht({telemetry:r,attributes:{...bo({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:n,fn:async E=>{let Z;try{const U=h2({execute:T.execute.bind(T),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const W of U)c.enqueue({...b,type:"tool-result",output:W.output,...W.type==="preliminary"&&{preliminary:!0}}),W.type==="final"&&(Z=W.output)}catch(U){pd(E,U),c.enqueue({...b,type:"tool-error",error:U}),h.delete(P),v();return}h.delete(P),v();try{E.setAttributes(Ht({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(Z)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=d.toolName;d.isError?c.enqueue({type:"tool-error",toolCallId:d.toolCallId,toolName:b,input:y.get(d.toolCallId),providerExecuted:d.providerExecuted,error:d.result}):w.enqueue({type:"tool-result",toolCallId:d.toolCallId,toolName:b,input:y.get(d.toolCallId),output:d.result,providerExecuted:d.providerExecuted});break}default:{const b=_;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){f=!0,v()}});return new ReadableStream({async start(d){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(w){d.enqueue(w)},close(){}})),u.pipeTo(new WritableStream({write(w){d.enqueue(w)},close(){d.close()}}))])}})}var AE=Rs({prefix:"aitxt",size:24});function ME({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=hd(1),experimental_output:u,experimental_telemetry:h,prepareStep:y,providerOptions:f,experimental_activeTools:g,activeTools:v=g,experimental_repairToolCall:m,experimental_transform:d,experimental_download:w,includeRawChunks:_=!1,onChunk:b,onError:T=({error:H})=>{console.error(H)},onFinish:P,onAbort:E,onStepFinish:Z,experimental_context:U,_internal:{now:W=OE,generateId:V=AE,currentDate:B=()=>new Date}={},...J}){return new LE({model:xi(e),telemetry:h,headers:l,settings:J,maxRetries:a,abortSignal:i,system:r,prompt:o,messages:s,tools:t,toolChoice:n,transforms:fd(d),activeTools:v,repairToolCall:m,stopConditions:fd(c),output:u,providerOptions:f,prepareStep:y,includeRawChunks:_,onChunk:b,onError:T,onFinish:P,onAbort:E,onStepFinish:Z,now:W,currentDate:B,generateId:V,experimental_context:U,download:w})}function jE(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,n="",r="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:r},partialOutput:i}),r=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&r.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){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"){r.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}n+=a.text,r+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const c=JSON.stringify(l.partial);c!==o&&(s({controller:i,partialOutput:l.partial}),o=c)}}})}var LE=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:c,toolChoice:u,transforms:h,activeTools:y,repairToolCall:f,stopConditions:g,output:v,providerOptions:m,prepareStep:d,includeRawChunks:w,now:_,currentDate:b,generateId:T,onChunk:P,onError:E,onFinish:Z,onAbort:U,onStepFinish:W,experimental_context:V,download:B}){this._totalUsage=new Oi,this._finishReason=new Oi,this._steps=new Oi,this.output=v,this.includeRawChunks=w,this.tools=c;let J,H=[];const ue=[];let Ce,ae,ye={},he=[];const L=[];let x,M={},R={};const $=new TransformStream({async transform($e,Pe){var Ge,we,nt,Rt;Pe.enqueue($e);const{part:G}=$e;if((G.type==="text-delta"||G.type==="reasoning-delta"||G.type==="source"||G.type==="tool-call"||G.type==="tool-result"||G.type==="tool-input-start"||G.type==="tool-input-delta"||G.type==="raw")&&await(P==null?void 0:P({chunk:G})),G.type==="error"&&await E({error:Yg(G.error)}),G.type==="text-start"&&(M[G.id]={type:"text",text:"",providerMetadata:G.providerMetadata},H.push(M[G.id])),G.type==="text-delta"){const Ae=M[G.id];if(Ae==null){Pe.enqueue({part:{type:"error",error:`text part ${G.id} not found`},partialOutput:void 0});return}Ae.text+=G.text,Ae.providerMetadata=(Ge=G.providerMetadata)!=null?Ge:Ae.providerMetadata}if(G.type==="text-end"){const Ae=M[G.id];if(Ae==null){Pe.enqueue({part:{type:"error",error:`text part ${G.id} not found`},partialOutput:void 0});return}Ae.providerMetadata=(we=G.providerMetadata)!=null?we:Ae.providerMetadata,delete M[G.id]}if(G.type==="reasoning-start"&&(R[G.id]={type:"reasoning",text:"",providerMetadata:G.providerMetadata},H.push(R[G.id])),G.type==="reasoning-delta"){const Ae=R[G.id];if(Ae==null){Pe.enqueue({part:{type:"error",error:`reasoning part ${G.id} not found`},partialOutput:void 0});return}Ae.text+=G.text,Ae.providerMetadata=(nt=G.providerMetadata)!=null?nt:Ae.providerMetadata}if(G.type==="reasoning-end"){const Ae=R[G.id];if(Ae==null){Pe.enqueue({part:{type:"error",error:`reasoning part ${G.id} not found`},partialOutput:void 0});return}Ae.providerMetadata=(Rt=G.providerMetadata)!=null?Rt:Ae.providerMetadata,delete R[G.id]}if(G.type==="file"&&H.push({type:"file",file:G.file}),G.type==="source"&&H.push(G),G.type==="tool-call"&&H.push(G),G.type==="tool-result"&&!G.preliminary&&H.push(G),G.type==="tool-error"&&H.push(G),G.type==="start-step"&&(ye=G.request,he=G.warnings),G.type==="finish-step"){const Ae=gd({content:H,tools:c}),Gt=new l1({content:H,finishReason:G.finishReason,usage:G.usage,warnings:he,request:ye,response:{...G.response,messages:[...ue,...Ae]},providerMetadata:G.providerMetadata});await(W==null?void 0:W(Gt)),ug(he),L.push(Gt),H=[],R={},M={},ue.push(...Ae),J.resolve()}G.type==="finish"&&(ae=G.totalUsage,Ce=G.finishReason)},async flush($e){try{if(L.length===0){const nt=new Nx({message:"No output generated. Check the stream for errors."});He._finishReason.reject(nt),He._totalUsage.reject(nt),He._steps.reject(nt);return}const Pe=Ce??"unknown",Ge=ae??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};He._finishReason.resolve(Pe),He._totalUsage.resolve(Ge),He._steps.resolve(L);const we=L[L.length-1];await(Z==null?void 0:Z({finishReason:Pe,totalUsage:Ge,usage:we.usage,content:we.content,text:we.text,reasoningText:we.reasoningText,reasoning:we.reasoning,files:we.files,sources:we.sources,toolCalls:we.toolCalls,staticToolCalls:we.staticToolCalls,dynamicToolCalls:we.dynamicToolCalls,toolResults:we.toolResults,staticToolResults:we.staticToolResults,dynamicToolResults:we.dynamicToolResults,request:we.request,response:we.response,warnings:we.warnings,providerMetadata:we.providerMetadata,steps:L})),x.setAttributes(Ht({telemetry:t,attributes:{"ai.response.finishReason":Pe,"ai.response.text":{output:()=>we.text},"ai.response.toolCalls":{output:()=>{var nt;return(nt=we.toolCalls)!=null&&nt.length?JSON.stringify(we.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(we.providerMetadata),"ai.usage.inputTokens":Ge.inputTokens,"ai.usage.outputTokens":Ge.outputTokens,"ai.usage.totalTokens":Ge.totalTokens,"ai.usage.reasoningTokens":Ge.reasoningTokens,"ai.usage.cachedInputTokens":Ge.cachedInputTokens}}))}catch(Pe){$e.error(Pe)}finally{x.end()}}}),k=RE();this.addStream=k.addStream,this.closeStream=k.close;const S=k.stream.getReader();let z=new ReadableStream({async start($e){$e.enqueue({type:"start"})},async pull($e){function Pe(){U==null||U({steps:L}),$e.enqueue({type:"abort"}),$e.close()}try{const{done:Ge,value:we}=await S.read();if(Ge){$e.close();return}if(s!=null&&s.aborted){Pe();return}$e.enqueue(we)}catch(Ge){Pr(Ge)&&(s!=null&&s.aborted)?Pe():$e.error(Ge)}},cancel($e){return k.stream.cancel($e)}});for(const $e of h)z=z.pipeThrough($e({tools:c,stopStream(){k.terminate()}}));this.baseStream=z.pipeThrough(jE(v)).pipeThrough($);const{maxRetries:D,retry:ve}=r1({maxRetries:o,abortSignal:s}),ce=Xg(t),Te=dd(r),Wt=Qg({model:e,telemetry:t,headers:n,settings:{...Te,maxRetries:D}}),He=this;So({name:"ai.streamText",attributes:Ht({telemetry:t,attributes:{...bo({operationId:"ai.streamText",telemetry:t}),...Wt,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:ce,endWhenDone:!1,fn:async $e=>{x=$e;async function Pe({currentStep:Ge,responseMessages:we,usage:nt}){var Rt,G,Ae,Gt,Me;const Ot=He.includeRawChunks;J=new Oi;const Fn=await Kg({system:a,prompt:i,messages:l}),Nt=[...Fn.messages,...we],dt=await(d==null?void 0:d({model:e,steps:L,stepNumber:L.length,messages:Nt})),Kt=xi((Rt=dt==null?void 0:dt.model)!=null?Rt:e),fr=await Bg({prompt:{system:(G=dt==null?void 0:dt.system)!=null?G:Fn.system,messages:(Ae=dt==null?void 0:dt.messages)!=null?Ae:Nt},supportedUrls:await Kt.supportedUrls,download:B}),{toolChoice:hr,tools:$o}=Hg({tools:c,toolChoice:(Gt=dt==null?void 0:dt.toolChoice)!=null?Gt:u,activeTools:(Me=dt==null?void 0:dt.activeTools)!=null?Me:y}),{result:{stream:Li,response:st,request:Bn},doStreamSpan:Hn,startTimestampMs:ry}=await ve(()=>So({name:"ai.streamText.doStream",attributes:Ht({telemetry:t,attributes:{...bo({operationId:"ai.streamText.doStream",telemetry:t}),...Wt,"ai.model.provider":Kt.provider,"ai.model.id":Kt.modelId,"ai.prompt.messages":{input:()=>e1(fr)},"ai.prompt.tools":{input:()=>$o==null?void 0:$o.map(oe=>JSON.stringify(oe))},"ai.prompt.toolChoice":{input:()=>hr!=null?JSON.stringify(hr):void 0},"gen_ai.system":Kt.provider,"gen_ai.request.model":Kt.modelId,"gen_ai.request.frequency_penalty":Te.frequencyPenalty,"gen_ai.request.max_tokens":Te.maxOutputTokens,"gen_ai.request.presence_penalty":Te.presencePenalty,"gen_ai.request.stop_sequences":Te.stopSequences,"gen_ai.request.temperature":Te.temperature,"gen_ai.request.top_k":Te.topK,"gen_ai.request.top_p":Te.topP}}),tracer:ce,endWhenDone:!1,fn:async oe=>({startTimestampMs:_(),doStreamSpan:oe,result:await Kt.doStream({...Te,tools:$o,toolChoice:hr,responseFormat:v==null?void 0:v.responseFormat,prompt:fr,providerOptions:m,abortSignal:s,headers:n,includeRawChunks:Ot})})})),tO=NE({tools:c,generatorStream:Li,tracer:ce,telemetry:t,system:a,messages:Nt,repairToolCall:f,abortSignal:s,experimental_context:V}),nO=Bn??{},zi=[],Ed=[];let Id;const Pd={};let ko="unknown",mn={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Rd,oy=!0,An={id:T(),timestamp:b(),modelId:e.modelId},sy="";He.addStream(tO.pipeThrough(new TransformStream({async transform(oe,pt){var Ws,Gs,Di,Jn;if(oe.type==="stream-start"){Id=oe.warnings;return}if(oy){const Ct=_()-ry;oy=!1,Hn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Ct}),Hn.setAttributes({"ai.response.msToFirstChunk":Ct}),pt.enqueue({type:"start-step",request:nO,warnings:Id??[]})}const ay=oe.type;switch(ay){case"text-start":case"text-end":{pt.enqueue(oe);break}case"text-delta":{oe.delta.length>0&&(pt.enqueue({type:"text-delta",id:oe.id,text:oe.delta,providerMetadata:oe.providerMetadata}),sy+=oe.delta);break}case"reasoning-start":case"reasoning-end":{pt.enqueue(oe);break}case"reasoning-delta":{pt.enqueue({type:"reasoning-delta",id:oe.id,text:oe.delta,providerMetadata:oe.providerMetadata});break}case"tool-call":{pt.enqueue(oe),zi.push(oe);break}case"tool-result":{pt.enqueue(oe),oe.preliminary||Ed.push(oe);break}case"tool-error":{pt.enqueue(oe),Ed.push(oe);break}case"response-metadata":{An={id:(Ws=oe.id)!=null?Ws:An.id,timestamp:(Gs=oe.timestamp)!=null?Gs:An.timestamp,modelId:(Di=oe.modelId)!=null?Di:An.modelId};break}case"finish":{mn=oe.usage,ko=oe.finishReason,Rd=oe.providerMetadata;const Ct=_()-ry;Hn.addEvent("ai.stream.finish"),Hn.setAttributes({"ai.response.msToFinish":Ct,"ai.response.avgOutputTokensPerSecond":1e3*((Jn=mn.outputTokens)!=null?Jn:0)/Ct});break}case"file":{pt.enqueue(oe);break}case"source":{pt.enqueue(oe);break}case"tool-input-start":{Pd[oe.id]=oe.toolName;const Ct=c==null?void 0:c[oe.toolName];(Ct==null?void 0:Ct.onInputStart)!=null&&await Ct.onInputStart({toolCallId:oe.id,messages:Nt,abortSignal:s,experimental_context:V}),pt.enqueue({...oe,dynamic:(Ct==null?void 0:Ct.type)==="dynamic"});break}case"tool-input-end":{delete Pd[oe.id],pt.enqueue(oe);break}case"tool-input-delta":{const Ct=Pd[oe.id],Od=c==null?void 0:c[Ct];(Od==null?void 0:Od.onInputDelta)!=null&&await Od.onInputDelta({inputTextDelta:oe.delta,toolCallId:oe.id,messages:Nt,abortSignal:s,experimental_context:V}),pt.enqueue(oe);break}case"error":{pt.enqueue(oe),ko="error";break}case"raw":{Ot&&pt.enqueue(oe);break}default:{const Ct=ay;throw new Error(`Unknown chunk type: ${Ct}`)}}},async flush(oe){const pt=zi.length>0?JSON.stringify(zi):void 0;try{Hn.setAttributes(Ht({telemetry:t,attributes:{"ai.response.finishReason":ko,"ai.response.text":{output:()=>sy},"ai.response.toolCalls":{output:()=>pt},"ai.response.id":An.id,"ai.response.model":An.modelId,"ai.response.timestamp":An.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Rd),"ai.usage.inputTokens":mn.inputTokens,"ai.usage.outputTokens":mn.outputTokens,"ai.usage.totalTokens":mn.totalTokens,"ai.usage.reasoningTokens":mn.reasoningTokens,"ai.usage.cachedInputTokens":mn.cachedInputTokens,"gen_ai.response.finish_reasons":[ko],"gen_ai.response.id":An.id,"gen_ai.response.model":An.modelId,"gen_ai.usage.input_tokens":mn.inputTokens,"gen_ai.usage.output_tokens":mn.outputTokens}}))}catch{}finally{Hn.end()}oe.enqueue({type:"finish-step",finishReason:ko,usage:mn,providerMetadata:Rd,response:{...An,headers:st==null?void 0:st.headers}});const Ws=t1(nt,mn);await J.promise;const Gs=zi.filter(Jn=>Jn.providerExecuted!==!0),Di=Ed.filter(Jn=>Jn.providerExecuted!==!0);if(Gs.length>0&&Di.length===Gs.length&&!await c1({stopConditions:g,steps:L})){we.push(...gd({content:L[L.length-1].content,tools:c}));try{await Pe({currentStep:Ge+1,responseMessages:we,usage:Ws})}catch(Jn){oe.enqueue({type:"error",error:Jn}),He.closeStream()}}else oe.enqueue({type:"finish",finishReason:ko,totalUsage:Ws}),He.closeStream()}})))}await Pe({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch($e=>{He.addStream(new ReadableStream({start(Pe){Pe.enqueue({type:"error",error:$e}),Pe.close()}})),He.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ri(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ri(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await PE({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(n){(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new lg;return Ri(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=_o}={}){const c=t!=null?CE({originalMessages:e,responseMessageId:t}):void 0,u={},h=f=>{var g,v;const m=u[f];return((v=(g=this.tools)==null?void 0:g[m])==null?void 0:v.type)==="dynamic"?!0:void 0},y=this.fullStream.pipeThrough(new TransformStream({transform:async(f,g)=>{const v=r==null?void 0:r({part:f}),m=f.type;switch(m){case"text-start":{g.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{o&&g.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`});break}case"source":{s&&f.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),s&&f.sourceType==="document"&&g.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{u[f.id]=f.toolName;const d=h(f.id);g.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...d!=null?{dynamic:d}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{u[f.toolCallId]=f.toolName;const d=h(f.toolCallId);f.invalid?g.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...d!=null?{dynamic:d}:{},errorText:l(f.error)}):g.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...d!=null?{dynamic:d}:{}});break}case"tool-result":{const d=h(f.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},...d!=null?{dynamic:d}:{}});break}case"tool-error":{const d=h(f.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:l(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...d!=null?{dynamic:d}:{}});break}case"error":{g.enqueue({type:"error",errorText:l(f.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&g.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{g.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{const d=m;throw new Error(`Unknown chunk type: ${d}`)}}v!=null&&m!=="start"&&m!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:v})}}));return Ri(EE({stream:y,messageId:c??(t==null?void 0:t()),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){IE({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){bE({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return SE({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return wE({textStream:this.textStream,...e})}};Rs({prefix:"aiobj",size:24}),Rs({prefix:"aiobj",size:24});var zE={};Cx(zE,{object:()=>ZE,text:()=>DE});var DE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),ZE=({schema:e})=>{const t=Ci(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await g1(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Or({text:n});if(!o.success)throw new Cg({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await ur({value:o.value,schema:t});if(!s.success)throw new Cg({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},_1="2025-06-18",UE=[_1,"2025-03-26","2024-11-05"],qE=lt({name:p(),version:p()}),vd=lt({_meta:te(C({}).loose())}),Fs=vd,VE=C({method:p(),params:te(vd)}),FE=lt({experimental:te(C({}).loose()),logging:te(C({}).loose()),prompts:te(lt({listChanged:te(le())})),resources:te(lt({subscribe:te(le()),listChanged:te(le())})),tools:te(lt({listChanged:te(le())}))}),BE=Fs.extend({protocolVersion:p(),capabilities:FE,serverInfo:qE,instructions:te(p())}),HE=Fs.extend({nextCursor:te(p())}),JE=C({name:p(),description:te(p()),inputSchema:C({type:N("object"),properties:te(C({}).loose())}).loose()}).loose(),WE=HE.extend({tools:A(JE)}),GE=C({type:N("text"),text:p()}).loose(),KE=C({type:N("image"),data:ch(),mimeType:p()}).loose(),w1=C({uri:p(),mimeType:te(p())}).loose(),YE=w1.extend({text:p()}),QE=w1.extend({blob:ch()}),XE=C({type:N("resource"),resource:ne([YE,QE])}).loose(),eI=Fs.extend({content:A(ne([GE,KE,XE])),isError:le().default(!1).optional()}).or(Fs.extend({toolResult:Ze()})),Ni="2.0",tI=C({jsonrpc:N(Ni),id:ne([p(),O().int()])}).merge(VE).strict(),nI=C({jsonrpc:N(Ni),id:ne([p(),O().int()]),result:Fs}).strict(),rI=C({jsonrpc:N(Ni),id:ne([p(),O().int()]),error:C({code:O().int(),message:p(),data:te(Ze())})}).strict(),oI=C({jsonrpc:N(Ni)}).merge(C({method:p(),params:te(vd)})).strict(),sI=ne([tI,oI,nI,rI]),aI=class{constructor({url:e,headers:t}){this.connected=!1,this.url=new URL(e),this.headers=t}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController,(async()=>{var r,o,s;try{const a=Rr({...this.headers,Accept:"text/event-stream"},`ai-sdk/${Ei}`,Os()),i=await fetch(this.url.href,{headers:a,signal:(r=this.abortController)==null?void 0:r.signal});if(!i.ok||!i.body){const h=new ot({message:`MCP SSE Transport Error: ${i.status} ${i.statusText}`});return(o=this.onerror)==null||o.call(this,h),t(h)}const c=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new ni).getReader(),u=async()=>{var h,y,f;try{for(;;){const{done:g,value:v}=await c.read();if(g){if(this.connected)throw this.connected=!1,new ot({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:d}=v;if(m==="endpoint"){if(this.endpoint=new URL(d,this.url),this.endpoint.origin!==this.url.origin)throw new ot({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(m==="message")try{const w=sI.parse(JSON.parse(d));(h=this.onmessage)==null||h.call(this,w)}catch(w){const _=new ot({message:"MCP SSE Transport Error: Failed to parse message",cause:w});(y=this.onerror)==null||y.call(this,_)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(f=this.onerror)==null||f.call(this,g),t(g)}};this.sseConnection={close:()=>c.cancel()},u()}catch(a){if(a instanceof Error&&a.name==="AbortError")return;(s=this.onerror)==null||s.call(this,a),t(a)}})()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){var t,n,r;if(!this.endpoint||!this.connected)throw new ot({message:"MCP SSE Transport Error: Not connected"});try{const s={method:"POST",headers:Rr({...this.headers,"Content-Type":"application/json"},`ai-sdk/${Ei}`,Os()),body:JSON.stringify(e),signal:(t=this.abortController)==null?void 0:t.signal},a=await fetch(this.endpoint,s);if(!a.ok){const i=await a.text().catch(()=>null),l=new ot({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${a.status}): ${i}`});(n=this.onerror)==null||n.call(this,l);return}}catch(o){(r=this.onerror)==null||r.call(this,o);return}}};function iI(e){if(e.type!=="sse")throw new ot({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new aI(e)}function lI(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var cI="1.0.0";async function uI(e){const t=new dI(e);return await t.init(),t}var dI=class{constructor({transport:e,name:t="ai-sdk-mcp-client",onUncaughtError:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,lI(e)?this.transport=e:this.transport=iI(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=r=>this.onError(r),this.transport.onmessage=r=>{if("method"in r){this.onError(new ot({message:"Unsupported message type"}));return}this.onResponse(r)},this.clientInfo={name:t,version:cI}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:_1,capabilities:{},clientInfo:this.clientInfo}},resultSchema:BE});if(e===void 0)throw new ot({message:"Server sent invalid initialize result"});if(!UE.includes(e.protocolVersion))throw new ot({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new ot({message:"Server does not support tools"});break;default:throw new ot({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,o)=>{if(this.isClosed)return o(new ot({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=n==null?void 0:n.signal;s==null||s.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s!=null&&s.aborted)return o(new ot({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);r(u)}catch(u){const h=new ot({message:"Failed to parse server response",cause:u});o(h)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:WE,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:eI,options:{signal:n==null?void 0:n.abortSignal}})}catch(r){throw r}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const r=await this.listTools();for(const{name:o,description:s,inputSchema:a}of r.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(u,h)=>{var y;return(y=h==null?void 0:h.abortSignal)==null||y.throwIfAborted(),i.callTool({name:o,args:u,options:h})},c=e==="automatic"?i2({description:s,inputSchema:As({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};n[o]=c}return n}catch(r){throw r}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ot({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new ot({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new ot({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Jt(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}function Bs(e){return Object.fromEntries([...e.headers])}var pI=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new ju({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},wt=pI();function _d(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var fI=["fetch failed","failed to fetch"];function hI({error:e,url:t,requestBodyValues:n}){if(_d(e))return e;if(e instanceof TypeError&&fI.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Ve({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function mI(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function gI(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}function wd(e,...t){const n=new Headers(gI(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var yI="3.0.18";function b1({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new _i({message:`${r} API key must be a string.`});if(typeof process>"u")throw new _i({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _i({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new _i({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function vI({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function _I(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}var wI=/"__proto__"\s*:/,bI=/"constructor"\s*:/;function S1(e){const t=JSON.parse(e);return t===null||typeof t!="object"||wI.test(e)===!1&&bI.test(e)===!1?t:SI(t)}function SI(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}function bd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return S1(e)}try{return S1(e)}finally{Error.stackTraceLimit=t}}var Ai=Symbol.for("vercel.ai.validator");function CI(e){return{[Ai]:!0,validate:e}}function $I(e){return typeof e=="object"&&e!==null&&Ai in e&&e[Ai]===!0&&"validate"in e}function bt(e){let t;return()=>(t==null&&(t=e()),t)}function kI(e){return $I(e)?e:typeof e=="function"?e():TI(e)}function TI(e){return CI(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new En({value:t,cause:n.issues})}})}async function pr({value:e,schema:t}){const n=await Hs({value:e,schema:t});if(!n.success)throw En.wrap({value:e,cause:n.error});return n.value}async function Hs({value:e,schema:t}){const n=kI(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:En.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:En.wrap({value:e,cause:r}),rawValue:e}}}async function xI({text:e,schema:t}){try{const n=bd(e);return t==null?n:pr({value:n,schema:t})}catch(n){throw cr.isInstance(n)||En.isInstance(n)?n:new cr({text:e,cause:n})}}async function C1({text:e,schema:t}){try{const n=bd(e);return t==null?{success:!0,value:n,rawValue:n}:await Hs({value:n,schema:t})}catch(n){return{success:!1,error:cr.isInstance(n)?n:new cr({text:e,cause:n}),rawValue:void 0}}}function Mi(e){try{return bd(e),!0}catch{return!1}}function EI({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ni).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await C1({text:n,schema:t}))}}))}async function On({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await Hs({value:t[e],schema:n});if(!r.success)throw new ju({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var II=()=>globalThis.fetch,pn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>$1({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),PI=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>$1({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),$1=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=II()})=>{try{const i=await a(e,{method:"POST",headers:wd(t,`ai-sdk/provider-utils/${yI}`,mI()),body:n.content,signal:s}),l=Bs(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:n.values})}catch(u){throw _d(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(_d(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw hI({error:i,url:e,requestBodyValues:n.values})}};function FO(e){return e}function Co({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:r,execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var k1=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=Bs(r);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await xI({text:a,schema:e});return{responseHeaders:i,value:new Ve({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new Ve({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},ji=e=>async({response:t})=>{const n=Bs(t);if(t.body==null)throw new Em({});return{responseHeaders:n,value:EI({stream:t.body,schema:e})}},zr=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await C1({text:o,schema:e}),a=Bs(t);if(!s.success)throw new Ve({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},RI=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=Bs(e);if(!e.body)throw new Ve({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Ve({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},OI=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},NI=Symbol("Let zodToJsonSchema decide on which parser to use"),T1={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"},AI=e=>typeof e=="string"?{...T1,name:e}:{...T1,...e};function Ut(){return{}}function MI(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==I.ZodAny&&(s.items=ze(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function jI(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function LI(){return{type:"boolean"}}function x1(e,t){return ze(e.type._def,t)}var zI=(e,t)=>ze(e.innerType._def,t);function E1(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>E1(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return DI(e)}}var DI=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function ZI(e,t){return{...ze(e.innerType._def,t),default:e.defaultValue()}}function UI(e,t){return t.effectStrategy==="input"?ze(e.schema._def,t):Ut()}function qI(e){return{type:"string",enum:Array.from(e.values)}}var VI=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function FI(e,t){const n=[ze(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ze(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(VI(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}r.push(s)}}),r.length?{allOf:r}:void 0}function BI(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Sd=void 0,fn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Sd===void 0&&(Sd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function I1(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":hn(n,"email",r.message,t);break;case"format:idn-email":hn(n,"idn-email",r.message,t);break;case"pattern:zod":St(n,fn.email,r.message,t);break}break;case"url":hn(n,"uri",r.message,t);break;case"uuid":hn(n,"uuid",r.message,t);break;case"regex":St(n,r.regex,r.message,t);break;case"cuid":St(n,fn.cuid,r.message,t);break;case"cuid2":St(n,fn.cuid2,r.message,t);break;case"startsWith":St(n,RegExp(`^${Cd(r.value,t)}`),r.message,t);break;case"endsWith":St(n,RegExp(`${Cd(r.value,t)}$`),r.message,t);break;case"datetime":hn(n,"date-time",r.message,t);break;case"date":hn(n,"date",r.message,t);break;case"time":hn(n,"time",r.message,t);break;case"duration":hn(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{St(n,RegExp(Cd(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&hn(n,"ipv4",r.message,t),r.version!=="v4"&&hn(n,"ipv6",r.message,t);break}case"base64url":St(n,fn.base64url,r.message,t);break;case"jwt":St(n,fn.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&St(n,fn.ipv4Cidr,r.message,t),r.version!=="v4"&&St(n,fn.ipv6Cidr,r.message,t);break}case"emoji":St(n,fn.emoji(),r.message,t);break;case"ulid":{St(n,fn.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{hn(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{St(n,fn.base64,r.message,t);break}}break}case"nanoid":St(n,fn.nanoid,r.message,t)}return n}function Cd(e,t){return t.patternStrategy==="escape"?JI(e):e}var HI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function JI(e){let t="";for(let n=0;n<e.length;n++)HI.has(e[n])||(t+="\\"),t+=e[n];return t}function hn(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function St(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:P1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=P1(t,r)}function P1(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
574
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
575
+ ]))`;continue}}if(r.s&&o[c]==="."){s+=i?`${o[c]}\r
576
+ `:`[${o[c]}\r
577
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function R1(e,t){var n,r,o,s,a,i;const l={type:"object",additionalProperties:(n=ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===I.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=I1(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===I.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===I.ZodBranded&&e.keyType._def.type._def.typeName===I.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=x1(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function WI(e,t){if(t.mapStrategy==="record")return R1(e,t);const n=ze(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ut(),r=ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ut();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function GI(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function KI(){return{not:Ut()}}function YI(){return{type:"null"}}var $d={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function QI(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in $d&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=$d[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return XI(e,t)}var XI=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>ze(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function eP(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[$d[e.innerType._def.typeName],"null"]};const n=ze(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function tP(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function nP(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=oP(i),c=ze(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=rP(e,t);return s!==void 0&&(n.additionalProperties=s),n}function rP(e,t){if(e.catchall._def.typeName!=="ZodNever")return ze(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function oP(e){try{return e.isOptional()}catch{return!0}}var sP=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return ze(e.innerType._def,t);const r=ze(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ut()},r]}:Ut()},aP=(e,t)=>{if(t.pipeStrategy==="input")return ze(e.in._def,t);if(t.pipeStrategy==="output")return ze(e.out._def,t);const n=ze(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=ze(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function iP(e,t){return ze(e.type._def,t)}function lP(e,t){const r={type:"array",uniqueItems:!0,items:ze(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function cP(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>ze(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ze(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>ze(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function uP(){return{not:Ut()}}function dP(){return Ut()}var pP=(e,t)=>ze(e.innerType._def,t),fP=(e,t,n)=>{switch(t){case I.ZodString:return I1(e,n);case I.ZodNumber:return tP(e);case I.ZodObject:return nP(e,n);case I.ZodBigInt:return jI(e);case I.ZodBoolean:return LI();case I.ZodDate:return E1(e,n);case I.ZodUndefined:return uP();case I.ZodNull:return YI();case I.ZodArray:return MI(e,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return QI(e,n);case I.ZodIntersection:return FI(e,n);case I.ZodTuple:return cP(e,n);case I.ZodRecord:return R1(e,n);case I.ZodLiteral:return BI(e);case I.ZodEnum:return qI(e);case I.ZodNativeEnum:return GI(e);case I.ZodNullable:return eP(e,n);case I.ZodOptional:return sP(e,n);case I.ZodMap:return WI(e,n);case I.ZodSet:return lP(e,n);case I.ZodLazy:return()=>e.getter()._def;case I.ZodPromise:return iP(e,n);case I.ZodNaN:case I.ZodNever:return KI();case I.ZodEffects:return UI(e,n);case I.ZodAny:return Ut();case I.ZodUnknown:return dP();case I.ZodDefault:return ZI(e,n);case I.ZodBranded:return x1(e,n);case I.ZodReadonly:return pP(e,n);case I.ZodCatch:return zI(e,n);case I.ZodPipeline:return aP(e,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}};function ze(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==NI)return l}if(o&&!n){const l=hP(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=fP(e,e.typeName,t),i=typeof a=="function"?ze(a(),t):a;if(i&&mP(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var hP=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:OI(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ut()):t.$refStrategy==="seen"?Ut():void 0}},mP=(e,t,n)=>(e.description&&(n.description=e.description),n),gP=e=>{const t=AI(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},yP=(e,t)=>{var n;const r=gP(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var y;return{...c,[u]:(y=ze(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0))!=null?y:Ut()}},{}):void 0;const s=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,a=(n=ze(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:Ut(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},vP=yP;function _P(e,t){var n;const r=(n=void 0)!=null?n:!1;return O1(()=>vP(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function wP(e,t){var n;const r=(n=void 0)!=null?n:!1;return O1(()=>ic(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"}),{validate:async o=>{const s=await lc(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function bP(e){return"_zod"in e}function Ne(e,t){return bP(e)?wP(e):_P(e)}var SP=Symbol.for("vercel.ai.schema");function mt(e){let t;return()=>(t==null&&(t=e()),t)}function O1(e,{validate:t}={}){return{[SP]:!0,_type:void 0,[Ai]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:CP,atob:$P}=globalThis;function kP(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=$P(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function TP(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return CP(t)}function Dr(e){return e instanceof Uint8Array?TP(e):e}function N1(e){return e==null?void 0:e.replace(/\/$/,"")}var kd=C({error:C({message:p(),type:p().nullish(),param:Mt().nullish(),code:ne([p(),O()]).nullish()})}),Nn=k1({errorSchema:kd,errorToMessage:e=>e.error.message});function xP({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((a,i)=>{var l,c,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,${Dr(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new cn({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Dr(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Dr(a.data),format:"mp3"}};default:throw new cn({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new cn({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,${Dr(a.data)}`}}}else throw new cn({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function Td({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function A1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var EP=bt(()=>Ne(C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({message:C({role:N("assistant").nullish(),content:p().nullish(),tool_calls:A(C({id:p().nullish(),type:N("function"),function:C({name:p(),arguments:p()})})).nullish(),annotations:A(C({type:N("url_citation"),start_index:O(),end_index:O(),url:p(),title:p()})).nullish()}),index:O(),logprobs:C({content:A(C({token:p(),logprob:O(),top_logprobs:A(C({token:p(),logprob:O()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:C({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:C({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}))),IP=bt(()=>Ne(ne([C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({delta:C({role:Se(["assistant"]).nullish(),content:p().nullish(),tool_calls:A(C({index:O(),id:p().nullish(),type:N("function").nullish(),function:C({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:A(C({type:N("url_citation"),start_index:O(),end_index:O(),url:p(),title:p()})).nullish()}).nullish(),logprobs:C({content:A(C({token:p(),logprob:O(),top_logprobs:A(C({token:p(),logprob:O()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:O()})),usage:C({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:C({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}),kd]))),PP=bt(()=>Ne(C({logitBias:fe(v6(),O()).optional(),logprobs:ne([le(),O()]).optional(),parallelToolCalls:le().optional(),user:p().optional(),reasoningEffort:Se(["none","minimal","low","medium","high"]).optional(),maxCompletionTokens:O().optional(),store:le().optional(),metadata:fe(p().max(64),p().max(512)).optional(),prediction:fe(p(),Mt()).optional(),structuredOutputs:le().optional(),serviceTier:Se(["auto","flex","priority","default"]).optional(),strictJsonSchema:le().optional(),textVerbosity:Se(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:Se(["in_memory","24h"]).optional(),safetyIdentifier:p().optional()})));function RP({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:n?r:void 0}});break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new cn({functionality:`tool choice type: ${i}`})}}}var OP=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:y}){var f,g,v,m;const d=[],w=(f=await On({provider:"openai",providerOptions:y,schema:PP}))!=null?f:{},_=(g=w.structuredOutputs)!=null?g:!0;o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!_&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:T}=xP({prompt:e,systemMessageMode:MP(this.modelId)});d.push(...T);const P=(v=w.strictJsonSchema)!=null?v:!1,E={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?_&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:P,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,prompt_cache_retention:w.promptCacheRetention,safety_identifier:w.safetyIdentifier,messages:b};M1(this.modelId)?(E.temperature!=null&&(E.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),E.top_p!=null&&(E.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),E.frequency_penalty!=null&&(E.frequency_penalty=void 0,d.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),E.presence_penalty!=null&&(E.presence_penalty=void 0,d.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),E.logit_bias!=null&&(E.logit_bias=void 0,d.push({type:"other",message:"logitBias is not supported for reasoning models"})),E.logprobs!=null&&(E.logprobs=void 0,d.push({type:"other",message:"logprobs is not supported for reasoning models"})),E.top_logprobs!=null&&(E.top_logprobs=void 0,d.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),E.max_tokens!=null&&(E.max_completion_tokens==null&&(E.max_completion_tokens=E.max_tokens),E.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&E.temperature!=null&&(E.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!NP(this.modelId)&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0),w.serviceTier==="priority"&&!AP(this.modelId)&&(d.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"}),E.service_tier=void 0);const{tools:Z,toolChoice:U,toolWarnings:W}=RP({tools:u,toolChoice:h,structuredOutputs:_,strictJsonSchema:P});return{args:{...E,tools:Z,tool_choice:U},warnings:[...d,...W]}}async doGenerate(e){var t,n,r,o,s,a,i,l,c,u,h,y,f,g;const{args:v,warnings:m}=await this.getArgs(e),{responseHeaders:d,value:w,rawValue:_}=await pn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:v,failedResponseHandler:Nn,successfulResponseHandler:zr(EP),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=w.choices[0],T=[],P=b.message.content;P!=null&&P.length>0&&T.push({type:"text",text:P});for(const W of(t=b.message.tool_calls)!=null?t:[])T.push({type:"tool-call",toolCallId:(n=W.id)!=null?n:wt(),toolName:W.function.name,input:W.function.arguments});for(const W of(r=b.message.annotations)!=null?r:[])T.push({type:"source",sourceType:"url",id:wt(),url:W.url,title:W.title});const E=(o=w.usage)==null?void 0:o.completion_tokens_details,Z=(s=w.usage)==null?void 0:s.prompt_tokens_details,U={openai:{}};return(E==null?void 0:E.accepted_prediction_tokens)!=null&&(U.openai.acceptedPredictionTokens=E==null?void 0:E.accepted_prediction_tokens),(E==null?void 0:E.rejected_prediction_tokens)!=null&&(U.openai.rejectedPredictionTokens=E==null?void 0:E.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(U.openai.logprobs=b.logprobs.content),{content:T,finishReason:A1(b.finish_reason),usage:{inputTokens:(l=(i=w.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=w.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(y=(h=w.usage)==null?void 0:h.total_tokens)!=null?y:void 0,reasoningTokens:(f=E==null?void 0:E.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(g=Z==null?void 0:Z.cached_tokens)!=null?g:void 0},request:{body:v},response:{...Td(w),headers:d,body:_},warnings:m,providerMetadata:U}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await pn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:r,failedResponseHandler:Nn,successfulResponseHandler:ji(IP),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:n})},transform(y,f){var g,v,m,d,w,_,b,T,P,E,Z,U,W,V,B,J,H,ue,Ce,ae,ye,he,L,x;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){i="error",f.enqueue({type:"error",error:y.error});return}const M=y.value;if("error"in M){i="error",f.enqueue({type:"error",error:M.error});return}if(!c){const k=Td(M);Object.values(k).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Td(M)}))}M.usage!=null&&(l.inputTokens=(g=M.usage.prompt_tokens)!=null?g:void 0,l.outputTokens=(v=M.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(m=M.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(w=(d=M.usage.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?w:void 0,l.cachedInputTokens=(b=(_=M.usage.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?b:void 0,((T=M.usage.completion_tokens_details)==null?void 0:T.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(P=M.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens),((E=M.usage.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(Z=M.usage.completion_tokens_details)==null?void 0:Z.rejected_prediction_tokens));const R=M.choices[0];if((R==null?void 0:R.finish_reason)!=null&&(i=A1(R.finish_reason)),((U=R==null?void 0:R.logprobs)==null?void 0:U.content)!=null&&(h.openai.logprobs=R.logprobs.content),(R==null?void 0:R.delta)==null)return;const $=R.delta;if($.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:$.content})),$.tool_calls!=null)for(const k of $.tool_calls){const S=k.index;if(a[S]==null){if(k.type!=="function")throw new Is({data:k,message:"Expected 'function' type."});if(k.id==null)throw new Is({data:k,message:"Expected 'id' to be a string."});if(((W=k.function)==null?void 0:W.name)==null)throw new Is({data:k,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:k.id,toolName:k.function.name}),a[S]={id:k.id,type:"function",function:{name:k.function.name,arguments:(V=k.function.arguments)!=null?V:""},hasFinished:!1};const D=a[S];((B=D.function)==null?void 0:B.name)!=null&&((J=D.function)==null?void 0:J.arguments)!=null&&(D.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),Mi(D.function.arguments)&&(f.enqueue({type:"tool-input-end",id:D.id}),f.enqueue({type:"tool-call",toolCallId:(H=D.id)!=null?H:wt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0));continue}const z=a[S];z.hasFinished||(((ue=k.function)==null?void 0:ue.arguments)!=null&&(z.function.arguments+=(ae=(Ce=k.function)==null?void 0:Ce.arguments)!=null?ae:""),f.enqueue({type:"tool-input-delta",id:z.id,delta:(ye=k.function.arguments)!=null?ye:""}),((he=z.function)==null?void 0:he.name)!=null&&((L=z.function)==null?void 0:L.arguments)!=null&&Mi(z.function.arguments)&&(f.enqueue({type:"tool-input-end",id:z.id}),f.enqueue({type:"tool-call",toolCallId:(x=z.id)!=null?x:wt(),toolName:z.function.name,input:z.function.arguments}),z.hasFinished=!0))}if($.annotations!=null)for(const k of $.annotations)f.enqueue({type:"source",sourceType:"url",id:wt(),url:k.url,title:k.title})},flush(y){u&&y.enqueue({type:"text-end",id:"0"}),y.enqueue({type:"finish",finishReason:i,usage:l,...h!=null?{providerMetadata:h}:{}})}})),request:{body:r},response:{headers:o}}}};function M1(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function NP(e){return e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")}function AP(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}function MP(e){var t,n;return M1(e)?(n=(t=jP[e])==null?void 0:t.systemMessageMode)!=null?n:"developer":"system"}var jP={o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function LP({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
522
578
 
523
- `,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new ea({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
524
- ${o}
579
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Ir({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");r+=`${t}:
580
+ ${a}
525
581
 
526
- `;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Ar({functionality:"tool-call messages"})}}).join("");a+=`${r}:
527
- ${o}
582
+ `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new cn({functionality:"tool-call messages"})}}).join("");r+=`${n}:
583
+ ${a}
528
584
 
529
- `;break}case"tool":throw new Ar({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
530
- `,{prompt:a,stopSequences:[`
531
- ${e}:`]}}function N0({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 A0(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 m9=_t(()=>De(I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({text:E(),finish_reason:E(),logprobs:I({tokens:oe(E()),token_logprobs:oe(Z()),top_logprobs:oe(kt(E(),Z())).nullish()}).nullish()})),usage:I({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()}).nullish()}))),v9=_t(()=>De(He([I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({text:E(),finish_reason:E().nullish(),index:Z(),logprobs:I({tokens:oe(E()),token_logprobs:oe(Z()),top_logprobs:oe(kt(E(),Z())).nullish()}).nullish()})),usage:I({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()}).nullish()}),vp]))),M0=_t(()=>De(I({echo:Pt().optional(),logitBias:kt(E(),Z()).optional(),suffix:E().optional(),user:E().optional(),logprobs:He([Pt(),Z()]).optional()}))),g9=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:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:f,providerOptions:g}){const d=[],m={...await tn({provider:"openai",providerOptions:g,schema:M0}),...await tn({provider:this.providerOptionsName,providerOptions:g,schema:M0})};n!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:h}=h9({prompt:t}),p=[...h??[],...i??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:(m==null?void 0:m.logprobs)===!0?0:(m==null?void 0:m.logprobs)===!1||m==null?void 0:m.logprobs,suffix:m.suffix,user:m.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:f,prompt:v,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await sr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:n,failedResponseHandler:sn,successfulResponseHandler:Dr(m9),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:A0(c.finish_reason),request:{body:n},response:{...N0(i),headers:o,body:l},providerMetadata:u,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await sr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:a,failedResponseHandler:sn,successfulResponseHandler:uo(v9),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,f){if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){o="error",f.enqueue({type:"error",error:u.error});return}const g=u.value;if("error"in g){o="error",f.enqueue({type:"error",error:g.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...N0(g)}),f.enqueue({type:"text-start",id:"0"})),g.usage!=null&&(l.inputTokens=g.usage.prompt_tokens,l.outputTokens=g.usage.completion_tokens,l.totalTokens=g.usage.total_tokens);const d=g.choices[0];(d==null?void 0:d.finish_reason)!=null&&(o=A0(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},y9=_t(()=>De(I({dimensions:Z().optional(),user:E().optional()}))),_9=_t(()=>De(I({data:oe(I({embedding:oe(Z())})),usage:I({prompt_tokens:Z()}).nullish()}))),w9=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:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new iC({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await tn({provider:"openai",providerOptions:a,schema:y9}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await sr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Gt(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:sn,successfulResponseHandler:Dr(_9),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},b9=_t(()=>De(I({data:oe(I({b64_json:E(),revised_prompt:E().optional()}))}))),E9={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},S9=new Set(["gpt-image-1","gpt-image-1-mini"]),$9=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=E9[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,c,u,f;const g=[];a!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&g.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:m,responseHeaders:v}=await sr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Gt(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(f=s.openai)!=null?f:{},...S9.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:sn,successfulResponseHandler:Dr(b9),abortSignal:i,fetch:this.config.fetch});return{images:m.data.map(h=>h.b64_json),warnings:g,response:{timestamp:d,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:m.data.map(h=>h.revised_prompt?{revisedPrompt:h.revised_prompt}:null)}}}}},P9=Vt(()=>De(I({code:E().nullish(),containerId:E()}))),k9=Vt(()=>De(I({outputs:oe(nr("type",[I({type:W("logs"),logs:E()}),I({type:W("image"),url:E()})])).nullish()}))),x9=Vt(()=>De(I({container:He([E(),I({fileIds:oe(E()).optional()})]).optional()}))),I9=Xa({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:P9,outputSchema:k9}),T9=(t={})=>I9(t),j0=I({key:E(),type:ht(["eq","ne","gt","gte","lt","lte"]),value:He([E(),Z(),Pt()])}),D0=I({type:ht(["and","or"]),filters:oe(He([j0,py(()=>D0)]))}),C9=Vt(()=>De(I({vectorStoreIds:oe(E()),maxNumResults:Z().optional(),ranking:I({ranker:E().optional(),scoreThreshold:Z().optional()}).optional(),filters:He([j0,D0]).optional()}))),R9=Vt(()=>De(I({queries:oe(E()),results:oe(I({attributes:kt(E(),Mr()),fileId:E(),filename:E(),score:Z(),text:E()})).nullable()}))),O9=Xa({id:"openai.file_search",name:"file_search",inputSchema:I({}),outputSchema:R9}),N9=Vt(()=>De(I({background:ht(["auto","opaque","transparent"]).optional(),inputFidelity:ht(["low","high"]).optional(),inputImageMask:I({fileId:E().optional(),imageUrl:E().optional()}).optional(),model:E().optional(),moderation:ht(["auto"]).optional(),outputCompression:Z().int().min(0).max(100).optional(),outputFormat:ht(["png","jpeg","webp"]).optional(),partialImages:Z().int().min(0).max(3).optional(),quality:ht(["auto","low","medium","high"]).optional(),size:ht(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),A9=Vt(()=>De(I({}))),M9=Vt(()=>De(I({result:E()}))),j9=Xa({id:"openai.image_generation",name:"image_generation",inputSchema:A9,outputSchema:M9}),D9=(t={})=>j9(t),L0=Vt(()=>De(I({action:I({type:W("exec"),command:oe(E()),timeoutMs:Z().optional(),user:E().optional(),workingDirectory:E().optional(),env:kt(E(),E()).optional()})}))),z0=Vt(()=>De(I({output:E()}))),L9=Xa({id:"openai.local_shell",name:"local_shell",inputSchema:L0,outputSchema:z0}),z9=Vt(()=>De(I({filters:I({allowedDomains:oe(E()).optional()}).optional(),searchContextSize:ht(["low","medium","high"]).optional(),userLocation:I({type:W("approximate"),country:E().optional(),city:E().optional(),region:E().optional(),timezone:E().optional()}).optional()}))),U9=Vt(()=>De(I({}))),q9=Vt(()=>De(I({action:nr("type",[I({type:W("search"),query:E().optional()}),I({type:W("openPage"),url:E()}),I({type:W("find"),url:E(),pattern:E()})])}))),F9=Xa({id:"openai.web_search",name:"web_search",inputSchema:U9,outputSchema:q9}),Z9=(t={})=>F9(t),V9=Vt(()=>De(I({searchContextSize:ht(["low","medium","high"]).optional(),userLocation:I({type:W("approximate"),country:E().optional(),city:E().optional(),region:E().optional(),timezone:E().optional()}).optional()}))),H9=Vt(()=>De(I({}))),B9=Vt(()=>De(I({action:nr("type",[I({type:W("search"),query:E().optional()}),I({type:W("openPage"),url:E()}),I({type:W("find"),url:E(),pattern:E()})])}))),J9=Xa({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:H9,outputSchema:B9}),G9={codeInterpreter:T9,fileSearch:O9,imageGeneration:D9,localShell:L9,webSearchPreview:J9,webSearch:Z9};function U0(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function K9({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:a,hasLocalShellTool:n=!1}){var s,o,i,l;const c=[],u=[];for(const{role:f,content:g}of t)switch(f){case"system":{switch(e){case"system":{c.push({role:"system",content:g});break}case"developer":{c.push({role:"developer",content:g});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":{c.push({role:"user",content:g.map((d,m)=>{var v,h,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&U0(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${ia(d.data)}`},detail:(h=(v=d.providerOptions)==null?void 0:v.openai)==null?void 0:h.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"&&U0(d.data,r)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${m}.pdf`,file_data:`data:application/pdf;base64,${ia(d.data)}`}};throw new Ar({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},m={};for(const v of g)switch(v.type){case"text":{const h=(o=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:o.itemId;if(a&&h!=null){c.push({type:"item_reference",id:h});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:h});break}case"tool-call":{if(m[v.toolCallId]=v,v.providerExecuted)break;const h=(l=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(a&&h!=null){c.push({type:"item_reference",id:h});break}if(n&&v.toolName==="local_shell"){const p=await en({value:v.input,schema:L0});c.push({type:"local_shell_call",call_id:v.toolCallId,id:h,action:{type:"exec",command:p.action.command,timeout_ms:p.action.timeoutMs,user:p.action.user,working_directory:p.action.workingDirectory,env:p.action.env}});break}c.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:h});break}case"tool-result":{a?c.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 h=await tn({provider:"openai",providerOptions:v.providerOptions,schema:W9}),p=h==null?void 0:h.itemId;if(p!=null){const _=d[p];if(a)_===void 0&&(c.push({type:"item_reference",id:p}),d[p]={type:"reasoning",id:p,summary:[]});else{const w=[];v.text.length>0?w.push({type:"summary_text",text:v.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),_===void 0?(d[p]={type:"reasoning",id:p,encrypted_content:h==null?void 0:h.reasoningEncryptedContent,summary:w},c.push(d[p])):(_.summary.push(...w),(h==null?void 0:h.reasoningEncryptedContent)!=null&&(_.encrypted_content=h.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 g){const m=d.output;if(n&&d.toolName==="local_shell"&&m.type==="json"){const h=await en({value:m.value,schema:z0});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:h.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(h=>{switch(h.type){case"text":return{type:"input_text",text:h.text};case"media":return h.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${h.mediaType};base64,${h.data}`}:{type:"input_file",filename:"data",file_data:`data:${h.mediaType};base64,${h.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:v})}break}default:{const d=f;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var W9=I({itemId:E().nullish(),reasoningEncryptedContent:E().nullish()});function q0({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 Q9=_t(()=>De(He([I({type:W("response.output_text.delta"),item_id:E(),delta:E(),logprobs:oe(I({token:E(),logprob:Z(),top_logprobs:oe(I({token:E(),logprob:Z()}))})).nullish()}),I({type:ht(["response.completed","response.incomplete"]),response:I({incomplete_details:I({reason:E()}).nullish(),usage:I({input_tokens:Z(),input_tokens_details:I({cached_tokens:Z().nullish()}).nullish(),output_tokens:Z(),output_tokens_details:I({reasoning_tokens:Z().nullish()}).nullish()}),service_tier:E().nullish()})}),I({type:W("response.created"),response:I({id:E(),created_at:Z(),model:E(),service_tier:E().nullish()})}),I({type:W("response.output_item.added"),output_index:Z(),item:nr("type",[I({type:W("message"),id:E()}),I({type:W("reasoning"),id:E(),encrypted_content:E().nullish()}),I({type:W("function_call"),id:E(),call_id:E(),name:E(),arguments:E()}),I({type:W("web_search_call"),id:E(),status:E()}),I({type:W("computer_call"),id:E(),status:E()}),I({type:W("file_search_call"),id:E()}),I({type:W("image_generation_call"),id:E()}),I({type:W("code_interpreter_call"),id:E(),container_id:E(),code:E().nullable(),outputs:oe(nr("type",[I({type:W("logs"),logs:E()}),I({type:W("image"),url:E()})])).nullable(),status:E()})])}),I({type:W("response.output_item.done"),output_index:Z(),item:nr("type",[I({type:W("message"),id:E()}),I({type:W("reasoning"),id:E(),encrypted_content:E().nullish()}),I({type:W("function_call"),id:E(),call_id:E(),name:E(),arguments:E(),status:W("completed")}),I({type:W("code_interpreter_call"),id:E(),code:E().nullable(),container_id:E(),outputs:oe(nr("type",[I({type:W("logs"),logs:E()}),I({type:W("image"),url:E()})])).nullable()}),I({type:W("image_generation_call"),id:E(),result:E()}),I({type:W("web_search_call"),id:E(),status:E(),action:nr("type",[I({type:W("search"),query:E().nullish()}),I({type:W("open_page"),url:E()}),I({type:W("find"),url:E(),pattern:E()})])}),I({type:W("file_search_call"),id:E(),queries:oe(E()),results:oe(I({attributes:kt(E(),Mr()),file_id:E(),filename:E(),score:Z(),text:E()})).nullish()}),I({type:W("local_shell_call"),id:E(),call_id:E(),action:I({type:W("exec"),command:oe(E()),timeout_ms:Z().optional(),user:E().optional(),working_directory:E().optional(),env:kt(E(),E()).optional()})}),I({type:W("computer_call"),id:E(),status:W("completed")})])}),I({type:W("response.function_call_arguments.delta"),item_id:E(),output_index:Z(),delta:E()}),I({type:W("response.image_generation_call.partial_image"),item_id:E(),output_index:Z(),partial_image_b64:E()}),I({type:W("response.code_interpreter_call_code.delta"),item_id:E(),output_index:Z(),delta:E()}),I({type:W("response.code_interpreter_call_code.done"),item_id:E(),output_index:Z(),code:E()}),I({type:W("response.output_text.annotation.added"),annotation:nr("type",[I({type:W("url_citation"),url:E(),title:E()}),I({type:W("file_citation"),file_id:E(),filename:E().nullish(),index:Z().nullish(),start_index:Z().nullish(),end_index:Z().nullish(),quote:E().nullish()})])}),I({type:W("response.reasoning_summary_part.added"),item_id:E(),summary_index:Z()}),I({type:W("response.reasoning_summary_text.delta"),item_id:E(),summary_index:Z(),delta:E()}),I({type:W("response.reasoning_summary_part.done"),item_id:E(),summary_index:Z()}),I({type:W("error"),code:E(),message:E(),param:E().nullish(),sequence_number:Z()}),I({type:E()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),Y9=_t(()=>De(I({id:E(),created_at:Z(),error:I({code:E(),message:E()}).nullish(),model:E(),output:oe(nr("type",[I({type:W("message"),role:W("assistant"),id:E(),content:oe(I({type:W("output_text"),text:E(),logprobs:oe(I({token:E(),logprob:Z(),top_logprobs:oe(I({token:E(),logprob:Z()}))})).nullish(),annotations:oe(nr("type",[I({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()}),I({type:W("file_citation"),file_id:E(),filename:E().nullish(),index:Z().nullish(),start_index:Z().nullish(),end_index:Z().nullish(),quote:E().nullish()}),I({type:W("container_file_citation")})]))}))}),I({type:W("web_search_call"),id:E(),status:E(),action:nr("type",[I({type:W("search"),query:E().nullish()}),I({type:W("open_page"),url:E()}),I({type:W("find"),url:E(),pattern:E()})])}),I({type:W("file_search_call"),id:E(),queries:oe(E()),results:oe(I({attributes:kt(E(),Mr()),file_id:E(),filename:E(),score:Z(),text:E()})).nullish()}),I({type:W("code_interpreter_call"),id:E(),code:E().nullable(),container_id:E(),outputs:oe(nr("type",[I({type:W("logs"),logs:E()}),I({type:W("image"),url:E()})])).nullable()}),I({type:W("image_generation_call"),id:E(),result:E()}),I({type:W("local_shell_call"),id:E(),call_id:E(),action:I({type:W("exec"),command:oe(E()),timeout_ms:Z().optional(),user:E().optional(),working_directory:E().optional(),env:kt(E(),E()).optional()})}),I({type:W("function_call"),call_id:E(),name:E(),arguments:E(),id:E()}),I({type:W("computer_call"),id:E(),status:E().optional()}),I({type:W("reasoning"),id:E(),encrypted_content:E().nullish(),summary:oe(I({type:W("summary_text"),text:E()}))})])),service_tier:E().nullish(),incomplete_details:I({reason:E()}).nullish(),usage:I({input_tokens:Z(),input_tokens_details:I({cached_tokens:Z().nullish()}).nullish(),output_tokens:Z(),output_tokens_details:I({reasoning_tokens:Z().nullish()}).nullish()})}))),F0=20,X9=_t(()=>De(I({include:oe(ht(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:E().nullish(),logprobs:He([Pt(),Z().min(1).max(F0)]).optional(),maxToolCalls:Z().nullish(),metadata:_r().nullish(),parallelToolCalls:Pt().nullish(),previousResponseId:E().nullish(),promptCacheKey:E().nullish(),reasoningEffort:E().nullish(),reasoningSummary:E().nullish(),safetyIdentifier:E().nullish(),serviceTier:ht(["auto","flex","priority","default"]).nullish(),store:Pt().nullish(),strictJsonSchema:Pt().nullish(),textVerbosity:ht(["low","medium","high"]).nullish(),truncation:ht(["auto","disabled"]).nullish(),user:E().nullish()})));async function eD({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=await en({value:o.args,schema:C9});n.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":{n.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await en({value:o.args,schema:V9});n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await en({value:o.args,schema:z9});n.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await en({value:o.args,schema:x9});n.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 en({value:o.args,schema:N9});n.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:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,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:a};default:{const o=s;throw new Ar({functionality:`tool choice type: ${o}`})}}}var tD=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:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:f,responseFormat:g}){var d,m,v,h;const p=[],_=dD(this.modelId);n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),i!=null&&p.push({type:"unsupported-setting",setting:"seed"}),s!=null&&p.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&p.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&p.push({type:"unsupported-setting",setting:"stopSequences"});const w=await tn({provider:"openai",providerOptions:c,schema:X9}),{input:b,warnings:S}=await K9({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=w==null?void 0:w.store)!=null?d:!0,hasLocalShellTool:O("openai.local_shell")});p.push(...S);const x=(m=w==null?void 0:w.strictJsonSchema)!=null?m:!1;let k=w==null?void 0:w.include;function A(ne){k==null?k=[ne]:k.includes(ne)||(k=[...k,ne])}function O(ne){return(u==null?void 0:u.find(ce=>ce.type==="provider-defined"&&ce.id===ne))!=null}const H=typeof(w==null?void 0:w.logprobs)=="number"?w==null?void 0:w.logprobs:(w==null?void 0:w.logprobs)===!0?F0:void 0;H&&A("message.output_text.logprobs");const J=(v=u==null?void 0:u.find(ne=>ne.type==="provider-defined"&&(ne.id==="openai.web_search"||ne.id==="openai.web_search_preview")))==null?void 0:v.name;J&&A("web_search_call.action.sources"),O("openai.code_interpreter")&&A("code_interpreter_call.outputs");const K=w==null?void 0:w.store;K===!1&&_.isReasoningModel&&A("reasoning.encrypted_content");const z={model:this.modelId,input:b,temperature:e,top_p:a,max_output_tokens:t,...((g==null?void 0:g.type)==="json"||(w==null?void 0:w.textVerbosity))&&{text:{...(g==null?void 0:g.type)==="json"&&{format:g.schema!=null?{type:"json_schema",strict:x,name:(h=g.name)!=null?h:"response",description:g.description,schema:g.schema}:{type:"json_object"}},...(w==null?void 0:w.textVerbosity)&&{verbosity:w.textVerbosity}}},max_tool_calls:w==null?void 0:w.maxToolCalls,metadata:w==null?void 0:w.metadata,parallel_tool_calls:w==null?void 0:w.parallelToolCalls,previous_response_id:w==null?void 0:w.previousResponseId,store:K,user:w==null?void 0:w.user,instructions:w==null?void 0:w.instructions,service_tier:w==null?void 0:w.serviceTier,include:k,prompt_cache_key:w==null?void 0:w.promptCacheKey,safety_identifier:w==null?void 0:w.safetyIdentifier,top_logprobs:H,truncation:w==null?void 0:w.truncation,..._.isReasoningModel&&((w==null?void 0:w.reasoningEffort)!=null||(w==null?void 0:w.reasoningSummary)!=null)&&{reasoning:{...(w==null?void 0:w.reasoningEffort)!=null&&{effort:w.reasoningEffort},...(w==null?void 0:w.reasoningSummary)!=null&&{summary:w.reasoningSummary}}}};_.isReasoningModel?(z.temperature!=null&&(z.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((w==null?void 0:w.reasoningEffort)!=null&&p.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(w==null?void 0:w.reasoningSummary)!=null&&p.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(w==null?void 0:w.serviceTier)==="flex"&&!_.supportsFlexProcessing&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete z.service_tier),(w==null?void 0:w.serviceTier)==="priority"&&!_.supportsPriorityProcessing&&(p.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 z.service_tier);const{tools:U,toolChoice:G,toolWarnings:se}=await eD({tools:u,toolChoice:f,strictJsonSchema:x});return{webSearchToolName:J,args:{...z,tools:U,tool_choice:G},warnings:[...p,...se],store:K}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,m,v,h,p,_,w;const{args:b,warnings:S,webSearchToolName:x}=await this.getArgs(t),k=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:A,value:O,rawValue:H}=await sr({url:k,headers:Gt(this.config.headers(),t.headers),body:b,failedResponseHandler:sn,successfulResponseHandler:Dr(Y9),abortSignal:t.abortSignal,fetch:this.config.fetch});if(O.error)throw new Nt({message:O.error.message,url:k,requestBodyValues:b,statusCode:400,responseHeaders:A,responseBody:H,isRetryable:!1});const J=[],K=[];let z=!1;for(const G of O.output)switch(G.type){case"reasoning":{G.summary.length===0&&G.summary.push({type:"summary_text",text:""});for(const se of G.summary)J.push({type:"reasoning",text:se.text,providerMetadata:{openai:{itemId:G.id,reasoningEncryptedContent:(e=G.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"image_generation",result:{result:G.result},providerExecuted:!0});break}case"local_shell_call":{J.push({type:"tool-call",toolCallId:G.call_id,toolName:"local_shell",input:JSON.stringify({action:G.action}),providerMetadata:{openai:{itemId:G.id}}});break}case"message":{for(const se of G.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&se.logprobs&&K.push(se.logprobs),J.push({type:"text",text:se.text,providerMetadata:{openai:{itemId:G.id}}});for(const ne of se.annotations)ne.type==="url_citation"?J.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:ar(),url:ne.url,title:ne.title}):ne.type==="file_citation"&&J.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:ar(),mediaType:"text/plain",title:(f=(u=ne.quote)!=null?u:ne.filename)!=null?f:"Document",filename:(g=ne.filename)!=null?g:ne.file_id})}break}case"function_call":{z=!0,J.push({type:"tool-call",toolCallId:G.call_id,toolName:G.name,input:G.arguments,providerMetadata:{openai:{itemId:G.id}}});break}case"web_search_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:x??"web_search",input:JSON.stringify({}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:x??"web_search",result:V0(G.action),providerExecuted:!0});break}case"computer_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"computer_use",input:"",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:G.status||"completed"},providerExecuted:!0});break}case"file_search_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"file_search",input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"file_search",result:{queries:G.queries,results:(m=(d=G.results)==null?void 0:d.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?m:null},providerExecuted:!0});break}case"code_interpreter_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"code_interpreter",input:JSON.stringify({code:G.code,containerId:G.container_id}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"code_interpreter",result:{outputs:G.outputs},providerExecuted:!0});break}}const U={openai:{responseId:O.id}};return K.length>0&&(U.openai.logprobs=K),typeof O.service_tier=="string"&&(U.openai.serviceTier=O.service_tier),{content:J,finishReason:q0({finishReason:(v=O.incomplete_details)==null?void 0:v.reason,hasFunctionCall:z}),usage:{inputTokens:O.usage.input_tokens,outputTokens:O.usage.output_tokens,totalTokens:O.usage.input_tokens+O.usage.output_tokens,reasoningTokens:(p=(h=O.usage.output_tokens_details)==null?void 0:h.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(w=(_=O.usage.input_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0},request:{body:b},response:{id:O.id,timestamp:new Date(O.created_at*1e3),modelId:O.model,headers:A,body:H},providerMetadata:U,warnings:S}}async doStream(t){const{args:e,warnings:r,webSearchToolName:a,store:n}=await this.getArgs(t),{responseHeaders:s,value:o}=await sr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:sn,successfulResponseHandler:uo(Q9),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this;let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let f=null;const g={};let d=!1;const m={};let v;return{stream:o.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,p){var _,w,b,S,x,k,A,O,H,J,K,z,U,G,se,ne,ce,pe,M,R,D,N;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){l="error",p.enqueue({type:"error",error:h.error});return}const y=h.value;if(Z0(y))y.item.type==="function_call"?(g[y.output_index]={toolName:y.item.name,toolCallId:y.item.call_id},p.enqueue({type:"tool-input-start",id:y.item.call_id,toolName:y.item.name})):y.item.type==="web_search_call"?(g[y.output_index]={toolName:a??"web_search",toolCallId:y.item.id},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:a??"web_search",providerExecuted:!0}),p.enqueue({type:"tool-input-end",id:y.item.id}),p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0})):y.item.type==="computer_call"?(g[y.output_index]={toolName:"computer_use",toolCallId:y.item.id},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:"computer_use",providerExecuted:!0})):y.item.type==="code_interpreter_call"?(g[y.output_index]={toolName:"code_interpreter",toolCallId:y.item.id,codeInterpreter:{containerId:y.item.container_id}},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:"code_interpreter",providerExecuted:!0}),p.enqueue({type:"tool-input-delta",id:y.item.id,delta:`{"containerId":"${y.item.container_id}","code":"`})):y.item.type==="file_search_call"?p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):y.item.type==="image_generation_call"?p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):y.item.type==="message"?p.enqueue({type:"text-start",id:y.item.id,providerMetadata:{openai:{itemId:y.item.id}}}):Z0(y)&&y.item.type==="reasoning"&&(m[y.item.id]={encryptedContent:y.item.encrypted_content,summaryParts:{0:"active"}},p.enqueue({type:"reasoning-start",id:`${y.item.id}:0`,providerMetadata:{openai:{itemId:y.item.id,reasoningEncryptedContent:(_=y.item.encrypted_content)!=null?_:null}}}));else if(nD(y)){if(y.item.type==="function_call")g[y.output_index]=void 0,d=!0,p.enqueue({type:"tool-input-end",id:y.item.call_id}),p.enqueue({type:"tool-call",toolCallId:y.item.call_id,toolName:y.item.name,input:y.item.arguments,providerMetadata:{openai:{itemId:y.item.id}}});else if(y.item.type==="web_search_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"web_search",result:V0(y.item.action),providerExecuted:!0});else if(y.item.type==="computer_call")g[y.output_index]=void 0,p.enqueue({type:"tool-input-end",id:y.item.id}),p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:y.item.status||"completed"},providerExecuted:!0});else if(y.item.type==="file_search_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"file_search",result:{queries:y.item.queries,results:(b=(w=y.item.results)==null?void 0:w.map(P=>({attributes:P.attributes,fileId:P.file_id,filename:P.filename,score:P.score,text:P.text})))!=null?b:null},providerExecuted:!0});else if(y.item.type==="code_interpreter_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"code_interpreter",result:{outputs:y.item.outputs},providerExecuted:!0});else if(y.item.type==="image_generation_call")p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"image_generation",result:{result:y.item.result},providerExecuted:!0});else if(y.item.type==="local_shell_call")g[y.output_index]=void 0,p.enqueue({type:"tool-call",toolCallId:y.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:y.item.action.command,timeoutMs:y.item.action.timeout_ms,user:y.item.action.user,workingDirectory:y.item.action.working_directory,env:y.item.action.env}}),providerMetadata:{openai:{itemId:y.item.id}}});else if(y.item.type==="message")p.enqueue({type:"text-end",id:y.item.id});else if(y.item.type==="reasoning"){const P=m[y.item.id],j=Object.entries(P.summaryParts).filter(([Q,ee])=>ee==="active"||ee==="can-conclude").map(([Q])=>Q);for(const Q of j)p.enqueue({type:"reasoning-end",id:`${y.item.id}:${Q}`,providerMetadata:{openai:{itemId:y.item.id,reasoningEncryptedContent:(S=y.item.encrypted_content)!=null?S:null}}});delete m[y.item.id]}}else if(oD(y)){const P=g[y.output_index];P!=null&&p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:y.delta})}else if(iD(y)){const P=g[y.output_index];P!=null&&p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:JSON.stringify(y.delta).slice(1,-1)})}else if(lD(y)){const P=g[y.output_index];P!=null&&(p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:'"}'}),p.enqueue({type:"tool-input-end",id:P.toolCallId}),p.enqueue({type:"tool-call",toolCallId:P.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:y.code,containerId:P.codeInterpreter.containerId}),providerExecuted:!0}))}else if(sD(y))f=y.response.id,p.enqueue({type:"response-metadata",id:y.response.id,timestamp:new Date(y.response.created_at*1e3),modelId:y.response.model});else if(rD(y))p.enqueue({type:"text-delta",id:y.item_id,delta:y.delta}),(k=(x=t.providerOptions)==null?void 0:x.openai)!=null&&k.logprobs&&y.logprobs&&u.push(y.logprobs);else if(y.type==="response.reasoning_summary_part.added"){if(y.summary_index>0){const P=m[y.item_id];P.summaryParts[y.summary_index]="active";for(const j of Object.keys(P.summaryParts))P.summaryParts[j]==="can-conclude"&&(p.enqueue({type:"reasoning-end",id:`${y.item_id}:${j}`,providerMetadata:{openai:{itemId:y.item_id}}}),P.summaryParts[j]="concluded");p.enqueue({type:"reasoning-start",id:`${y.item_id}:${y.summary_index}`,providerMetadata:{openai:{itemId:y.item_id,reasoningEncryptedContent:(O=(A=m[y.item_id])==null?void 0:A.encryptedContent)!=null?O:null}}})}}else y.type==="response.reasoning_summary_text.delta"?p.enqueue({type:"reasoning-delta",id:`${y.item_id}:${y.summary_index}`,delta:y.delta,providerMetadata:{openai:{itemId:y.item_id}}}):y.type==="response.reasoning_summary_part.done"?n?(p.enqueue({type:"reasoning-end",id:`${y.item_id}:${y.summary_index}`,providerMetadata:{openai:{itemId:y.item_id}}}),m[y.item_id].summaryParts[y.summary_index]="concluded"):m[y.item_id].summaryParts[y.summary_index]="can-conclude":aD(y)?(l=q0({finishReason:(H=y.response.incomplete_details)==null?void 0:H.reason,hasFunctionCall:d}),c.inputTokens=y.response.usage.input_tokens,c.outputTokens=y.response.usage.output_tokens,c.totalTokens=y.response.usage.input_tokens+y.response.usage.output_tokens,c.reasoningTokens=(K=(J=y.response.usage.output_tokens_details)==null?void 0:J.reasoning_tokens)!=null?K:void 0,c.cachedInputTokens=(U=(z=y.response.usage.input_tokens_details)==null?void 0:z.cached_tokens)!=null?U:void 0,typeof y.response.service_tier=="string"&&(v=y.response.service_tier)):cD(y)?y.annotation.type==="url_citation"?p.enqueue({type:"source",sourceType:"url",id:(ne=(se=(G=i.config).generateId)==null?void 0:se.call(G))!=null?ne:ar(),url:y.annotation.url,title:y.annotation.title}):y.annotation.type==="file_citation"&&p.enqueue({type:"source",sourceType:"document",id:(M=(pe=(ce=i.config).generateId)==null?void 0:pe.call(ce))!=null?M:ar(),mediaType:"text/plain",title:(D=(R=y.annotation.quote)!=null?R:y.annotation.filename)!=null?D:"Document",filename:(N=y.annotation.filename)!=null?N:y.annotation.file_id}):uD(y)&&p.enqueue({type:"error",error:y})},flush(h){const p={openai:{responseId:f}};u.length>0&&(p.openai.logprobs=u),v!==void 0&&(p.openai.serviceTier=v),h.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p})}})),request:{body:e},response:{headers:s}}}};function rD(t){return t.type==="response.output_text.delta"}function nD(t){return t.type==="response.output_item.done"}function aD(t){return t.type==="response.completed"||t.type==="response.incomplete"}function sD(t){return t.type==="response.created"}function oD(t){return t.type==="response.function_call_arguments.delta"}function iD(t){return t.type==="response.code_interpreter_call_code.delta"}function lD(t){return t.type==="response.code_interpreter_call_code.done"}function Z0(t){return t.type==="response.output_item.added"}function cD(t){return t.type==="response.output_text.annotation.added"}function uD(t){return t.type==="error"}function dD(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"),a={systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}function V0(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find":return{action:{type:"find",url:t.url,pattern:t.pattern}}}}var pD=_t(()=>De(I({instructions:E().nullish(),speed:Z().min(.25).max(4).default(1).nullish()}))),fD=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:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await tn({provider:"openai",providerOptions:o,schema:pD}),c={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const f in u){const g=u[f];g!==void 0&&(c[f]=g)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:c}=await sr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:s,failedResponseHandler:sn,successfulResponseHandler:ON(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:c}}}},hD=_t(()=>De(I({text:E(),language:E().nullish(),duration:Z().nullish(),words:oe(I({word:E(),start:Z(),end:Z()})).nullish(),segments:oe(I({id:Z(),seek:Z(),start:Z(),end:Z(),text:E(),tokens:oe(Z()),temperature:Z(),avg_logprob:Z(),compression_ratio:Z(),no_speech_prob:Z()})).nullish()}))),mD=_t(()=>De(I({include:oe(E()).optional(),language:E().optional(),prompt:E().optional(),temperature:Z().min(0).max(1).default(0).optional(),timestampGranularities:oe(ht(["word","segment"])).default(["segment"]).optional()}))),H0={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"},vD=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 a=[],n=await tn({provider:"openai",providerOptions:r,schema:mD}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([gl(t)]);s.append("model",this.modelId);const i=yN(e);if(s.append("file",new File([o],"audio",{type:e}),`audio.${i}`),n){const l={include:n.include,language:n.language,prompt:n.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:n.temperature,timestamp_granularities:n.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const f of u)s.append(`${c}[]`,String(f));else s.append(c,String(u))}return{formData:s,warnings:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const c=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:u,warnings:f}=await this.getArgs(t),{value:g,responseHeaders:d,rawValue:m}=await CN({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),formData:u,failedResponseHandler:sn,successfulResponseHandler:Dr(hD),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=g.language!=null&&g.language in H0?H0[g.language]:void 0;return{text:g.text,segments:(i=(o=(n=g.segments)==null?void 0:n.map(h=>({text:h.text,startSecond:h.start,endSecond:h.end})))!=null?o:(s=g.words)==null?void 0:s.map(h=>({text:h.word,startSecond:h.start,endSecond:h.end})))!=null?i:[],language:v,durationInSeconds:(l=g.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:d,body:m}}}},gD="2.0.53";function B0(t={}){var e,r;const a=(e=Vd(co({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>aa({Authorization:`Bearer ${gy({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${gD}`),o=v=>new c9(v,{provider:`${n}.chat`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),i=v=>new g9(v,{provider:`${n}.completion`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),l=v=>new w9(v,{provider:`${n}.embedding`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),c=v=>new $9(v,{provider:`${n}.image`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),u=v=>new vD(v,{provider:`${n}.transcription`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),f=v=>new fD(v,{provider:`${n}.speech`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch}),g=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(v)},d=v=>new tD(v,{provider:`${n}.responses`,url:({path:h})=>`${a}${h}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),m=function(v){return g(v)};return m.languageModel=g,m.chat=o,m.completion=i,m.responses=d,m.embedding=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=u,m.transcriptionModel=u,m.speech=f,m.speechModel=f,m.tools=G9,m}B0();function Eo(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function yD(t){const e=[];for(const{role:r,content:a,...n}of t){const s=Eo({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...Eo(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=Eo(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${ia(o.data)}`},...i}}else throw new Ar({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const c=Eo(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=Eo(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...c})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function J0({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 G0(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 gp=I({user:E().optional(),reasoningEffort:E().optional(),textVerbosity:E().optional()}),_D=I({error:I({message:E(),type:E().nullish(),param:_r().nullish(),code:He([E(),Z()]).nullish()})}),wD={errorSchema:_D,errorToMessage:t=>t.error.message};function bD({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new Ar({functionality:`tool choice type: ${s}`})}}}var ED=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:wD;this.chunkSchema=$D(n.errorSchema),this.failedResponseHandler=oa(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!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:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:f,tools:g}){var d,m,v,h;const p=[],_=Object.assign((d=await tn({provider:"openai-compatible",providerOptions:i,schema:gp}))!=null?d:{},(m=await tn({provider:this.providerOptionsName,providerOptions:i,schema:gp}))!=null?m:{});n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:b,toolWarnings:S}=bD({tools:g,toolChoice:f});return{args:{model:this.modelId,user:_.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((h=i==null?void 0:i[this.providerOptionsName])!=null?h:{}).filter(([x])=>!Object.keys(gp.shape).includes(x))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:yD(t),tools:w,tool_choice:b},warnings:[...p,...S]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,m,v,h,p;const{args:_,warnings:w}=await this.getArgs({...t}),b=JSON.stringify(_),{responseHeaders:S,value:x,rawValue:k}=await sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Dr(SD),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=x.choices[0],O=[],H=A.message.content;H!=null&&H.length>0&&O.push({type:"text",text:H});const J=(e=A.message.reasoning_content)!=null?e:A.message.reasoning;if(J!=null&&J.length>0&&O.push({type:"reasoning",text:J}),A.message.tool_calls!=null)for(const U of A.message.tool_calls)O.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:ar(),toolName:U.function.name,input:U.function.arguments});const K={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:k}))},z=(s=x.usage)==null?void 0:s.completion_tokens_details;return(z==null?void 0:z.accepted_prediction_tokens)!=null&&(K[this.providerOptionsName].acceptedPredictionTokens=z==null?void 0:z.accepted_prediction_tokens),(z==null?void 0:z.rejected_prediction_tokens)!=null&&(K[this.providerOptionsName].rejectedPredictionTokens=z==null?void 0:z.rejected_prediction_tokens),{content:O,finishReason:G0(A.finish_reason),usage:{inputTokens:(i=(o=x.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=x.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=x.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(m=(d=(g=x.usage)==null?void 0:g.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?m:void 0,cachedInputTokens:(p=(h=(v=x.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:h.cached_tokens)!=null?p:void 0},providerMetadata:K,request:{body:b},response:{...J0(x),headers:S,body:k},warnings:w}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Gt(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:uo(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let f=!0;const g=this.providerOptionsName;let d=!1,m=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:a})},transform(v,h){var p,_,w,b,S,x,k,A,O,H,J,K,z;if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",h.enqueue({type:"error",error:v.error});return}const U=v.value;if(s==null||s.processChunk(v.rawValue),"error"in U){c="error",h.enqueue({type:"error",error:U.error.message});return}if(f&&(f=!1,h.enqueue({type:"response-metadata",...J0(U)})),U.usage!=null){const{prompt_tokens:ce,completion_tokens:pe,total_tokens:M,prompt_tokens_details:R,completion_tokens_details:D}=U.usage;u.promptTokens=ce??void 0,u.completionTokens=pe??void 0,u.totalTokens=M??void 0,(D==null?void 0:D.reasoning_tokens)!=null&&(u.completionTokensDetails.reasoningTokens=D==null?void 0:D.reasoning_tokens),(D==null?void 0:D.accepted_prediction_tokens)!=null&&(u.completionTokensDetails.acceptedPredictionTokens=D==null?void 0:D.accepted_prediction_tokens),(D==null?void 0:D.rejected_prediction_tokens)!=null&&(u.completionTokensDetails.rejectedPredictionTokens=D==null?void 0:D.rejected_prediction_tokens),(R==null?void 0:R.cached_tokens)!=null&&(u.promptTokensDetails.cachedTokens=R==null?void 0:R.cached_tokens)}const G=U.choices[0];if((G==null?void 0:G.finish_reason)!=null&&(c=G0(G.finish_reason)),(G==null?void 0:G.delta)==null)return;const se=G.delta,ne=(p=se.reasoning_content)!=null?p:se.reasoning;if(ne&&(d||(h.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),h.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ne})),se.content&&(m||(h.enqueue({type:"text-start",id:"txt-0"}),m=!0),h.enqueue({type:"text-delta",id:"txt-0",delta:se.content})),se.tool_calls!=null)for(const ce of se.tool_calls){const pe=ce.index;if(l[pe]==null){if(ce.id==null)throw new Xs({data:ce,message:"Expected 'id' to be a string."});if(((_=ce.function)==null?void 0:_.name)==null)throw new Xs({data:ce,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:ce.id,toolName:ce.function.name}),l[pe]={id:ce.id,type:"function",function:{name:ce.function.name,arguments:(w=ce.function.arguments)!=null?w:""},hasFinished:!1};const R=l[pe];((b=R.function)==null?void 0:b.name)!=null&&((S=R.function)==null?void 0:S.arguments)!=null&&(R.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),hl(R.function.arguments)&&(h.enqueue({type:"tool-input-end",id:R.id}),h.enqueue({type:"tool-call",toolCallId:(x=R.id)!=null?x:ar(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const M=l[pe];M.hasFinished||(((k=ce.function)==null?void 0:k.arguments)!=null&&(M.function.arguments+=(O=(A=ce.function)==null?void 0:A.arguments)!=null?O:""),h.enqueue({type:"tool-input-delta",id:M.id,delta:(H=ce.function.arguments)!=null?H:""}),((J=M.function)==null?void 0:J.name)!=null&&((K=M.function)==null?void 0:K.arguments)!=null&&hl(M.function.arguments)&&(h.enqueue({type:"tool-input-end",id:M.id}),h.enqueue({type:"tool-call",toolCallId:(z=M.id)!=null?z:ar(),toolName:M.function.name,input:M.function.arguments}),M.hasFinished=!0))}},flush(v){var h,p,_,w,b,S;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),m&&v.enqueue({type:"text-end",id:"txt-0"});for(const k of l.filter(A=>!A.hasFinished))v.enqueue({type:"tool-input-end",id:k.id}),v.enqueue({type:"tool-call",toolCallId:(h=k.id)!=null?h:ar(),toolName:k.function.name,input:k.function.arguments});const x={[g]:{},...s==null?void 0:s.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(x[g].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(x[g].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(p=u.promptTokens)!=null?p:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(w=u.totalTokens)!=null?w:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(S=u.promptTokensDetails.cachedTokens)!=null?S:void 0},providerMetadata:x})}})),request:{body:n},response:{headers:o}}}},K0=I({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:I({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:I({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish(),SD=I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({message:I({role:W("assistant").nullish(),content:E().nullish(),reasoning_content:E().nullish(),reasoning:E().nullish(),tool_calls:oe(I({id:E().nullish(),function:I({name:E(),arguments:E()})})).nullish()}),finish_reason:E().nullish()})),usage:K0}),$D=t=>He([I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({delta:I({role:ht(["assistant"]).nullish(),content:E().nullish(),reasoning_content:E().nullish(),reasoning:E().nullish(),tool_calls:oe(I({index:Z(),id:E().nullish(),function:I({name:E().nullish(),arguments:E().nullish()})})).nullish()}).nullish(),finish_reason:E().nullish()})),usage:K0}),t]);I({echo:Pt().optional(),logitBias:kt(E(),Z()).optional(),suffix:E().optional(),user:E().optional()});var PD=I({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()});I({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(I({text:E(),finish_reason:E()})),usage:PD.nullish()}),I({dimensions:Z().optional(),user:E().optional()}),I({data:oe(I({embedding:oe(Z())})),usage:I({prompt_tokens:Z()}).nullish(),providerMetadata:kt(E(),kt(E(),_r())).optional()}),I({data:oe(I({b64_json:E()}))});var W0=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}}},kD={extractMetadata:async({parsedBody:t})=>{const e=await jr({value:t,schema:xD});return!e.success||e.value.usage==null?void 0:W0(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await jr({value:e,schema:ID});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>W0(t)}}},Q0=I({prompt_cache_hit_tokens:Z().nullish(),prompt_cache_miss_tokens:Z().nullish()}),xD=I({usage:Q0.nullish()}),ID=I({choices:oe(I({finish_reason:E().nullish()})).nullish(),usage:Q0.nullish()}),TD="1.0.23";function Y0(t={}){var e;const r=Vd((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>aa({Authorization:`Bearer ${gy({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${TD}`),n=o=>new ED(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:kD}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new Pd({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new Pd({modelId:o,modelType:"imageModel"})},s}Y0();const yp=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=RN({description:n,inputSchema:ml({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}},CD={openai:B0,deepseek:Y0};class RD{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!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 a=e.providerType;let n;typeof a=="string"?n=CD[a]:n=a,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Bs(new URL(e.url)):"type"in e&&e.type==="extension"?r=new pv(e.sessionId):r=e;const a=new cv({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await a.connect(r),a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n;try{const s=e.__transport__;if(s&&s instanceof Ks||s&&s instanceof Js)return;await((r=s==null?void 0:s.terminateSession)==null?void 0:r.call(s)),await((a=s==null?void 0:s.close)==null?void 0:a.call(s)),await((n=e==null?void 0:e.close)==null?void 0:n.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{try{const s=n?await yp(n):null;return{serverName:a,tools:s}}catch(s){return this.onError&&this.onError((s==null?void 0:s.message)||"Failed to query tools",s),console.error("Failed to query tools",s),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{const s=n&&typeof n=="object"?n:{};this.mcpTools[a]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var s,o;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);if(!a)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=a;const n=await yp(a);return this.mcpTools[e]=n&&typeof n=="object"?n:{},this.mcpServers[e]=r,(o=this.onUpdatedTools)==null||o.call(this),a}async removeMcpServer(e){var n;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 a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:dp(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(_j,e)}async chatStream(e){return this._chat(Lj,e)}}Ze.AgentModelProvider=RD,Ze.Ajv=mS,Ze.AuthClientProvider=Xx,Ze.ContentScriptServerTransport=aT,Ze.ExtensionClientTransport=pv,Ze.ExtensionPageServerTransport=nT,Ze.InMemoryTransport=Ks,Ze.QrCode=Nv,Ze.ResourceTemplate=qI,Ze.UriTemplate=yn,Ze.WebMcpClient=cv,Ze.WebMcpServer=BI,Ze.completable=LI,Ze.createMessageChannelClientTransport=XI,Ze.createMessageChannelPairTransport=GI,Ze.createMessageChannelServerTransport=JI,Ze.createRemoter=GT,Ze.createSSEClientTransport=QI,Ze.createStreamableHTTPClientTransport=YI,Ze.getAISDKTools=yp,Ze.getDisplayName=HI,Ze.isMcpClient=rT,Ze.isMcpServer=WI,Ze.isMessageChannelClientTransport=tT,Ze.isMessageChannelServerTransport=KI,Ze.isSSEClientTransport=eT,Ze.isStreamableHTTPClientTransport=uv,Ze.z=f$,Object.defineProperty(Ze,Symbol.toStringTag,{value:"Module"})});
585
+ `;break}case"tool":throw new cn({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
586
+ `,{prompt:r,stopSequences:[`
587
+ ${t}:`]}}function j1({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function L1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var zP=bt(()=>Ne(C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({text:p(),finish_reason:p(),logprobs:C({tokens:A(p()),token_logprobs:A(O()),top_logprobs:A(fe(p(),O())).nullish()}).nullish()})),usage:C({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}))),DP=bt(()=>Ne(ne([C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({text:p(),finish_reason:p().nullish(),index:O(),logprobs:C({tokens:A(p()),token_logprobs:A(O()),top_logprobs:A(fe(p(),O())).nullish()}).nullish()})),usage:C({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}),kd]))),z1=bt(()=>Ne(C({echo:le().optional(),logitBias:fe(p(),O()).optional(),suffix:p().optional(),user:p().optional(),logprobs:ne([le(),O()]).optional()}))),ZP=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:y}){const f=[],g={...await On({provider:"openai",providerOptions:y,schema:z1}),...await On({provider:this.providerOptionsName,providerOptions:y,schema:z1})};o!=null&&f.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&f.push({type:"unsupported-setting",setting:"tools"}),u!=null&&f.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:m}=LP({prompt:e}),d=[...m??[],...i??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:(g==null?void 0:g.logprobs)===!0?0:(g==null?void 0:g.logprobs)===!1||g==null?void 0:g.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:h,prompt:v,stop:d.length>0?d:void 0},warnings:f}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await pn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:o,failedResponseHandler:Nn,successfulResponseHandler:zr(zP),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:L1(c.finish_reason),request:{body:o},response:{...j1(i),headers:a,body:l},providerMetadata:u,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await pn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:r,failedResponseHandler:Nn,successfulResponseHandler:ji(DP),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:n})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",h.enqueue({type:"error",error:u.error});return}const y=u.value;if("error"in y){a="error",h.enqueue({type:"error",error:y.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...j1(y)}),h.enqueue({type:"text-start",id:"0"})),y.usage!=null&&(l.inputTokens=y.usage.prompt_tokens,l.outputTokens=y.usage.completion_tokens,l.totalTokens=y.usage.total_tokens);const f=y.choices[0];(f==null?void 0:f.finish_reason)!=null&&(a=L1(f.finish_reason)),(f==null?void 0:f.logprobs)!=null&&(i.openai.logprobs=f.logprobs),(f==null?void 0:f.text)!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},UP=bt(()=>Ne(C({dimensions:O().optional(),user:p().optional()}))),qP=bt(()=>Ne(C({data:A(C({embedding:A(O())})),usage:C({prompt_tokens:O()}).nullish()}))),VP=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new o$({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await On({provider:"openai",providerOptions:r,schema:UP}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await pn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Jt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Nn,successfulResponseHandler:zr(qP),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},FP=bt(()=>Ne(C({data:A(C({b64_json:p(),revised_prompt:p().nullish()}))}))),BP={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},HP=new Set(["gpt-image-1","gpt-image-1-mini"]),JP=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=BP[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,c,u,h;const y=[];r!=null&&y.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&y.push({type:"unsupported-setting",setting:"seed"});const f=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:g,responseHeaders:v}=await pn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Jt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(h=s.openai)!=null?h:{},...HP.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Nn,successfulResponseHandler:zr(FP),abortSignal:i,fetch:this.config.fetch});return{images:g.data.map(m=>m.b64_json),warnings:y,response:{timestamp:f,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:g.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},WP=mt(()=>Ne(C({code:p().nullish(),containerId:p()}))),GP=mt(()=>Ne(C({outputs:A(rt("type",[C({type:N("logs"),logs:p()}),C({type:N("image"),url:p()})])).nullish()}))),KP=mt(()=>Ne(C({container:ne([p(),C({fileIds:A(p()).optional()})]).optional()}))),YP=Co({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:WP,outputSchema:GP}),QP=(e={})=>YP(e),D1=C({key:p(),type:Se(["eq","ne","gt","gte","lt","lte"]),value:ne([p(),O(),le()])}),Z1=C({type:Se(["and","or"]),filters:A(ne([D1,yh(()=>Z1)]))}),XP=mt(()=>Ne(C({vectorStoreIds:A(p()),maxNumResults:O().optional(),ranking:C({ranker:p().optional(),scoreThreshold:O().optional()}).optional(),filters:ne([D1,Z1]).optional()}))),eR=mt(()=>Ne(C({queries:A(p()),results:A(C({attributes:fe(p(),Ze()),fileId:p(),filename:p(),score:O(),text:p()})).nullable()}))),tR=Co({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:eR}),nR=mt(()=>Ne(C({background:Se(["auto","opaque","transparent"]).optional(),inputFidelity:Se(["low","high"]).optional(),inputImageMask:C({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:Se(["auto"]).optional(),outputCompression:O().int().min(0).max(100).optional(),outputFormat:Se(["png","jpeg","webp"]).optional(),partialImages:O().int().min(0).max(3).optional(),quality:Se(["auto","low","medium","high"]).optional(),size:Se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),rR=mt(()=>Ne(C({}))),oR=mt(()=>Ne(C({result:p()}))),sR=Co({id:"openai.image_generation",name:"image_generation",inputSchema:rR,outputSchema:oR}),aR=(e={})=>sR(e),U1=mt(()=>Ne(C({action:C({type:N("exec"),command:A(p()),timeoutMs:O().optional(),user:p().optional(),workingDirectory:p().optional(),env:fe(p(),p()).optional()})}))),q1=mt(()=>Ne(C({output:p()}))),iR=Co({id:"openai.local_shell",name:"local_shell",inputSchema:U1,outputSchema:q1}),lR=mt(()=>Ne(C({externalWebAccess:le().optional(),filters:C({allowedDomains:A(p()).optional()}).optional(),searchContextSize:Se(["low","medium","high"]).optional(),userLocation:C({type:N("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),cR=mt(()=>Ne(C({}))),uR=mt(()=>Ne(C({action:rt("type",[C({type:N("search"),query:p().optional()}),C({type:N("openPage"),url:p()}),C({type:N("find"),url:p(),pattern:p()})]),sources:A(rt("type",[C({type:N("url"),url:p()}),C({type:N("api"),name:p()})])).optional()}))),dR=Co({id:"openai.web_search",name:"web_search",inputSchema:cR,outputSchema:uR}),pR=(e={})=>dR(e),fR=mt(()=>Ne(C({searchContextSize:Se(["low","medium","high"]).optional(),userLocation:C({type:N("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),hR=mt(()=>Ne(C({}))),mR=mt(()=>Ne(C({action:rt("type",[C({type:N("search"),query:p().optional()}),C({type:N("openPage"),url:p()}),C({type:N("find"),url:p(),pattern:p()})])}))),gR=Co({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:hR,outputSchema:mR}),yR={codeInterpreter:QP,fileSearch:tR,imageGeneration:aR,localShell:iR,webSearchPreview:gR,webSearch:pR};function V1(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function vR({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:o=!1}){var s,a,i,l;const c=[],u=[];for(const{role:h,content:y}of e)switch(h){case"system":{switch(t){case"system":{c.push({role:"system",content:y});break}case"developer":{c.push({role:"developer",content:y});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const f=t;throw new Error(`Unsupported system message mode: ${f}`)}}break}case"user":{c.push({role:"user",content:y.map((f,g)=>{var v,m,d;switch(f.type){case"text":return{type:"input_text",text:f.text};case"file":if(f.mediaType.startsWith("image/")){const w=f.mediaType==="image/*"?"image/jpeg":f.mediaType;return{type:"input_image",...f.data instanceof URL?{image_url:f.data.toString()}:typeof f.data=="string"&&V1(f.data,n)?{file_id:f.data}:{image_url:`data:${w};base64,${Dr(f.data)}`},detail:(m=(v=f.providerOptions)==null?void 0:v.openai)==null?void 0:m.imageDetail}}else{if(f.mediaType==="application/pdf")return f.data instanceof URL?{type:"input_file",file_url:f.data.toString()}:{type:"input_file",...typeof f.data=="string"&&V1(f.data,n)?{file_id:f.data}:{filename:(d=f.filename)!=null?d:`part-${g}.pdf`,file_data:`data:application/pdf;base64,${Dr(f.data)}`}};throw new cn({functionality:`file part media type ${f.mediaType}`})}}})});break}case"assistant":{const f={},g={};for(const v of y)switch(v.type){case"text":{const m=(a=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:a.itemId;if(r&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:m});break}case"tool-call":{if(g[v.toolCallId]=v,v.providerExecuted)break;const m=(l=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(r&&m!=null){c.push({type:"item_reference",id:m});break}if(o&&v.toolName==="local_shell"){const d=await pr({value:v.input,schema:U1});c.push({type:"local_shell_call",call_id:v.toolCallId,id:m,action:{type:"exec",command:d.action.command,timeout_ms:d.action.timeoutMs,user:d.action.user,working_directory:d.action.workingDirectory,env:d.action.env}});break}c.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:m});break}case"tool-result":{r?c.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 m=await On({provider:"openai",providerOptions:v.providerOptions,schema:_R}),d=m==null?void 0:m.itemId;if(d!=null){const w=f[d];if(r)w===void 0&&(c.push({type:"item_reference",id:d}),f[d]={type:"reasoning",id:d,summary:[]});else{const _=[];v.text.length>0?_.push({type:"summary_text",text:v.text}):w!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),w===void 0?(f[d]={type:"reasoning",id:d,encrypted_content:m==null?void 0:m.reasoningEncryptedContent,summary:_},c.push(f[d])):(w.summary.push(..._),(m==null?void 0:m.reasoningEncryptedContent)!=null&&(w.encrypted_content=m.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 f of y){const g=f.output;if(o&&f.toolName==="local_shell"&&g.type==="json"){const m=await pr({value:g.value,schema:q1});c.push({type:"local_shell_call_output",call_id:f.toolCallId,output:m.output});break}let v;switch(g.type){case"text":case"error-text":v=g.value;break;case"json":case"error-json":v=JSON.stringify(g.value);break;case"content":v=g.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:f.toolCallId,output:v})}break}default:{const f=h;throw new Error(`Unsupported role: ${f}`)}}return{input:c,warnings:u}}var _R=C({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function F1({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var wR=bt(()=>Ne(ne([C({type:N("response.output_text.delta"),item_id:p(),delta:p(),logprobs:A(C({token:p(),logprob:O(),top_logprobs:A(C({token:p(),logprob:O()}))})).nullish()}),C({type:Se(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:p()}).nullish(),usage:C({input_tokens:O(),input_tokens_details:C({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:C({reasoning_tokens:O().nullish()}).nullish()}),service_tier:p().nullish()})}),C({type:N("response.created"),response:C({id:p(),created_at:O(),model:p(),service_tier:p().nullish()})}),C({type:N("response.output_item.added"),output_index:O(),item:rt("type",[C({type:N("message"),id:p()}),C({type:N("reasoning"),id:p(),encrypted_content:p().nullish()}),C({type:N("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),C({type:N("web_search_call"),id:p(),status:p()}),C({type:N("computer_call"),id:p(),status:p()}),C({type:N("file_search_call"),id:p()}),C({type:N("image_generation_call"),id:p()}),C({type:N("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:A(rt("type",[C({type:N("logs"),logs:p()}),C({type:N("image"),url:p()})])).nullable(),status:p()})])}),C({type:N("response.output_item.done"),output_index:O(),item:rt("type",[C({type:N("message"),id:p()}),C({type:N("reasoning"),id:p(),encrypted_content:p().nullish()}),C({type:N("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:N("completed")}),C({type:N("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:A(rt("type",[C({type:N("logs"),logs:p()}),C({type:N("image"),url:p()})])).nullable()}),C({type:N("image_generation_call"),id:p(),result:p()}),C({type:N("web_search_call"),id:p(),status:p(),action:rt("type",[C({type:N("search"),query:p().nullish(),sources:A(rt("type",[C({type:N("url"),url:p()}),C({type:N("api"),name:p()})])).nullish()}),C({type:N("open_page"),url:p()}),C({type:N("find"),url:p(),pattern:p()})])}),C({type:N("file_search_call"),id:p(),queries:A(p()),results:A(C({attributes:fe(p(),Ze()),file_id:p(),filename:p(),score:O(),text:p()})).nullish()}),C({type:N("local_shell_call"),id:p(),call_id:p(),action:C({type:N("exec"),command:A(p()),timeout_ms:O().optional(),user:p().optional(),working_directory:p().optional(),env:fe(p(),p()).optional()})}),C({type:N("computer_call"),id:p(),status:N("completed")})])}),C({type:N("response.function_call_arguments.delta"),item_id:p(),output_index:O(),delta:p()}),C({type:N("response.image_generation_call.partial_image"),item_id:p(),output_index:O(),partial_image_b64:p()}),C({type:N("response.code_interpreter_call_code.delta"),item_id:p(),output_index:O(),delta:p()}),C({type:N("response.code_interpreter_call_code.done"),item_id:p(),output_index:O(),code:p()}),C({type:N("response.output_text.annotation.added"),annotation:rt("type",[C({type:N("url_citation"),start_index:O(),end_index:O(),url:p(),title:p()}),C({type:N("file_citation"),file_id:p(),filename:p().nullish(),index:O().nullish(),start_index:O().nullish(),end_index:O().nullish(),quote:p().nullish()})])}),C({type:N("response.reasoning_summary_part.added"),item_id:p(),summary_index:O()}),C({type:N("response.reasoning_summary_text.delta"),item_id:p(),summary_index:O(),delta:p()}),C({type:N("response.reasoning_summary_part.done"),item_id:p(),summary_index:O()}),C({type:N("error"),sequence_number:O(),error:C({type:p(),code:p(),message:p(),param:p().nullish()})}),C({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),bR=bt(()=>Ne(C({id:p().optional(),created_at:O().optional(),error:C({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:A(rt("type",[C({type:N("message"),role:N("assistant"),id:p(),content:A(C({type:N("output_text"),text:p(),logprobs:A(C({token:p(),logprob:O(),top_logprobs:A(C({token:p(),logprob:O()}))})).nullish(),annotations:A(rt("type",[C({type:N("url_citation"),start_index:O(),end_index:O(),url:p(),title:p()}),C({type:N("file_citation"),file_id:p(),filename:p().nullish(),index:O().nullish(),start_index:O().nullish(),end_index:O().nullish(),quote:p().nullish()}),C({type:N("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:O().nullish(),end_index:O().nullish(),index:O().nullish()}),C({type:N("file_path"),file_id:p(),index:O().nullish()})]))}))}),C({type:N("web_search_call"),id:p(),status:p(),action:rt("type",[C({type:N("search"),query:p().nullish(),sources:A(rt("type",[C({type:N("url"),url:p()}),C({type:N("api"),name:p()})])).nullish()}),C({type:N("open_page"),url:p()}),C({type:N("find"),url:p(),pattern:p()})])}),C({type:N("file_search_call"),id:p(),queries:A(p()),results:A(C({attributes:fe(p(),ne([p(),O(),le()])),file_id:p(),filename:p(),score:O(),text:p()})).nullish()}),C({type:N("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:A(rt("type",[C({type:N("logs"),logs:p()}),C({type:N("image"),url:p()})])).nullable()}),C({type:N("image_generation_call"),id:p(),result:p()}),C({type:N("local_shell_call"),id:p(),call_id:p(),action:C({type:N("exec"),command:A(p()),timeout_ms:O().optional(),user:p().optional(),working_directory:p().optional(),env:fe(p(),p()).optional()})}),C({type:N("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),C({type:N("computer_call"),id:p(),status:p().optional()}),C({type:N("reasoning"),id:p(),encrypted_content:p().nullish(),summary:A(C({type:N("summary_text"),text:p()}))})])).optional(),service_tier:p().nullish(),incomplete_details:C({reason:p()}).nullish(),usage:C({input_tokens:O(),input_tokens_details:C({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:C({reasoning_tokens:O().nullish()}).nullish()}).optional()}))),B1=20,SR=bt(()=>Ne(C({conversation:p().nullish(),include:A(Se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:ne([le(),O().min(1).max(B1)]).optional(),maxToolCalls:O().nullish(),metadata:Mt().nullish(),parallelToolCalls:le().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:Se(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:Se(["auto","flex","priority","default"]).nullish(),store:le().nullish(),strictJsonSchema:le().nullish(),textVerbosity:Se(["low","medium","high"]).nullish(),truncation:Se(["auto","disabled"]).nullish(),user:p().nullish()})));async function CR({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await pr({value:a.args,schema:XP});o.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":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await pr({value:a.args,schema:fR});o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await pr({value:a.args,schema:lR});o.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 pr({value:a.args,schema:KP});o.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 pr({value:a.args,schema:nR});o.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:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new cn({functionality:`tool choice type: ${a}`})}}}var $R=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:y}){var f,g,v,m;const d=[],w=AR(this.modelId);o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),i!=null&&d.push({type:"unsupported-setting",setting:"seed"}),s!=null&&d.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&d.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&d.push({type:"unsupported-setting",setting:"stopSequences"});const _=await On({provider:"openai",providerOptions:c,schema:SR});_!=null&&_.conversation&&(_!=null&&_.previousResponseId)&&d.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:T}=await vR({prompt:l,systemMessageMode:w.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(f=_==null?void 0:_.store)!=null?f:!0,hasLocalShellTool:U("openai.local_shell")});d.push(...T);const P=(g=_==null?void 0:_.strictJsonSchema)!=null?g:!1;let E=_==null?void 0:_.include;function Z(ae){E==null?E=[ae]:E.includes(ae)||(E=[...E,ae])}function U(ae){return(u==null?void 0:u.find(ye=>ye.type==="provider-defined"&&ye.id===ae))!=null}const W=typeof(_==null?void 0:_.logprobs)=="number"?_==null?void 0:_.logprobs:(_==null?void 0:_.logprobs)===!0?B1:void 0;W&&Z("message.output_text.logprobs");const V=(v=u==null?void 0:u.find(ae=>ae.type==="provider-defined"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:v.name;V&&Z("web_search_call.action.sources"),U("openai.code_interpreter")&&Z("code_interpreter_call.outputs");const B=_==null?void 0:_.store;B===!1&&w.isReasoningModel&&Z("reasoning.encrypted_content");const J={model:this.modelId,input:b,temperature:t,top_p:r,max_output_tokens:e,...((y==null?void 0:y.type)==="json"||(_==null?void 0:_.textVerbosity))&&{text:{...(y==null?void 0:y.type)==="json"&&{format:y.schema!=null?{type:"json_schema",strict:P,name:(m=y.name)!=null?m:"response",description:y.description,schema:y.schema}:{type:"json_object"}},...(_==null?void 0:_.textVerbosity)&&{verbosity:_.textVerbosity}}},conversation:_==null?void 0:_.conversation,max_tool_calls:_==null?void 0:_.maxToolCalls,metadata:_==null?void 0:_.metadata,parallel_tool_calls:_==null?void 0:_.parallelToolCalls,previous_response_id:_==null?void 0:_.previousResponseId,store:B,user:_==null?void 0:_.user,instructions:_==null?void 0:_.instructions,service_tier:_==null?void 0:_.serviceTier,include:E,prompt_cache_key:_==null?void 0:_.promptCacheKey,prompt_cache_retention:_==null?void 0:_.promptCacheRetention,safety_identifier:_==null?void 0:_.safetyIdentifier,top_logprobs:W,truncation:_==null?void 0:_.truncation,...w.isReasoningModel&&((_==null?void 0:_.reasoningEffort)!=null||(_==null?void 0:_.reasoningSummary)!=null)&&{reasoning:{...(_==null?void 0:_.reasoningEffort)!=null&&{effort:_.reasoningEffort},...(_==null?void 0:_.reasoningSummary)!=null&&{summary:_.reasoningSummary}}}};w.isReasoningModel?(J.temperature!=null&&(J.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),J.top_p!=null&&(J.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((_==null?void 0:_.reasoningEffort)!=null&&d.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(_==null?void 0:_.reasoningSummary)!=null&&d.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(_==null?void 0:_.serviceTier)==="flex"&&!w.supportsFlexProcessing&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete J.service_tier),(_==null?void 0:_.serviceTier)==="priority"&&!w.supportsPriorityProcessing&&(d.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 J.service_tier);const{tools:H,toolChoice:ue,toolWarnings:Ce}=await CR({tools:u,toolChoice:h,strictJsonSchema:P});return{webSearchToolName:V,args:{...J,tools:H,tool_choice:ue},warnings:[...d,...Ce],store:B}}async doGenerate(e){var t,n,r,o,s,a,i,l,c,u,h,y,f,g,v,m,d,w,_,b,T,P,E,Z,U,W,V,B;const{args:J,warnings:H,webSearchToolName:ue}=await this.getArgs(e),Ce=this.config.url({path:"/responses",modelId:this.modelId}),ae=this.config.provider.replace(".responses",""),{responseHeaders:ye,value:he,rawValue:L}=await pn({url:Ce,headers:Jt(this.config.headers(),e.headers),body:J,failedResponseHandler:Nn,successfulResponseHandler:zr(bR),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new Ve({message:he.error.message,url:Ce,requestBodyValues:J,statusCode:400,responseHeaders:ye,responseBody:L,isRetryable:!1});const x=[],M=[];let R=!1;for(const S of he.output)switch(S.type){case"reasoning":{S.summary.length===0&&S.summary.push({type:"summary_text",text:""});for(const z of S.summary)x.push({type:"reasoning",text:z.text,providerMetadata:{[ae]:{itemId:S.id,reasoningEncryptedContent:(t=S.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:S.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:S.id,toolName:"image_generation",result:{result:S.result},providerExecuted:!0});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:S.call_id,toolName:"local_shell",input:JSON.stringify({action:S.action}),providerMetadata:{[ae]:{itemId:S.id}}});break}case"message":{for(const z of S.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&z.logprobs&&M.push(z.logprobs),x.push({type:"text",text:z.text,providerMetadata:{[ae]:{itemId:S.id}}});for(const D of z.annotations)D.type==="url_citation"?x.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:wt(),url:D.url,title:D.title}):D.type==="file_citation"?x.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:wt(),mediaType:"text/plain",title:(h=(u=D.quote)!=null?u:D.filename)!=null?h:"Document",filename:(y=D.filename)!=null?y:D.file_id,...D.file_id?{providerMetadata:{[ae]:{fileId:D.file_id}}}:{}}):D.type==="container_file_citation"?x.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:wt(),mediaType:"text/plain",title:(d=(m=D.filename)!=null?m:D.file_id)!=null?d:"Document",filename:(w=D.filename)!=null?w:D.file_id,providerMetadata:{[ae]:{fileId:D.file_id,containerId:D.container_id,...D.index!=null?{index:D.index}:{}}}}):D.type==="file_path"&&x.push({type:"source",sourceType:"document",id:(T=(b=(_=this.config).generateId)==null?void 0:b.call(_))!=null?T:wt(),mediaType:"application/octet-stream",title:D.file_id,filename:D.file_id,providerMetadata:{[ae]:{fileId:D.file_id,...D.index!=null?{index:D.index}:{}}}})}break}case"function_call":{R=!0,x.push({type:"tool-call",toolCallId:S.call_id,toolName:S.name,input:S.arguments,providerMetadata:{[ae]:{itemId:S.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:S.id,toolName:ue??"web_search",input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:S.id,toolName:ue??"web_search",result:J1(S.action),providerExecuted:!0});break}case"computer_call":{x.push({type:"tool-call",toolCallId:S.id,toolName:"computer_use",input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:S.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:S.status||"completed"},providerExecuted:!0});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:S.id,toolName:"file_search",input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:S.id,toolName:"file_search",result:{queries:S.queries,results:(E=(P=S.results)==null?void 0:P.map(z=>({attributes:z.attributes,fileId:z.file_id,filename:z.filename,score:z.score,text:z.text})))!=null?E:null},providerExecuted:!0});break}case"code_interpreter_call":{x.push({type:"tool-call",toolCallId:S.id,toolName:"code_interpreter",input:JSON.stringify({code:S.code,containerId:S.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:S.id,toolName:"code_interpreter",result:{outputs:S.outputs},providerExecuted:!0});break}}const $={[ae]:{...he.id!=null?{responseId:he.id}:{}}};M.length>0&&($[ae].logprobs=M),typeof he.service_tier=="string"&&($[ae].serviceTier=he.service_tier);const k=he.usage;return{content:x,finishReason:F1({finishReason:(Z=he.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:R}),usage:{inputTokens:k.input_tokens,outputTokens:k.output_tokens,totalTokens:k.input_tokens+k.output_tokens,reasoningTokens:(W=(U=k.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?W:void 0,cachedInputTokens:(B=(V=k.input_tokens_details)==null?void 0:V.cached_tokens)!=null?B:void 0},request:{body:J},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:ye,body:L},providerMetadata:$,warnings:H}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r,store:o}=await this.getArgs(e),{responseHeaders:s,value:a}=await pn({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Nn,successfulResponseHandler:ji(wR),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},h=[];let y=null;const f={},g=[];let v=!1;const m={};let d;return{stream:a.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,_){var b,T,P,E,Z,U,W,V,B,J,H,ue,Ce,ae,ye,he,L,x,M,R,$,k;if(e.includeRawChunks&&_.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",_.enqueue({type:"error",error:w.error});return}const S=w.value;if(H1(S))S.item.type==="function_call"?(f[S.output_index]={toolName:S.item.name,toolCallId:S.item.call_id},_.enqueue({type:"tool-input-start",id:S.item.call_id,toolName:S.item.name})):S.item.type==="web_search_call"?(f[S.output_index]={toolName:r??"web_search",toolCallId:S.item.id},_.enqueue({type:"tool-input-start",id:S.item.id,toolName:r??"web_search",providerExecuted:!0}),_.enqueue({type:"tool-input-end",id:S.item.id}),_.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:r??"web_search",input:JSON.stringify({}),providerExecuted:!0})):S.item.type==="computer_call"?(f[S.output_index]={toolName:"computer_use",toolCallId:S.item.id},_.enqueue({type:"tool-input-start",id:S.item.id,toolName:"computer_use",providerExecuted:!0})):S.item.type==="code_interpreter_call"?(f[S.output_index]={toolName:"code_interpreter",toolCallId:S.item.id,codeInterpreter:{containerId:S.item.container_id}},_.enqueue({type:"tool-input-start",id:S.item.id,toolName:"code_interpreter",providerExecuted:!0}),_.enqueue({type:"tool-input-delta",id:S.item.id,delta:`{"containerId":"${S.item.container_id}","code":"`})):S.item.type==="file_search_call"?_.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):S.item.type==="image_generation_call"?_.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):S.item.type==="message"?(g.splice(0,g.length),_.enqueue({type:"text-start",id:S.item.id,providerMetadata:{[l]:{itemId:S.item.id}}})):H1(S)&&S.item.type==="reasoning"&&(m[S.item.id]={encryptedContent:S.item.encrypted_content,summaryParts:{0:"active"}},_.enqueue({type:"reasoning-start",id:`${S.item.id}:0`,providerMetadata:{[l]:{itemId:S.item.id,reasoningEncryptedContent:(b=S.item.encrypted_content)!=null?b:null}}}));else if(TR(S)){if(S.item.type==="message")_.enqueue({type:"text-end",id:S.item.id,providerMetadata:{[l]:{itemId:S.item.id,...g.length>0&&{annotations:g}}}});else if(S.item.type==="function_call")f[S.output_index]=void 0,v=!0,_.enqueue({type:"tool-input-end",id:S.item.call_id}),_.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:S.item.name,input:S.item.arguments,providerMetadata:{[l]:{itemId:S.item.id}}});else if(S.item.type==="web_search_call")f[S.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:r??"web_search",result:J1(S.item.action),providerExecuted:!0});else if(S.item.type==="computer_call")f[S.output_index]=void 0,_.enqueue({type:"tool-input-end",id:S.item.id}),_.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),_.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:S.item.status||"completed"},providerExecuted:!0});else if(S.item.type==="file_search_call")f[S.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:"file_search",result:{queries:S.item.queries,results:(P=(T=S.item.results)==null?void 0:T.map(z=>({attributes:z.attributes,fileId:z.file_id,filename:z.filename,score:z.score,text:z.text})))!=null?P:null},providerExecuted:!0});else if(S.item.type==="code_interpreter_call")f[S.output_index]=void 0,_.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:"code_interpreter",result:{outputs:S.item.outputs},providerExecuted:!0});else if(S.item.type==="image_generation_call")_.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:"image_generation",result:{result:S.item.result},providerExecuted:!0});else if(S.item.type==="local_shell_call")f[S.output_index]=void 0,_.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:S.item.action.command,timeoutMs:S.item.action.timeout_ms,user:S.item.action.user,workingDirectory:S.item.action.working_directory,env:S.item.action.env}}),providerMetadata:{[l]:{itemId:S.item.id}}});else if(S.item.type==="reasoning"){const z=m[S.item.id],D=Object.entries(z.summaryParts).filter(([ve,ce])=>ce==="active"||ce==="can-conclude").map(([ve])=>ve);for(const ve of D)_.enqueue({type:"reasoning-end",id:`${S.item.id}:${ve}`,providerMetadata:{[l]:{itemId:S.item.id,reasoningEncryptedContent:(E=S.item.encrypted_content)!=null?E:null}}});delete m[S.item.id]}}else if(IR(S)){const z=f[S.output_index];z!=null&&_.enqueue({type:"tool-input-delta",id:z.toolCallId,delta:S.delta})}else if(PR(S)){const z=f[S.output_index];z!=null&&_.enqueue({type:"tool-input-delta",id:z.toolCallId,delta:JSON.stringify(S.delta).slice(1,-1)})}else if(RR(S)){const z=f[S.output_index];z!=null&&(_.enqueue({type:"tool-input-delta",id:z.toolCallId,delta:'"}'}),_.enqueue({type:"tool-input-end",id:z.toolCallId}),_.enqueue({type:"tool-call",toolCallId:z.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:S.code,containerId:z.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ER(S))y=S.response.id,_.enqueue({type:"response-metadata",id:S.response.id,timestamp:new Date(S.response.created_at*1e3),modelId:S.response.model});else if(kR(S))_.enqueue({type:"text-delta",id:S.item_id,delta:S.delta}),(U=(Z=e.providerOptions)==null?void 0:Z.openai)!=null&&U.logprobs&&S.logprobs&&h.push(S.logprobs);else if(S.type==="response.reasoning_summary_part.added"){if(S.summary_index>0){const z=m[S.item_id];z.summaryParts[S.summary_index]="active";for(const D of Object.keys(z.summaryParts))z.summaryParts[D]==="can-conclude"&&(_.enqueue({type:"reasoning-end",id:`${S.item_id}:${D}`,providerMetadata:{[l]:{itemId:S.item_id}}}),z.summaryParts[D]="concluded");_.enqueue({type:"reasoning-start",id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[l]:{itemId:S.item_id,reasoningEncryptedContent:(V=(W=m[S.item_id])==null?void 0:W.encryptedContent)!=null?V:null}}})}}else S.type==="response.reasoning_summary_text.delta"?_.enqueue({type:"reasoning-delta",id:`${S.item_id}:${S.summary_index}`,delta:S.delta,providerMetadata:{[l]:{itemId:S.item_id}}}):S.type==="response.reasoning_summary_part.done"?o?(_.enqueue({type:"reasoning-end",id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[l]:{itemId:S.item_id}}}),m[S.item_id].summaryParts[S.summary_index]="concluded"):m[S.item_id].summaryParts[S.summary_index]="can-conclude":xR(S)?(c=F1({finishReason:(B=S.response.incomplete_details)==null?void 0:B.reason,hasFunctionCall:v}),u.inputTokens=S.response.usage.input_tokens,u.outputTokens=S.response.usage.output_tokens,u.totalTokens=S.response.usage.input_tokens+S.response.usage.output_tokens,u.reasoningTokens=(H=(J=S.response.usage.output_tokens_details)==null?void 0:J.reasoning_tokens)!=null?H:void 0,u.cachedInputTokens=(Ce=(ue=S.response.usage.input_tokens_details)==null?void 0:ue.cached_tokens)!=null?Ce:void 0,typeof S.response.service_tier=="string"&&(d=S.response.service_tier)):OR(S)?(g.push(S.annotation),S.annotation.type==="url_citation"?_.enqueue({type:"source",sourceType:"url",id:(he=(ye=(ae=i.config).generateId)==null?void 0:ye.call(ae))!=null?he:wt(),url:S.annotation.url,title:S.annotation.title}):S.annotation.type==="file_citation"&&_.enqueue({type:"source",sourceType:"document",id:(M=(x=(L=i.config).generateId)==null?void 0:x.call(L))!=null?M:wt(),mediaType:"text/plain",title:($=(R=S.annotation.quote)!=null?R:S.annotation.filename)!=null?$:"Document",filename:(k=S.annotation.filename)!=null?k:S.annotation.file_id,...S.annotation.file_id?{providerMetadata:{[l]:{fileId:S.annotation.file_id}}}:{}})):NR(S)&&_.enqueue({type:"error",error:S})},flush(w){const _={[l]:{responseId:y}};h.length>0&&(_[l].logprobs=h),d!==void 0&&(_[l].serviceTier=d),w.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:_})}})),request:{body:t},response:{headers:s}}}};function kR(e){return e.type==="response.output_text.delta"}function TR(e){return e.type==="response.output_item.done"}function xR(e){return e.type==="response.completed"||e.type==="response.incomplete"}function ER(e){return e.type==="response.created"}function IR(e){return e.type==="response.function_call_arguments.delta"}function PR(e){return e.type==="response.code_interpreter_call_code.delta"}function RR(e){return e.type==="response.code_interpreter_call_code.done"}function H1(e){return e.type==="response.output_item.added"}function OR(e){return e.type==="response.output_text.annotation.added"}function NR(e){return e.type==="error"}function AR(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith("gpt-5-chat")?{...r,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?{...r,isReasoningModel:!0,systemMessageMode:"developer"}:{...r,isReasoningModel:!1}}function J1(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find":return{action:{type:"find",url:e.url,pattern:e.pattern}}}}var MR=bt(()=>Ne(C({instructions:p().nullish(),speed:O().min(.25).max(4).default(1).nullish()}))),jR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:s,providerOptions:a}){const i=[],l=await On({provider:"openai",providerOptions:a,schema:MR}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?c.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const u={};for(const h in u){const y=u[h];y!==void 0&&(c[h]=y)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await pn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:s,failedResponseHandler:Nn,successfulResponseHandler:RI(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},LR=bt(()=>Ne(C({text:p(),language:p().nullish(),duration:O().nullish(),words:A(C({word:p(),start:O(),end:O()})).nullish(),segments:A(C({id:O(),seek:O(),start:O(),end:O(),text:p(),tokens:A(O()),temperature:O(),avg_logprob:O(),compression_ratio:O(),no_speech_prob:O()})).nullish()}))),zR=bt(()=>Ne(C({include:A(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:O().min(0).max(1).default(0).optional(),timestampGranularities:A(Se(["word","segment"])).default(["segment"]).optional()}))),W1={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"},DR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await On({provider:"openai",providerOptions:n,schema:zR}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([kP(e)]);s.append("model",this.modelId);const i=_I(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const h of u)s.append(`${c}[]`,String(h));else s.append(c,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const c=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:u,warnings:h}=await this.getArgs(e),{value:y,responseHeaders:f,rawValue:g}=await PI({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Nn,successfulResponseHandler:zr(LR),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=y.language!=null&&y.language in W1?W1[y.language]:void 0;return{text:y.text,segments:(i=(a=(o=y.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(s=y.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:v,durationInSeconds:(l=y.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},ZR="2.0.75";function G1(e={}){var t,n;const r=(t=N1(vI({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>wd({Authorization:`Bearer ${b1({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${ZR}`),a=v=>new OP(v,{provider:`${o}.chat`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),i=v=>new ZP(v,{provider:`${o}.completion`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),l=v=>new VP(v,{provider:`${o}.embedding`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),c=v=>new JP(v,{provider:`${o}.image`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),u=v=>new DR(v,{provider:`${o}.transcription`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),h=v=>new jR(v,{provider:`${o}.speech`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),y=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new $R(v,{provider:`${o}.responses`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return y(v)};return g.languageModel=y,g.chat=a,g.completion=i,g.responses=f,g.embedding=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=h,g.speechModel=h,g.tools=yR,g}G1();function Js(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function UR(e){const t=[];for(const{role:n,content:r,...o}of e){const s=Js({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...Js(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=Js(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${Dr(a.data)}`},...i}}else throw new cn({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const c=Js(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=Js(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function K1({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function Y1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var xd=C({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional()}),qR=C({error:C({message:p(),type:p().nullish(),param:Mt().nullish(),code:ne([p(),O()]).nullish()})}),VR={errorSchema:qR,errorToMessage:e=>e.error.message};function FR({tools:e,toolChoice:t}){e=e!=null&&e.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new cn({functionality:`tool choice type: ${s}`})}}}var BR=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:VR;this.chunkSchema=JR(o.errorSchema),this.failedResponseHandler=k1(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:y}){var f,g,v,m;const d=[],w=Object.assign((f=await On({provider:"openai-compatible",providerOptions:i,schema:xd}))!=null?f:{},(g=await On({provider:this.providerOptionsName,providerOptions:i,schema:xd}))!=null?g:{});o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:_,toolChoice:b,toolWarnings:T}=FR({tools:y,toolChoice:h});return{args:{model:this.modelId,user:w.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i==null?void 0:i[this.providerOptionsName])!=null?m:{}).filter(([P])=>!Object.keys(xd.shape).includes(P))),reasoning_effort:w.reasoningEffort,verbosity:w.textVerbosity,messages:UR(e),tools:_,tool_choice:b},warnings:[...d,...T]}}async doGenerate(e){var t,n,r,o,s,a,i,l,c,u,h,y,f,g,v,m,d;const{args:w,warnings:_}=await this.getArgs({...e}),b=JSON.stringify(w),{responseHeaders:T,value:P,rawValue:E}=await pn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:w,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:zr(HR),abortSignal:e.abortSignal,fetch:this.config.fetch}),Z=P.choices[0],U=[],W=Z.message.content;W!=null&&W.length>0&&U.push({type:"text",text:W});const V=(t=Z.message.reasoning_content)!=null?t:Z.message.reasoning;if(V!=null&&V.length>0&&U.push({type:"reasoning",text:V}),Z.message.tool_calls!=null)for(const H of Z.message.tool_calls)U.push({type:"tool-call",toolCallId:(n=H.id)!=null?n:wt(),toolName:H.function.name,input:H.function.arguments});const B={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:E}))},J=(s=P.usage)==null?void 0:s.completion_tokens_details;return(J==null?void 0:J.accepted_prediction_tokens)!=null&&(B[this.providerOptionsName].acceptedPredictionTokens=J==null?void 0:J.accepted_prediction_tokens),(J==null?void 0:J.rejected_prediction_tokens)!=null&&(B[this.providerOptionsName].rejectedPredictionTokens=J==null?void 0:J.rejected_prediction_tokens),{content:U,finishReason:Y1(Z.finish_reason),usage:{inputTokens:(i=(a=P.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=P.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=P.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(g=(f=(y=P.usage)==null?void 0:y.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(d=(m=(v=P.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?d:void 0},providerMetadata:B,request:{body:b},response:{...K1(P),headers:T,body:E},warnings:_}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await pn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Jt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:ji(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const y=this.providerOptionsName;let f=!1,g=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:r})},transform(v,m){var d,w,_,b,T,P,E,Z,U,W,V,B,J;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",m.enqueue({type:"error",error:v.error});return}const H=v.value;if(s==null||s.processChunk(v.rawValue),"error"in H){c="error",m.enqueue({type:"error",error:H.error.message});return}if(h&&(h=!1,m.enqueue({type:"response-metadata",...K1(H)})),H.usage!=null){const{prompt_tokens:ye,completion_tokens:he,total_tokens:L,prompt_tokens_details:x,completion_tokens_details:M}=H.usage;u.promptTokens=ye??void 0,u.completionTokens=he??void 0,u.totalTokens=L??void 0,(M==null?void 0:M.reasoning_tokens)!=null&&(u.completionTokensDetails.reasoningTokens=M==null?void 0:M.reasoning_tokens),(M==null?void 0:M.accepted_prediction_tokens)!=null&&(u.completionTokensDetails.acceptedPredictionTokens=M==null?void 0:M.accepted_prediction_tokens),(M==null?void 0:M.rejected_prediction_tokens)!=null&&(u.completionTokensDetails.rejectedPredictionTokens=M==null?void 0:M.rejected_prediction_tokens),(x==null?void 0:x.cached_tokens)!=null&&(u.promptTokensDetails.cachedTokens=x==null?void 0:x.cached_tokens)}const ue=H.choices[0];if((ue==null?void 0:ue.finish_reason)!=null&&(c=Y1(ue.finish_reason)),(ue==null?void 0:ue.delta)==null)return;const Ce=ue.delta,ae=(d=Ce.reasoning_content)!=null?d:Ce.reasoning;if(ae&&(f||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ae})),Ce.content&&(g||(m.enqueue({type:"text-start",id:"txt-0"}),g=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:Ce.content})),Ce.tool_calls!=null)for(const ye of Ce.tool_calls){const he=ye.index;if(l[he]==null){if(ye.id==null)throw new Is({data:ye,message:"Expected 'id' to be a string."});if(((w=ye.function)==null?void 0:w.name)==null)throw new Is({data:ye,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ye.id,toolName:ye.function.name}),l[he]={id:ye.id,type:"function",function:{name:ye.function.name,arguments:(_=ye.function.arguments)!=null?_:""},hasFinished:!1};const x=l[he];((b=x.function)==null?void 0:b.name)!=null&&((T=x.function)==null?void 0:T.arguments)!=null&&(x.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:x.id,delta:x.function.arguments}),Mi(x.function.arguments)&&(m.enqueue({type:"tool-input-end",id:x.id}),m.enqueue({type:"tool-call",toolCallId:(P=x.id)!=null?P:wt(),toolName:x.function.name,input:x.function.arguments}),x.hasFinished=!0));continue}const L=l[he];L.hasFinished||(((E=ye.function)==null?void 0:E.arguments)!=null&&(L.function.arguments+=(U=(Z=ye.function)==null?void 0:Z.arguments)!=null?U:""),m.enqueue({type:"tool-input-delta",id:L.id,delta:(W=ye.function.arguments)!=null?W:""}),((V=L.function)==null?void 0:V.name)!=null&&((B=L.function)==null?void 0:B.arguments)!=null&&Mi(L.function.arguments)&&(m.enqueue({type:"tool-input-end",id:L.id}),m.enqueue({type:"tool-call",toolCallId:(J=L.id)!=null?J:wt(),toolName:L.function.name,input:L.function.arguments}),L.hasFinished=!0))}},flush(v){var m,d,w,_,b,T;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const E of l.filter(Z=>!Z.hasFinished))v.enqueue({type:"tool-input-end",id:E.id}),v.enqueue({type:"tool-call",toolCallId:(m=E.id)!=null?m:wt(),toolName:E.function.name,input:E.function.arguments});const P={[y]:{},...s==null?void 0:s.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(P[y].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(P[y].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(d=u.promptTokens)!=null?d:void 0,outputTokens:(w=u.completionTokens)!=null?w:void 0,totalTokens:(_=u.totalTokens)!=null?_:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(T=u.promptTokensDetails.cachedTokens)!=null?T:void 0},providerMetadata:P})}})),request:{body:o},response:{headers:a}}}},Q1=C({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:C({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish(),HR=C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({message:C({role:N("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:A(C({id:p().nullish(),function:C({name:p(),arguments:p()})})).nullish()}),finish_reason:p().nullish()})),usage:Q1}),JR=e=>ne([C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({delta:C({role:Se(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:A(C({index:O(),id:p().nullish(),function:C({name:p().nullish(),arguments:p().nullish()})})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:Q1}),e]);C({echo:le().optional(),logitBias:fe(p(),O()).optional(),suffix:p().optional(),user:p().optional()});var WR=C({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()});C({id:p().nullish(),created:O().nullish(),model:p().nullish(),choices:A(C({text:p(),finish_reason:p()})),usage:WR.nullish()}),C({dimensions:O().optional(),user:p().optional()}),C({data:A(C({embedding:A(O())})),usage:C({prompt_tokens:O()}).nullish(),providerMetadata:fe(p(),fe(p(),Mt())).optional()}),C({data:A(C({b64_json:p()}))});var X1=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},GR={extractMetadata:async({parsedBody:e})=>{const t=await Hs({value:e,schema:KR});return!t.success||t.value.usage==null?void 0:X1(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await Hs({value:t,schema:YR});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>X1(e)}}},ey=C({prompt_cache_hit_tokens:O().nullish(),prompt_cache_miss_tokens:O().nullish()}),KR=C({usage:ey.nullish()}),YR=C({choices:A(C({finish_reason:p().nullish()})).nullish(),usage:ey.nullish()}),QR="1.0.30";function ty(e={}){var t;const n=N1((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>wd({Authorization:`Bearer ${b1({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${QR}`);class o extends BR{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const y=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:y}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${n}${l}`,headers:r,fetch:e.fetch,metadataExtractor:GR}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new Lu({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Lu({modelId:i,modelType:"imageModel"})},a}ty();const ny=async e=>{const t={};try{const n=await e.listTools();for(const{name:r,description:o,inputSchema:s}of n.tools){const a=async(i,l)=>e.callTool({name:r,arguments:i},{signal:l==null?void 0:l.abortSignal});t[r]=i2({description:o,inputSchema:As({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(n){throw n}},XR={openai:G1,deepseek:ty};class eO{constructor({llmConfig:t,mcpServers:n}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=n||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const r=t.providerType;let o;typeof r=="string"?o=XR[r]:o=r,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(t){try{let n;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new bs(new URL(t.url)):"type"in t&&t.type==="extension"?n=new G0(t.sessionId):n=t,t.useAISdkClient??!1){const o=await uI({transport:n});return o.__transport__=n,o}else{const o=new H0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(n),o.__transport__=n,o}}catch(n){return this.onError&&this.onError((n==null?void 0:n.message)||"Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _closeOneClient(t){var n,r,o;try{const s=t.__transport__;if(s&&s instanceof ks||s&&s instanceof Ss)return;await((n=s==null?void 0:s.terminateSession)==null?void 0:n.call(s)),await((r=s==null?void 0:s.close)==null?void 0:r.call(s)),await((o=t==null?void 0:t.close)==null?void 0:o.call(t))}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),n=await Promise.all(t.map(async([r,o])=>{const s=await this._createOneClient(o);return{serverName:r,client:s}}));this.mcpClients={},n.forEach(({serverName:r,client:o})=>{this.mcpClients[r]=o})}async _getClientTools(t,n){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await ny(t)}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||`Failed to query tools for ${n}`,r),console.error(`Failed to query tools for ${n}`,r),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),n=await Promise.all(t.map(async([r,o])=>{const s=await this._getClientTools(o,r);return{serverName:r,tools:s}}));this.mcpTools={},n.forEach(({serverName:r,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[r]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(n){this.onError&&this.onError((n==null?void 0:n.message)||"Failed to close client",n),console.error("Failed to close client",n)}}))}async initClientsAndTools(){var t;await this._createMpcClients(),await this._createMpcTools(),(t=this.onUpdatedTools)==null||t.call(this)}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,n){var s,a;if(this.mcpServers[t])return!1;const r=await this._createOneClient(n);if(!r)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=r;const o=await this._getClientTools(r,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=n,(a=this.onUpdatedTools)==null||a.call(this),r}async removeMcpServer(t){var o;if(!this.mcpServers[t])return;delete this.mcpServers[t];const n=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(n)}catch{}const r=this.mcpTools[t];delete this.mcpTools[t],r&&Object.keys(r).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==s)}),(o=this.onUpdatedTools)==null||o.call(this)}_tempMergeTools(t={}){const n=Object.values(this.mcpTools).reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(n),stopWhen:hd(r),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return(i=a==null?void 0:a.response)==null||i.then(l=>{this.messages.push(...l.messages)}),a}async chat(t){return this._chat(gE,t)}async chatStream(t){return this._chat(ME,t)}}xe.AgentModelProvider=eO,xe.Ajv=vb,xe.AuthClientProvider=C8,xe.ContentScriptServerTransport=G8,xe.ExtensionClientTransport=G0,xe.ExtensionPageServerTransport=W8,xe.InMemoryTransport=ks,xe.QrCode=gm,xe.ResourceTemplate=O8,xe.UriTemplate=Vn,xe.WebMcpClient=H0,xe.WebMcpServer=L8,xe.completable=k8,xe.createMessageChannelClientTransport=F8,xe.createMessageChannelPairTransport=D8,xe.createMessageChannelServerTransport=z8,xe.createRemoter=HC,xe.createSSEClientTransport=q8,xe.createStreamableHTTPClientTransport=V8,xe.getAISDKTools=ny,xe.getDisplayName=j8,xe.isMcpClient=J8,xe.isMcpServer=U8,xe.isMessageChannelClientTransport=H8,xe.isMessageChannelServerTransport=Z8,xe.isSSEClientTransport=B8,xe.isStreamableHTTPClientTransport=J0,xe.z=b3,Object.defineProperty(xe,Symbol.toStringTag,{value:"Module"})});