@zuplo/runtime 6.70.21 → 6.70.23

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.
@@ -22,1390 +22,38 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as we,H as sm,I as yc,J as Bv,K as cm,L as h,M as um,N as re,O as ce,P as dm,Q as lm,R as Re,S as C,T as I,U as Ae,V as fe,W as wc,X as Sc,Y as le,Z as it,_ as O,a as dr,aa as pm,b as am,ba as vc,ca as mm,da as hm,ea as c,fa as ae,j as fo,k as im,q as _c,z as Vt}from"../chunk-UMZORQLU.js";import{d as go}from"../chunk-2ZQVIVZ3.js";import{a as J}from"../chunk-ZS34EO4B.js";import{X as Za,Y as Ft,Z as om,a as o,c as A,e as nm}from"../chunk-YGYFQCBA.js";var xo=A(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var ko=class{static{o(this,"_CodeOrName")}};ne._CodeOrName=ko;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lr=class extends ko{static{o(this,"Name")}constructor(t){if(super(),!ne.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Lr;var pt=class extends ko{static{o(this,"_Code")}constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Lr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=pt;ne.nil=new pt("");function Om(e,...t){let r=[e[0]],n=0;for(;n<t.length;)tu(r,t[n]),r.push(e[++n]);return new pt(r)}o(Om,"_");ne._=Om;var eu=new pt("+");function Um(e,...t){let r=[Eo(e[0])],n=0;for(;n<t.length;)r.push(eu),tu(r,t[n]),r.push(eu,Eo(e[++n]));return fb(r),new pt(r)}o(Um,"str");ne.str=Um;function tu(e,t){t instanceof pt?e.push(...t._items):t instanceof Lr?e.push(t):e.push(yb(t))}o(tu,"addCodeArg");ne.addCodeArg=tu;function fb(e){let t=1;for(;t<e.length-1;){if(e[t]===eu){let r=gb(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(fb,"optimize");function gb(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Lr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Lr))return`"${e}${t.slice(1)}`}o(gb,"mergeExprItems");function _b(e,t){return t.emptyStr()?e:e.emptyStr()?t:Um`${e}${t}`}o(_b,"strConcat");ne.strConcat=_b;function yb(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Eo(Array.isArray(e)?e.join(","):e)}o(yb,"interpolate");function wb(e){return new pt(Eo(e))}o(wb,"stringify");ne.stringify=wb;function Eo(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(Eo,"safeStringify");ne.safeStringify=Eo;function Sb(e){return typeof e=="string"&&ne.IDENTIFIER.test(e)?new pt(`.${e}`):Om`[${e}]`}o(Sb,"getProperty");ne.getProperty=Sb;function vb(e){if(typeof e=="string"&&ne.IDENTIFIER.test(e))return new pt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(vb,"getEsmExportName");ne.getEsmExportName=vb;function Rb(e){return new pt(e.toString())}o(Rb,"regexpCode");ne.regexpCode=Rb});var ou=A(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Xe=xo(),ru=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},di;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(di||(Qe.UsedValueState=di={}));Qe.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var li=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Xe.Name?t:this.name(t)}name(t){return new Xe.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Qe.Scope=li;var pi=class extends Xe.Name{static{o(this,"ValueScopeName")}constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};Qe.ValueScopeName=pi;var bb=(0,Xe._)`\n`,nu=class extends li{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?bb:Xe.nil}}get(){return this._scope}name(t){return new pi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,s=(n=r.key)!==null&&n!==void 0?n:r.ref,u=this._values[i];if(u){let l=u.get(s);if(l)return l}else u=this._values[i]=new Map;u.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:i,itemIndex:p}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Xe.nil;for(let s in t){let u=t[s];if(!u)continue;let d=n[s]=n[s]||new Map;u.forEach(p=>{if(d.has(p))return;d.set(p,di.Started);let l=r(p);if(l){let m=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;i=(0,Xe._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Xe._)`${i}${l}${this.opts._n}`;else throw new ru(p);d.set(p,di.Completed)})}return i}};Qe.ValueScope=nu});var Z=A(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var X=xo(),vt=ou(),wr=xo();Object.defineProperty(W,"_",{enumerable:!0,get:o(function(){return wr._},"get")});Object.defineProperty(W,"str",{enumerable:!0,get:o(function(){return wr.str},"get")});Object.defineProperty(W,"strConcat",{enumerable:!0,get:o(function(){return wr.strConcat},"get")});Object.defineProperty(W,"nil",{enumerable:!0,get:o(function(){return wr.nil},"get")});Object.defineProperty(W,"getProperty",{enumerable:!0,get:o(function(){return wr.getProperty},"get")});Object.defineProperty(W,"stringify",{enumerable:!0,get:o(function(){return wr.stringify},"get")});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:o(function(){return wr.regexpCode},"get")});Object.defineProperty(W,"Name",{enumerable:!0,get:o(function(){return wr.Name},"get")});var gi=ou();Object.defineProperty(W,"Scope",{enumerable:!0,get:o(function(){return gi.Scope},"get")});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:o(function(){return gi.ValueScope},"get")});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:o(function(){return gi.ValueScopeName},"get")});Object.defineProperty(W,"varKinds",{enumerable:!0,get:o(function(){return gi.varKinds},"get")});W.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var Jt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},au=class extends Jt{static{o(this,"Def")}constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?vt.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,t,r)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},mi=class extends Jt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof X.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof X.Name?{}:{...this.lhs.names};return fi(t,this.rhs)}},iu=class extends mi{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},su=class extends Jt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},cu=class extends Jt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},uu=class extends Jt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},du=class extends Jt{static{o(this,"AnyCode")}constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=bn(this.code,t,r),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},Po=class extends Jt{static{o(this,"ParentNode")}constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(Cb(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Gr(t,r.names),{})}},Yt=class extends Po{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},lu=class extends Po{static{o(this,"Root")}},Rn=class extends Yt{static{o(this,"Else")}};Rn.kind="else";var jr=class e extends Yt{static{o(this,"If")}constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Rn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Nm(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=bn(this.condition,t,r),this}get names(){let t=super.names;return fi(t,this.condition),this.else&&Gr(t,this.else.names),t}};jr.kind="if";var Hr=class extends Yt{static{o(this,"For")}};Hr.kind="for";var pu=class extends Hr{static{o(this,"ForLoop")}constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=bn(this.iteration,t,r),this}get names(){return Gr(super.names,this.iteration.names)}},mu=class extends Hr{static{o(this,"ForRange")}constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?vt.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=fi(super.names,this.from);return fi(t,this.to)}},hi=class extends Hr{static{o(this,"ForIter")}constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=bn(this.iterable,t,r),this}get names(){return Gr(super.names,this.iterable.names)}},Oo=class extends Yt{static{o(this,"Func")}constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Oo.kind="func";var Uo=class extends Po{static{o(this,"Return")}render(t){return"return "+super.render(t)}};Uo.kind="return";var hu=class extends Yt{static{o(this,"Try")}render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Gr(t,this.catch.names),this.finally&&Gr(t,this.finally.names),t}},No=class extends Yt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};No.kind="catch";var zo=class extends Yt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};zo.kind="finally";var fu=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
26
- `:""},this._extScope=t,this._scope=new vt.Scope({parent:t}),this._nodes=[new lu]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new au(t,i,n)),i}const(t,r,n){return this._def(vt.varKinds.const,t,r,n)}let(t,r,n){return this._def(vt.varKinds.let,t,r,n)}var(t,r,n){return this._def(vt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new mi(t,r,n))}add(t,r){return this._leafNode(new iu(t,W.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==X.nil&&this._leafNode(new du(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,X.addCodeArg)(r,a));return r.push("}"),new X._Code(r)}if(t,r,n){if(this._blockNode(new jr(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new jr(t))}else(){return this._elseNode(new Rn)}endIf(){return this._endBlockNode(jr,Rn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new pu(t),r)}forRange(t,r,n,a,i=this.opts.es5?vt.varKinds.var:vt.varKinds.let){let s=this._scope.toName(t);return this._for(new mu(i,s,r,n),()=>a(s))}forOf(t,r,n,a=vt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof X.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,X._)`${s}.length`,u=>{this.var(i,(0,X._)`${s}[${u}]`),n(i)})}return this._for(new hi("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?vt.varKinds.var:vt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,X._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new hi("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Hr)}label(t){return this._leafNode(new su(t))}break(t){return this._leafNode(new cu(t))}return(t){let r=new Uo;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Uo)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new hu;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new No(i),r(i)}return n&&(this._currNode=a.finally=new zo,this.code(n)),this._endBlockNode(No,zo)}throw(t){return this._leafNode(new uu(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=X.nil,n,a){return this._blockNode(new Oo(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(Oo)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};W.CodeGen=fu;function Gr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Gr,"addNames");function fi(e,t){return t instanceof X._CodeOrName?Gr(e,t.names):e}o(fi,"addExprNames");function bn(e,t,r){if(e instanceof X.Name)return n(e);if(!a(e))return e;return new X._Code(e._items.reduce((i,s)=>(s instanceof X.Name&&(s=n(s)),s instanceof X._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof X._Code&&i._items.some(s=>s instanceof X.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(bn,"optimizeExpr");function Cb(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(Cb,"subtractNames");function Nm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,X._)`!${gu(e)}`}o(Nm,"not");W.not=Nm;var Ib=zm(W.operators.AND);function Tb(...e){return e.reduce(Ib)}o(Tb,"and");W.and=Tb;var Ab=zm(W.operators.OR);function kb(...e){return e.reduce(Ab)}o(kb,"or");W.or=kb;function zm(e){return(t,r)=>t===X.nil?r:r===X.nil?t:(0,X._)`${gu(t)} ${e} ${gu(r)}`}o(zm,"mappend");function gu(e){return e instanceof X.Name?e:(0,X._)`(${e})`}o(gu,"par")});var oe=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var ue=Z(),Eb=xo();function xb(e){let t={};for(let r of e)t[r]=!0;return t}o(xb,"toHash");Y.toHash=xb;function Pb(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Mm(e,t),!qm(t,e.self.RULES.all))}o(Pb,"alwaysValidSchema");Y.alwaysValidSchema=Pb;function Mm(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||Hm(e,`unknown keyword: "${i}"`)}o(Mm,"checkUnknownRules");Y.checkUnknownRules=Mm;function qm(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(qm,"schemaHasRules");Y.schemaHasRules=qm;function Ob(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(Ob,"schemaHasRulesButRef");Y.schemaHasRulesButRef=Ob;function Ub({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ue._)`${r}`}return(0,ue._)`${e}${t}${(0,ue.getProperty)(n)}`}o(Ub,"schemaRefOrVal");Y.schemaRefOrVal=Ub;function Nb(e){return Lm(decodeURIComponent(e))}o(Nb,"unescapeFragment");Y.unescapeFragment=Nb;function zb(e){return encodeURIComponent(yu(e))}o(zb,"escapeFragment");Y.escapeFragment=zb;function yu(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(yu,"escapeJsonPointer");Y.escapeJsonPointer=yu;function Lm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(Lm,"unescapeJsonPointer");Y.unescapeJsonPointer=Lm;function $b(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o($b,"eachItem");Y.eachItem=$b;function $m({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,u)=>{let d=s===void 0?i:s instanceof ue.Name?(i instanceof ue.Name?e(a,i,s):t(a,i,s),s):i instanceof ue.Name?(t(a,s,i),i):r(i,s);return u===ue.Name&&!(d instanceof ue.Name)?n(a,d):d}}o($m,"makeMergeEvaluated");Y.mergeEvaluated={props:$m({mergeNames:o((e,t,r)=>e.if((0,ue._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ue._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ue._)`${r} || {}`).code((0,ue._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ue._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ue._)`${r} || {}`),wu(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:jm}),items:$m({mergeNames:o((e,t,r)=>e.if((0,ue._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ue._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ue._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ue._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function jm(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ue._)`{}`);return t!==void 0&&wu(e,r,t),r}o(jm,"evaluatedPropsToName");Y.evaluatedPropsToName=jm;function wu(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ue._)`${t}${(0,ue.getProperty)(n)}`,!0))}o(wu,"setEvaluated");Y.setEvaluated=wu;var Dm={};function Db(e,t){return e.scopeValue("func",{ref:t,code:Dm[t.code]||(Dm[t.code]=new Eb._Code(t.code))})}o(Db,"useFunc");Y.useFunc=Db;var _u;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(_u||(Y.Type=_u={}));function Mb(e,t,r){if(e instanceof ue.Name){let n=t===_u.Num;return r?n?(0,ue._)`"[" + ${e} + "]"`:(0,ue._)`"['" + ${e} + "']"`:n?(0,ue._)`"/" + ${e}`:(0,ue._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ue.getProperty)(e).toString():"/"+yu(e)}o(Mb,"getErrorPath");Y.getErrorPath=Mb;function Hm(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}o(Hm,"checkStrictMode");Y.checkStrictMode=Hm});var Xt=A(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var He=Z(),qb={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};Su.default=qb});var $o=A(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.extendErrors=Ge.resetErrorsCount=Ge.reportExtraError=Ge.reportError=Ge.keyword$DataError=Ge.keywordError=void 0;var te=Z(),_i=oe(),Ze=Xt();Ge.keywordError={message:o(({keyword:e})=>(0,te.str)`must pass "${e}" keyword validation`,"message")};Ge.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,te.str)`"${e}" keyword must be ${t} ($data)`:(0,te.str)`"${e}" keyword is invalid ($data)`,"message")};function Lb(e,t=Ge.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:u}=a,d=Fm(e,t,r);n??(s||u)?Gm(i,d):Bm(a,(0,te._)`[${d}]`)}o(Lb,"reportError");Ge.reportError=Lb;function jb(e,t=Ge.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,u=Fm(e,t,r);Gm(a,u),i||s||Bm(n,Ze.default.vErrors)}o(jb,"reportExtraError");Ge.reportExtraError=jb;function Hb(e,t){e.assign(Ze.default.errors,t),e.if((0,te._)`${Ze.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,te._)`${Ze.default.vErrors}.length`,t),()=>e.assign(Ze.default.vErrors,null)))}o(Hb,"resetErrorsCount");Ge.resetErrorsCount=Hb;function Gb({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ze.default.errors,u=>{e.const(s,(0,te._)`${Ze.default.vErrors}[${u}]`),e.if((0,te._)`${s}.instancePath === undefined`,()=>e.assign((0,te._)`${s}.instancePath`,(0,te.strConcat)(Ze.default.instancePath,i.errorPath))),e.assign((0,te._)`${s}.schemaPath`,(0,te.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,te._)`${s}.schema`,r),e.assign((0,te._)`${s}.data`,n))})}o(Gb,"extendErrors");Ge.extendErrors=Gb;function Gm(e,t){let r=e.const("err",t);e.if((0,te._)`${Ze.default.vErrors} === null`,()=>e.assign(Ze.default.vErrors,(0,te._)`[${r}]`),(0,te._)`${Ze.default.vErrors}.push(${r})`),e.code((0,te._)`${Ze.default.errors}++`)}o(Gm,"addError");function Bm(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,te._)`new ${e.ValidationError}(${t})`):(r.assign((0,te._)`${n}.errors`,t),r.return(!1))}o(Bm,"returnErrors");var Br={keyword:new te.Name("keyword"),schemaPath:new te.Name("schemaPath"),params:new te.Name("params"),propertyName:new te.Name("propertyName"),message:new te.Name("message"),schema:new te.Name("schema"),parentSchema:new te.Name("parentSchema")};function Fm(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,te._)`{}`:Bb(e,t,r)}o(Fm,"errorObjectCode");function Bb(e,t,r={}){let{gen:n,it:a}=e,i=[Fb(a,r),Vb(e,r)];return Kb(e,t,i),n.object(...i)}o(Bb,"errorObject");function Fb({errorPath:e},{instancePath:t}){let r=t?(0,te.str)`${e}${(0,_i.getErrorPath)(t,_i.Type.Str)}`:e;return[Ze.default.instancePath,(0,te.strConcat)(Ze.default.instancePath,r)]}o(Fb,"errorInstancePath");function Vb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,te.str)`${t}/${e}`;return r&&(a=(0,te.str)`${a}${(0,_i.getErrorPath)(r,_i.Type.Str)}`),[Br.schemaPath,a]}o(Vb,"errorSchemaPath");function Kb(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:s,it:u}=e,{opts:d,propertyName:p,topSchemaRef:l,schemaPath:m}=u;n.push([Br.keyword,a],[Br.params,typeof t=="function"?t(e):t||(0,te._)`{}`]),d.messages&&n.push([Br.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([Br.schema,s],[Br.parentSchema,(0,te._)`${l}${m}`],[Ze.default.data,i]),p&&n.push([Br.propertyName,p])}o(Kb,"extraErrorProps")});var Km=A(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.boolOrEmptySchema=Cn.topBoolOrEmptySchema=void 0;var Zb=$o(),Wb=Z(),Jb=Xt(),Yb={message:"boolean schema is false"};function Xb(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Vm(e,!1):typeof r=="object"&&r.$async===!0?t.return(Jb.default.data):(t.assign((0,Wb._)`${n}.errors`,null),t.return(!0))}o(Xb,"topBoolOrEmptySchema");Cn.topBoolOrEmptySchema=Xb;function Qb(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Vm(e)):r.var(t,!0)}o(Qb,"boolOrEmptySchema");Cn.boolOrEmptySchema=Qb;function Vm(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Zb.reportError)(a,Yb,void 0,t)}o(Vm,"falseSchemaError")});var vu=A(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.getRules=In.isJSONType=void 0;var eC=["string","number","integer","boolean","null","object","array"],tC=new Set(eC);function rC(e){return typeof e=="string"&&tC.has(e)}o(rC,"isJSONType");In.isJSONType=rC;function nC(){let 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:{}}}o(nC,"getRules");In.getRules=nC});var Ru=A(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.shouldUseRule=Sr.shouldUseGroup=Sr.schemaHasRulesForType=void 0;function oC({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Zm(e,n)}o(oC,"schemaHasRulesForType");Sr.schemaHasRulesForType=oC;function Zm(e,t){return t.rules.some(r=>Wm(e,r))}o(Zm,"shouldUseGroup");Sr.shouldUseGroup=Zm;function Wm(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}o(Wm,"shouldUseRule");Sr.shouldUseRule=Wm});var Do=A(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var aC=vu(),iC=Ru(),sC=$o(),K=Z(),Jm=oe(),Tn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Tn||(Be.DataType=Tn={}));function cC(e){let t=Ym(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}o(cC,"getSchemaTypes");Be.getSchemaTypes=cC;function Ym(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(aC.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Ym,"getJSONTypes");Be.getJSONTypes=Ym;function uC(e,t){let{gen:r,data:n,opts:a}=e,i=dC(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,iC.schemaHasRulesForType)(e,t[0]));if(s){let u=Cu(t,n,a.strictNumbers,Tn.Wrong);r.if(u,()=>{i.length?lC(e,t,i):Iu(e)})}return s}o(uC,"coerceAndCheckDataType");Be.coerceAndCheckDataType=uC;var Xm=new Set(["string","number","integer","boolean","null"]);function dC(e,t){return t?e.filter(r=>Xm.has(r)||t==="array"&&r==="array"):[]}o(dC,"coerceToTypes");function lC(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,K._)`typeof ${a}`),u=n.let("coerced",(0,K._)`undefined`);i.coerceTypes==="array"&&n.if((0,K._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,K._)`${a}[0]`).assign(s,(0,K._)`typeof ${a}`).if(Cu(t,a,i.strictNumbers),()=>n.assign(u,a))),n.if((0,K._)`${u} !== undefined`);for(let p of r)(Xm.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),Iu(e),n.endIf(),n.if((0,K._)`${u} !== undefined`,()=>{n.assign(a,u),pC(e,u)});function d(p){switch(p){case"string":n.elseIf((0,K._)`${s} == "number" || ${s} == "boolean"`).assign(u,(0,K._)`"" + ${a}`).elseIf((0,K._)`${a} === null`).assign(u,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${s} == "boolean" || ${a} === null
27
- || (${s} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,K._)`+${a}`);return;case"integer":n.elseIf((0,K._)`${s} === "boolean" || ${a} === null
28
- || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(u,(0,K._)`+${a}`);return;case"boolean":n.elseIf((0,K._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(u,!1).elseIf((0,K._)`${a} === "true" || ${a} === 1`).assign(u,!0);return;case"null":n.elseIf((0,K._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(u,null);return;case"array":n.elseIf((0,K._)`${s} === "string" || ${s} === "number"
29
- || ${s} === "boolean" || ${a} === null`).assign(u,(0,K._)`[${a}]`)}}o(d,"coerceSpecificType")}o(lC,"coerceData");function pC({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,K._)`${t} !== undefined`,()=>e.assign((0,K._)`${t}[${r}]`,n))}o(pC,"assignParentData");function bu(e,t,r,n=Tn.Correct){let a=n===Tn.Correct?K.operators.EQ:K.operators.NEQ,i;switch(e){case"null":return(0,K._)`${t} ${a} null`;case"array":i=(0,K._)`Array.isArray(${t})`;break;case"object":i=(0,K._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,K._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,K._)`typeof ${t} ${a} ${e}`}return n===Tn.Correct?i:(0,K.not)(i);function s(u=K.nil){return(0,K.and)((0,K._)`typeof ${t} == "number"`,u,r?(0,K._)`isFinite(${t})`:K.nil)}}o(bu,"checkDataType");Be.checkDataType=bu;function Cu(e,t,r,n){if(e.length===1)return bu(e[0],t,r,n);let a,i=(0,Jm.toHash)(e);if(i.array&&i.object){let s=(0,K._)`typeof ${t} != "object"`;a=i.null?s:(0,K._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=K.nil;i.number&&delete i.integer;for(let s in i)a=(0,K.and)(a,bu(s,t,r,n));return a}o(Cu,"checkDataTypes");Be.checkDataTypes=Cu;var mC={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,K._)`{type: ${e}}`:(0,K._)`{type: ${t}}`,"params")};function Iu(e){let t=hC(e);(0,sC.reportError)(t,mC)}o(Iu,"reportTypeError");Be.reportTypeError=Iu;function hC(e){let{gen:t,data:r,schema:n}=e,a=(0,Jm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(hC,"getTypeErrorContext")});var eh=A(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.assignDefaults=void 0;var An=Z(),fC=oe();function gC(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Qm(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>Qm(e,i,a.default))}o(gC,"assignDefaults");yi.assignDefaults=gC;function Qm(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let u=(0,An._)`${i}${(0,An.getProperty)(t)}`;if(a){(0,fC.checkStrictMode)(e,`default is ignored for: ${u}`);return}let d=(0,An._)`${u} === undefined`;s.useDefaults==="empty"&&(d=(0,An._)`${d} || ${u} === null || ${u} === ""`),n.if(d,(0,An._)`${u} = ${(0,An.stringify)(r)}`)}o(Qm,"assignDefault")});var mt=A(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.validateUnion=se.validateArray=se.usePattern=se.callValidateCode=se.schemaProperties=se.allSchemaProperties=se.noPropertyInData=se.propertyInData=se.isOwnProperty=se.hasPropFunc=se.reportMissingProp=se.checkMissingProp=se.checkReportMissingProp=void 0;var pe=Z(),Tu=oe(),vr=Xt(),_C=oe();function yC(e,t){let{gen:r,data:n,it:a}=e;r.if(ku(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}o(yC,"checkReportMissingProp");se.checkReportMissingProp=yC;function wC({gen:e,data:t,it:{opts:r}},n,a){return(0,pe.or)(...n.map(i=>(0,pe.and)(ku(e,t,i,r.ownProperties),(0,pe._)`${a} = ${i}`)))}o(wC,"checkMissingProp");se.checkMissingProp=wC;function SC(e,t){e.setParams({missingProperty:t},!0),e.error()}o(SC,"reportMissingProp");se.reportMissingProp=SC;function th(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}o(th,"hasPropFunc");se.hasPropFunc=th;function Au(e,t,r){return(0,pe._)`${th(e)}.call(${t}, ${r})`}o(Au,"isOwnProperty");se.isOwnProperty=Au;function vC(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${a} && ${Au(e,t,r)}`:a}o(vC,"propertyInData");se.propertyInData=vC;function ku(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(a,(0,pe.not)(Au(e,t,r))):a}o(ku,"noPropertyInData");se.noPropertyInData=ku;function rh(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(rh,"allSchemaProperties");se.allSchemaProperties=rh;function RC(e,t){return rh(t).filter(r=>!(0,Tu.alwaysValidSchema)(e,t[r]))}o(RC,"schemaProperties");se.schemaProperties=RC;function bC({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},u,d,p){let l=p?(0,pe._)`${e}, ${t}, ${n}${a}`:t,m=[[vr.default.instancePath,(0,pe.strConcat)(vr.default.instancePath,i)],[vr.default.parentData,s.parentData],[vr.default.parentDataProperty,s.parentDataProperty],[vr.default.rootData,vr.default.rootData]];s.opts.dynamicRef&&m.push([vr.default.dynamicAnchors,vr.default.dynamicAnchors]);let f=(0,pe._)`${l}, ${r.object(...m)}`;return d!==pe.nil?(0,pe._)`${u}.call(${d}, ${f})`:(0,pe._)`${u}(${f})`}o(bC,"callValidateCode");se.callValidateCode=bC;var CC=(0,pe._)`new RegExp`;function IC({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,pe._)`${a.code==="new RegExp"?CC:(0,_C.useFunc)(e,a)}(${r}, ${n})`})}o(IC,"usePattern");se.usePattern=IC;function TC(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let u=t.let("valid",!0);return s(()=>t.assign(u,!1)),u}return t.var(i,!0),s(()=>t.break()),i;function s(u){let d=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:Tu.Type.Num},i),t.if((0,pe.not)(i),u)})}o(s,"validateItems")}o(TC,"validateArray");se.validateArray=TC;function AC(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,Tu.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),u=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},u);t.assign(s,(0,pe._)`${s} || ${u}`),e.mergeValidEvaluated(l,u)||t.if((0,pe.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(AC,"validateUnion");se.validateUnion=AC});var ah=A(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;var We=Z(),Fr=Xt(),kC=mt(),EC=$o();function xC(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,u=t.macro.call(s.self,a,i,s),d=oh(r,n,u);s.opts.validateSchema!==!1&&s.self.validateSchema(u,!0);let p=r.name("valid");e.subschema({schema:u,schemaPath:We.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(xC,"macroKeywordCode");Pt.macroKeywordCode=xC;function PC(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:u,it:d}=e;UC(d,t);let p=!u&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=oh(n,a,p),m=n.let("valid");e.block$data(m,f),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function f(){if(t.errors===!1)y(),t.modifying&&nh(e),S(()=>e.error());else{let v=t.async?_():w();t.modifying&&nh(e),S(()=>OC(e,v))}}o(f,"validateKeyword");function _(){let v=n.let("ruleErrs",null);return n.try(()=>y((0,We._)`await `),R=>n.assign(m,!1).if((0,We._)`${R} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,We._)`${R}.errors`),()=>n.throw(R))),v}o(_,"validateAsync");function w(){let v=(0,We._)`${l}.errors`;return n.assign(v,null),y(We.nil),v}o(w,"validateSync");function y(v=t.async?(0,We._)`await `:We.nil){let R=d.opts.passContext?Fr.default.this:Fr.default.self,b=!("compile"in t&&!u||t.schema===!1);n.assign(m,(0,We._)`${v}${(0,kC.callValidateCode)(e,l,R,b)}`,t.modifying)}o(y,"assignValid");function S(v){var R;n.if((0,We.not)((R=t.valid)!==null&&R!==void 0?R:m),v)}o(S,"reportErrs")}o(PC,"funcKeywordCode");Pt.funcKeywordCode=PC;function nh(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}o(nh,"modifyData");function OC(e,t){let{gen:r}=e;r.if((0,We._)`Array.isArray(${t})`,()=>{r.assign(Fr.default.vErrors,(0,We._)`${Fr.default.vErrors} === null ? ${t} : ${Fr.default.vErrors}.concat(${t})`).assign(Fr.default.errors,(0,We._)`${Fr.default.vErrors}.length`),(0,EC.extendErrors)(e)},()=>e.error())}o(OC,"addErrs");function UC({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(UC,"checkAsyncKeyword");function oh(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}o(oh,"useKeyword");function NC(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}o(NC,"validSchemaType");Pt.validSchemaType=NC;function zC({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let s=a.dependencies;if(s?.some(u=>!Object.prototype.hasOwnProperty.call(e,u)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let d=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}o(zC,"validateKeywordUsage");Pt.validateKeywordUsage=zC});var sh=A(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.extendSubschemaMode=Rr.extendSubschemaData=Rr.getSubschema=void 0;var Ot=Z(),ih=oe();function $C(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let u=e.schema[t];return r===void 0?{schema:u,schemaPath:(0,Ot._)`${e.schemaPath}${(0,Ot.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:u[r],schemaPath:(0,Ot._)`${e.schemaPath}${(0,Ot.getProperty)(t)}${(0,Ot.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ih.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}o($C,"getSubschema");Rr.getSubschema=$C;function DC(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:s}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:u}=t;if(r!==void 0){let{errorPath:p,dataPathArr:l,opts:m}=t,f=u.let("data",(0,Ot._)`${t.data}${(0,Ot.getProperty)(r)}`,!0);d(f),e.errorPath=(0,Ot.str)`${p}${(0,ih.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Ot._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Ot.Name?a:u.let("data",a,!0);d(p),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(p){e.data=p,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,p]}o(d,"dataContextProps")}o(DC,"extendSubschemaData");Rr.extendSubschemaData=DC;function MC(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}o(MC,"extendSubschemaMode");Rr.extendSubschemaMode=MC});var Eu=A((GH,ch)=>{"use strict";ch.exports=o(function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var s=i[a];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r},"equal")});var dh=A((FH,uh)=>{"use strict";var br=uh.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};wi(t,n,a,e,"",e)};br.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};br.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};br.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};br.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 wi(e,t,r,n,a,i,s,u,d,p){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,s,u,d,p);for(var l in n){var m=n[l];if(Array.isArray(m)){if(l in br.arrayKeywords)for(var f=0;f<m.length;f++)wi(e,t,r,m[f],a+"/"+l+"/"+f,i,a,l,n,f)}else if(l in br.propsKeywords){if(m&&typeof m=="object")for(var _ in m)wi(e,t,r,m[_],a+"/"+l+"/"+qC(_),i,a,l,n,_)}else(l in br.keywords||e.allKeys&&!(l in br.skipKeywords))&&wi(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,u,d,p)}}o(wi,"_traverse");function qC(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(qC,"escapeJsonPtr")});var Mo=A(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var LC=oe(),jC=Eu(),HC=dh(),GC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function BC(e,t=!0){return typeof e=="boolean"?!0:t===!0?!xu(e):t?lh(e)<=t:!1}o(BC,"inlineRef");et.inlineRef=BC;var FC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function xu(e){for(let t in e){if(FC.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(xu)||typeof r=="object"&&xu(r))return!0}return!1}o(xu,"hasRef");function lh(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!GC.has(r)&&(typeof e[r]=="object"&&(0,LC.eachItem)(e[r],n=>t+=lh(n)),t===1/0))return 1/0}return t}o(lh,"countKeys");function ph(e,t="",r){r!==!1&&(t=kn(t));let n=e.parse(t);return mh(e,n)}o(ph,"getFullPath");et.getFullPath=ph;function mh(e,t){return e.serialize(t).split("#")[0]+"#"}o(mh,"_getFullPath");et._getFullPath=mh;var VC=/#\/?$/;function kn(e){return e?e.replace(VC,""):""}o(kn,"normalizeId");et.normalizeId=kn;function KC(e,t,r){return r=kn(r),e.resolve(t,r)}o(KC,"resolveUrl");et.resolveUrl=KC;var ZC=/^[a-z_][-a-z0-9._]*$/i;function WC(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=kn(e[r]||t),i={"":a},s=ph(n,a,!1),u={},d=new Set;return HC(e,{allKeys:!0},(m,f,_,w)=>{if(w===void 0)return;let y=s+f,S=i[w];typeof m[r]=="string"&&(S=v.call(this,m[r])),R.call(this,m.$anchor),R.call(this,m.$dynamicAnchor),i[f]=S;function v(b){let q=this.opts.uriResolver.resolve;if(b=kn(S?q(S,b):b),d.has(b))throw l(b);d.add(b);let L=this.refs[b];return typeof L=="string"&&(L=this.refs[L]),typeof L=="object"?p(m,L.schema,b):b!==kn(y)&&(b[0]==="#"?(p(m,u[b],b),u[b]=m):this.refs[b]=y),b}o(v,"addRef");function R(b){if(typeof b=="string"){if(!ZC.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}o(R,"addAnchor")}),u;function p(m,f,_){if(f!==void 0&&!jC(m,f))throw l(_)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(WC,"getSchemaRefs");et.getSchemaRefs=WC});var jo=A(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getData=Cr.KeywordCxt=Cr.validateFunctionCode=void 0;var yh=Km(),hh=Do(),Ou=Ru(),Si=Do(),JC=eh(),Lo=ah(),Pu=sh(),U=Z(),B=Xt(),YC=Mo(),Qt=oe(),qo=$o();function XC(e){if(vh(e)&&(Rh(e),Sh(e))){tI(e);return}wh(e,()=>(0,yh.topBoolOrEmptySchema)(e))}o(XC,"validateFunctionCode");Cr.validateFunctionCode=XC;function wh({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,U._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{e.code((0,U._)`"use strict"; ${fh(r,a)}`),eI(e,a),e.code(i)}):e.func(t,(0,U._)`${B.default.data}, ${QC(a)}`,n.$async,()=>e.code(fh(r,a)).code(i))}o(wh,"validateFunction");function QC(e){return(0,U._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${e.dynamicRef?(0,U._)`, ${B.default.dynamicAnchors}={}`:U.nil}}={}`}o(QC,"destructureValCxt");function eI(e,t){e.if(B.default.valCxt,()=>{e.var(B.default.instancePath,(0,U._)`${B.default.valCxt}.${B.default.instancePath}`),e.var(B.default.parentData,(0,U._)`${B.default.valCxt}.${B.default.parentData}`),e.var(B.default.parentDataProperty,(0,U._)`${B.default.valCxt}.${B.default.parentDataProperty}`),e.var(B.default.rootData,(0,U._)`${B.default.valCxt}.${B.default.rootData}`),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,U._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{e.var(B.default.instancePath,(0,U._)`""`),e.var(B.default.parentData,(0,U._)`undefined`),e.var(B.default.parentDataProperty,(0,U._)`undefined`),e.var(B.default.rootData,B.default.data),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,U._)`{}`)})}o(eI,"destructureValCxtES5");function tI(e){let{schema:t,opts:r,gen:n}=e;wh(e,()=>{r.$comment&&t.$comment&&Ch(e),iI(e),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&rI(e),bh(e),uI(e)})}o(tI,"topSchemaObjCode");function rI(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,U._)`${r}.evaluated`),t.if((0,U._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,U._)`${e.evaluated}.props`,(0,U._)`undefined`)),t.if((0,U._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,U._)`${e.evaluated}.items`,(0,U._)`undefined`))}o(rI,"resetEvaluated");function fh(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}o(fh,"funcSourceUrl");function nI(e,t){if(vh(e)&&(Rh(e),Sh(e))){oI(e,t);return}(0,yh.boolOrEmptySchema)(e,t)}o(nI,"subschemaCode");function Sh({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}o(Sh,"schemaCxtHasRules");function vh(e){return typeof e.schema!="boolean"}o(vh,"isSchemaObj");function oI(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&Ch(e),sI(e),cI(e);let i=n.const("_errs",B.default.errors);bh(e,i),n.var(t,(0,U._)`${i} === ${B.default.errors}`)}o(oI,"subSchemaObjCode");function Rh(e){(0,Qt.checkUnknownRules)(e),aI(e)}o(Rh,"checkKeywords");function bh(e,t){if(e.opts.jtd)return gh(e,[],!1,t);let r=(0,hh.getSchemaTypes)(e.schema),n=(0,hh.coerceAndCheckDataType)(e,r);gh(e,r,!n,t)}o(bh,"typeAndKeywords");function aI(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Qt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(aI,"checkRefsAndKeywords");function iI(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Qt.checkStrictMode)(e,"default is ignored in the schema root")}o(iI,"checkNoDefault");function sI(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,YC.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(sI,"updateContext");function cI(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(cI,"checkAsyncSchema");function Ch({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,U._)`${B.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,U.str)`${n}/$comment`,u=e.scopeValue("root",{ref:t.root});e.code((0,U._)`${B.default.self}.opts.$comment(${i}, ${s}, ${u}.schema)`)}}o(Ch,"commentKeyword");function uI(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,U._)`${B.default.errors} === 0`,()=>t.return(B.default.data),()=>t.throw((0,U._)`new ${a}(${B.default.vErrors})`)):(t.assign((0,U._)`${n}.errors`,B.default.vErrors),i.unevaluated&&dI(e),t.return((0,U._)`${B.default.errors} === 0`))}o(uI,"returnResults");function dI({gen:e,evaluated:t,props:r,items:n}){r instanceof U.Name&&e.assign((0,U._)`${t}.props`,r),n instanceof U.Name&&e.assign((0,U._)`${t}.items`,n)}o(dI,"assignEvaluated");function gh(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:u,opts:d,self:p}=e,{RULES:l}=p;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Qt.schemaHasRulesButRef)(i,l))){a.block(()=>Th(e,"$ref",l.all.$ref.definition));return}d.jtd||lI(e,t),a.block(()=>{for(let f of l.rules)m(f);m(l.post)});function m(f){(0,Ou.shouldUseGroup)(i,f)&&(f.type?(a.if((0,Si.checkDataType)(f.type,s,d.strictNumbers)),_h(e,f),t.length===1&&t[0]===f.type&&r&&(a.else(),(0,Si.reportTypeError)(e)),a.endIf()):_h(e,f),u||a.if((0,U._)`${B.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(gh,"schemaKeywords");function _h(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,JC.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ou.shouldUseRule)(n,i)&&Th(e,i.keyword,i.definition,t.type)})}o(_h,"iterateKeywords");function lI(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(pI(e,t),e.opts.allowUnionTypes||mI(e,t),hI(e,e.dataTypes))}o(lI,"checkStrictTypes");function pI(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Ih(e.dataTypes,r)||Uu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),gI(e,t)}}o(pI,"checkContextTypes");function mI(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Uu(e,"use allowUnionTypes to allow union type keyword")}o(mI,"checkMultipleTypes");function hI(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Ou.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>fI(t,s))&&Uu(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(hI,"checkKeywordTypes");function fI(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(fI,"hasApplicableType");function Ih(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(Ih,"includesType");function gI(e,t){let r=[];for(let n of e.dataTypes)Ih(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(gI,"narrowSchemaTypes");function Uu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Qt.checkStrictMode)(e,t,e.opts.strictTypes)}o(Uu,"strictTypesError");var vi=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,Lo.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Qt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Ah(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Lo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",B.default.errors))}result(t,r,n){this.failResult((0,U.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,U.not)(t),void 0,r)}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);let{schemaCode:r}=this;this.fail((0,U._)`${r} !== undefined && (${(0,U.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?qo.reportExtraError:qo.reportError)(this,this.def.error,r)}$dataError(){(0,qo.reportError)(this,this.def.$dataError||qo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,qo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=U.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,U.or)((0,U._)`${a} === undefined`,r)),t!==U.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==U.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,U.or)(s(),u());function s(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,U._)`${(0,Si.checkDataTypes)(d,r,i.opts.strictNumbers,Si.DataType.Wrong)}`}return U.nil}function u(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,U._)`!${d}(${r})`}return U.nil}}subschema(t,r){let n=(0,Pu.getSubschema)(this.it,t);(0,Pu.extendSubschemaData)(n,this.it,t),(0,Pu.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return nI(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Qt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Qt.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,U.Name)),!0}};Cr.KeywordCxt=vi;function Th(e,t,r,n){let a=new vi(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,Lo.funcKeywordCode)(a,r):"macro"in r?(0,Lo.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,Lo.funcKeywordCode)(a,r)}o(Th,"keywordCode");var _I=/^\/(?:[^~]|~0|~1)*$/,yI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ah(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return B.default.rootData;if(e[0]==="/"){if(!_I.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=B.default.rootData}else{let p=yI.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,u=a.split("/");for(let p of u)p&&(i=(0,U._)`${i}${(0,U.getProperty)((0,Qt.unescapeJsonPointer)(p))}`,s=(0,U._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(Ah,"getData");Cr.getData=Ah});var Ri=A(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var Nu=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};zu.default=Nu});var Ho=A(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var $u=Mo(),Du=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,$u.resolveUrl)(t,r,n),this.missingSchema=(0,$u.normalizeId)((0,$u.getFullPath)(t,this.missingRef))}};Mu.default=Du});var Ci=A(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.resolveSchema=ht.getCompilingSchema=ht.resolveRef=ht.compileSchema=ht.SchemaEnv=void 0;var Rt=Z(),wI=Ri(),Vr=Xt(),bt=Mo(),kh=oe(),SI=jo(),En=class{static{o(this,"SchemaEnv")}constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,bt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};ht.SchemaEnv=En;function Lu(e){let t=Eh.call(this,e);if(t)return t;let r=(0,bt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new Rt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),u;e.$async&&(u=s.scopeValue("Error",{ref:wI.default,code:(0,Rt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:Vr.default.data,parentData:Vr.default.parentData,parentDataProperty:Vr.default.parentDataProperty,dataNames:[Vr.default.data],dataPathArr:[Rt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Rt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:u,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Rt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,SI.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(Vr.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let _=new Function(`${Vr.default.self}`,`${Vr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:_}),_.errors=null,_.schema=e.schema,_.schemaEnv=e,e.$async&&(_.$async=!0),this.opts.code.source===!0&&(_.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:w,items:y}=p;_.evaluated={props:w instanceof Rt.Name?void 0:w,items:y instanceof Rt.Name?void 0:y,dynamicProps:w instanceof Rt.Name,dynamicItems:y instanceof Rt.Name},_.source&&(_.source.evaluated=(0,Rt.stringify)(_.evaluated))}return e.validate=_,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Lu,"compileSchema");ht.compileSchema=Lu;function vI(e,t,r){var n;r=(0,bt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=CI.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:u}=this.opts;s&&(i=new En({schema:s,schemaId:u,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=RI.call(this,i)}o(vI,"resolveRef");ht.resolveRef=vI;function RI(e){return(0,bt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Lu.call(this,e)}o(RI,"inlineOrCompile");function Eh(e){for(let t of this._compilations)if(bI(t,e))return t}o(Eh,"getCompilingSchema");ht.getCompilingSchema=Eh;function bI(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(bI,"sameSchemaEnv");function CI(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||bi.call(this,e,t)}o(CI,"resolve");function bi(e,t){let r=this.opts.uriResolver.parse(t),n=(0,bt._getFullPath)(this.opts.uriResolver,r),a=(0,bt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return qu.call(this,r,e);let i=(0,bt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let u=bi.call(this,e,s);return typeof u?.schema!="object"?void 0:qu.call(this,r,u)}if(typeof s?.schema=="object"){if(s.validate||Lu.call(this,s),i===(0,bt.normalizeId)(t)){let{schema:u}=s,{schemaId:d}=this.opts,p=u[d];return p&&(a=(0,bt.resolveUrl)(this.opts.uriResolver,a,p)),new En({schema:u,schemaId:d,root:e,baseId:a})}return qu.call(this,r,s)}}o(bi,"resolveSchema");ht.resolveSchema=bi;var II=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qu(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let u of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,kh.unescapeFragment)(u)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!II.has(u)&&p&&(t=(0,bt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,kh.schemaHasRulesButRef)(r,this.RULES)){let u=(0,bt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=bi.call(this,n,u)}let{schemaId:s}=this.opts;if(i=i||new En({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(qu,"getJsonPointer")});var xh=A((nG,TI)=>{TI.exports={$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 Hu=A((oG,Nh)=>{"use strict";var AI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Oh=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 ju(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(ju,"stringArrayToHexStripped");var kI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ph(e){return e.length=0,!0}o(Ph,"consumeIsZone");function EI(e,t,r){if(e.length){let n=ju(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(EI,"consumeHextets");function xI(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,u=EI;for(let d=0;d<e.length;d++){let p=e[d];if(!(p==="["||p==="]"))if(p===":"){if(i===!0&&(s=!0),!u(a,n,r))break;if(++t>7){r.error=!0;break}d>0&&e[d-1]===":"&&(i=!0),n.push(":");continue}else if(p==="%"){if(!u(a,n,r))break;u=Ph}else{a.push(p);continue}}return a.length&&(u===Ph?r.zone=a.join(""):s?n.push(a.join("")):n.push(ju(a))),r.address=n.join(""),r}o(xI,"getIPV6");function Uh(e){if(PI(e,":")<2)return{host:e,isIPV6:!1};let t=xI(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}o(Uh,"normalizeIPv6");function PI(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(PI,"findToken");function OI(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}o(OI,"removeDotSegments");function UI(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}o(UI,"normalizeComponentEncoding");function NI(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Oh(r)){let n=Uh(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}o(NI,"recomposeAuthority");Nh.exports={nonSimpleDomain:kI,recomposeAuthority:NI,normalizeComponentEncoding:UI,removeDotSegments:OI,isIPv4:Oh,isUUID:AI,normalizeIPv6:Uh,stringArrayToHexStripped:ju}});var qh=A((iG,Mh)=>{"use strict";var{isUUID:zI}=Hu(),$I=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,DI=["http","https","ws","wss","urn","urn:uuid"];function MI(e){return DI.indexOf(e)!==-1}o(MI,"isValidSchemeName");function Gu(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}o(Gu,"wsIsSecure");function zh(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(zh,"httpParse");function $h(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}o($h,"httpSerialize");function qI(e){return e.secure=Gu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(qI,"wsParse");function LI(e){if((e.port===(Gu(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){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(LI,"wsSerialize");function jI(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match($I);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=Bu(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(jI,"urnParse");function HI(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=Bu(a);i&&(e=i.serialize(e,t));let s=e,u=e.nss;return s.path=`${n||t.nid}:${u}`,t.skipEscape=!0,s}o(HI,"urnSerialize");function GI(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!zI(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(GI,"urnuuidParse");function BI(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(BI,"urnuuidSerialize");var Dh={scheme:"http",domainHost:!0,parse:zh,serialize:$h},FI={scheme:"https",domainHost:Dh.domainHost,parse:zh,serialize:$h},Ii={scheme:"ws",domainHost:!0,parse:qI,serialize:LI},VI={scheme:"wss",domainHost:Ii.domainHost,parse:Ii.parse,serialize:Ii.serialize},KI={scheme:"urn",parse:jI,serialize:HI,skipNormalize:!0},ZI={scheme:"urn:uuid",parse:GI,serialize:BI,skipNormalize:!0},Ti={http:Dh,https:FI,ws:Ii,wss:VI,urn:KI,"urn:uuid":ZI};Object.setPrototypeOf(Ti,null);function Bu(e){return e&&(Ti[e]||Ti[e.toLowerCase()])||void 0}o(Bu,"getSchemeHandler");Mh.exports={wsIsSecure:Gu,SCHEMES:Ti,isValidSchemeName:MI,getSchemeHandler:Bu}});var Hh=A((cG,ki)=>{"use strict";var{normalizeIPv6:WI,removeDotSegments:Go,recomposeAuthority:JI,normalizeComponentEncoding:Ai,isIPv4:YI,nonSimpleDomain:XI}=Hu(),{SCHEMES:QI,getSchemeHandler:Lh}=qh();function eT(e,t){return typeof e=="string"?e=Ut(er(e,t),t):typeof e=="object"&&(e=er(Ut(e,t),t)),e}o(eT,"normalize");function tT(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=jh(er(e,n),er(t,n),n,!0);return n.skipEscape=!0,Ut(a,n)}o(tT,"resolve");function jh(e,t,r,n){let a={};return n||(e=er(Ut(e,r),r),t=er(Ut(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Go(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Go(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=Go(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=Go(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}o(jh,"resolveComponent");function rT(e,t,r){return typeof e=="string"?(e=unescape(e),e=Ut(Ai(er(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ut(Ai(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=Ut(Ai(er(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ut(Ai(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(rT,"equal");function Ut(e,t){let r={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:""},n=Object.assign({},t),a=[],i=Lh(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let s=JI(r);if(s!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(s),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(u=Go(u)),s===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),a.push(u)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}o(Ut,"serialize");var nT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function er(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(nT);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host)if(YI(n.host)===!1){let d=WI(n.host);n.host=d.host.toLowerCase(),a=d.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=Lh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&XI(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(er,"parse");var Fu={SCHEMES:QI,normalize:eT,resolve:tT,resolveComponent:jh,equal:rT,serialize:Ut,parse:er};ki.exports=Fu;ki.exports.default=Fu;ki.exports.fastUri=Fu});var Bh=A(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var Gh=Hh();Gh.code='require("ajv/dist/runtime/uri").default';Vu.default=Gh});var Xh=A(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var oT=jo();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:o(function(){return oT.KeywordCxt},"get")});var xn=Z();Object.defineProperty(Ue,"_",{enumerable:!0,get:o(function(){return xn._},"get")});Object.defineProperty(Ue,"str",{enumerable:!0,get:o(function(){return xn.str},"get")});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:o(function(){return xn.stringify},"get")});Object.defineProperty(Ue,"nil",{enumerable:!0,get:o(function(){return xn.nil},"get")});Object.defineProperty(Ue,"Name",{enumerable:!0,get:o(function(){return xn.Name},"get")});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:o(function(){return xn.CodeGen},"get")});var aT=Ri(),Wh=Ho(),iT=vu(),Bo=Ci(),sT=Z(),Fo=Mo(),Ei=Do(),Zu=oe(),Fh=xh(),cT=Bh(),Jh=o((e,t)=>new RegExp(e,t),"defaultRegExp");Jh.code="new RegExp";var uT=["removeAdditional","useDefaults","coerceTypes"],dT=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),lT={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."},pT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vh=200;function mT(e){var t,r,n,a,i,s,u,d,p,l,m,f,_,w,y,S,v,R,b,q,L,je,ut,fn,ur;let Gt=e.strict,zr=(t=e.code)===null||t===void 0?void 0:t.optimize,co=zr===!0||zr===void 0?1:zr||0,uo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Jh,lo=(a=e.uriResolver)!==null&&a!==void 0?a:cT.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Gt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(u=e.strictNumbers)!==null&&u!==void 0?u:Gt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:Gt)!==null&&l!==void 0?l:"log",strictTuples:(f=(m=e.strictTuples)!==null&&m!==void 0?m:Gt)!==null&&f!==void 0?f:"log",strictRequired:(w=(_=e.strictRequired)!==null&&_!==void 0?_:Gt)!==null&&w!==void 0?w:!1,code:e.code?{...e.code,optimize:co,regExp:uo}:{optimize:co,regExp:uo},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:Vh,loopEnum:(S=e.loopEnum)!==null&&S!==void 0?S:Vh,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(R=e.messages)!==null&&R!==void 0?R:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(q=e.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(L=e.addUsedSchema)!==null&&L!==void 0?L:!0,validateSchema:(je=e.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(ut=e.validateFormats)!==null&&ut!==void 0?ut:!0,unicodeRegExp:(fn=e.unicodeRegExp)!==null&&fn!==void 0?fn:!0,int32range:(ur=e.int32range)!==null&&ur!==void 0?ur:!0,uriResolver:lo}}o(mT,"requiredOptions");var Vo=class{static{o(this,"Ajv")}constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...mT(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new sT.ValueScope({scope:{},prefixes:dT,es5:r,lines:n}),this.logger=wT(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,iT.getRules)(),Kh.call(this,lT,t,"NOT SUPPORTED"),Kh.call(this,pT,t,"DEPRECATED","warn"),this._metaOpts=_T.call(this),t.formats&&fT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&gT.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),hT.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Fh;n==="id"&&(a={...Fh},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,m){await i.call(this,l.$schema);let f=this._addSchema(l,m);return f.validate||s.call(this,f)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(m){if(!(m instanceof Wh.default))throw m;return u.call(this,m),await d.call(this,m.missingSchema),s.call(this,l)}}function u({missingSchema:l,missingRef:m}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${m} cannot be resolved`)}async function d(l){let m=await p.call(this,l);this.refs[l]||await i.call(this,m.$schema),this.refs[l]||this.addSchema(m,l,r)}async function p(l){let m=this._loading[l];if(m)return m;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Fo.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=Zh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Bo.SchemaEnv({schema:{},schemaId:n});if(r=Bo.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Zh.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Fo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.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(vT.call(this,n,r),!r)return(0,Zu.eachItem)(n,i=>Ku.call(this,i)),this;bT.call(this,r);let a={...r,type:(0,Ei.getJSONTypes)(r.type),schemaType:(0,Ei.getJSONTypes)(r.schemaType)};return(0,Zu.eachItem)(n,a.type.length===0?i=>Ku.call(this,i,a):i=>a.type.forEach(s=>Ku.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let u of i)s=s[u];for(let u in n){let d=n[u];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[u];p&&l&&(s[u]=Yh(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:u}=this.opts;if(typeof t=="object")s=t[u];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let d=this._cache.get(t);if(d!==void 0)return d;n=(0,Fo.normalizeId)(s||n);let p=Fo.getSchemaRefs.call(this,t,n);return d=new Bo.SchemaEnv({schema:t,schemaId:u,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),a&&this.validateSchema(t,!0),d}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Bo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Bo.compileSchema.call(this,t)}finally{this.opts=r}}};Vo.ValidationError=aT.default;Vo.MissingRefError=Wh.default;Ue.default=Vo;function Kh(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}o(Kh,"checkOptions");function Zh(e){return e=(0,Fo.normalizeId)(e),this.schemas[e]||this.refs[e]}o(Zh,"getSchEnv");function hT(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}o(hT,"addInitialSchemas");function fT(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(fT,"addInitialFormats");function gT(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}o(gT,"addInitialKeywords");function _T(){let e={...this.opts};for(let t of uT)delete e[t];return e}o(_T,"getMetaSchemaOptions");var yT={log(){},warn(){},error(){}};function wT(e){if(e===!1)return yT;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}o(wT,"getLogger");var ST=/^[a-z_$][a-z0-9_$:-]*$/i;function vT(e,t){let{RULES:r}=this;if((0,Zu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!ST.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}o(vT,"checkKeyword");function Ku(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let u={keyword:e,definition:{...t,type:(0,Ei.getJSONTypes)(t.type),schemaType:(0,Ei.getJSONTypes)(t.schemaType)}};t.before?RT.call(this,s,u,t.before):s.rules.push(u),i.all[e]=u,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(Ku,"addRule");function RT(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}o(RT,"addBeforeRule");function bT(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Yh(t)),e.validateSchema=this.compile(t,!0))}o(bT,"keywordMetaschema");var CT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yh(e){return{anyOf:[e,CT]}}o(Yh,"schemaOrData")});var Qh=A(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var IT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Wu.default=IT});var nf=A(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.callRef=Kr.getValidate=void 0;var TT=Ho(),ef=mt(),tt=Z(),Pn=Xt(),tf=Ci(),xi=oe(),AT={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:s,opts:u,self:d}=n,{root:p}=i;if((r==="#"||r==="#/")&&a===p.baseId)return m();let l=tf.resolveRef.call(d,p,a,r);if(l===void 0)throw new TT.default(n.opts.uriResolver,a,r);if(l instanceof tf.SchemaEnv)return f(l);return _(l);function m(){if(i===p)return Pi(e,s,i,i.$async);let w=t.scopeValue("root",{ref:p});return Pi(e,(0,tt._)`${w}.validate`,p,p.$async)}function f(w){let y=rf(e,w);Pi(e,y,w,w.$async)}function _(w){let y=t.scopeValue("schema",u.code.source===!0?{ref:w,code:(0,tt.stringify)(w)}:{ref:w}),S=t.name("valid"),v=e.subschema({schema:w,dataTypes:[],schemaPath:tt.nil,topSchemaRef:y,errSchemaPath:r},S);e.mergeEvaluated(v),e.ok(S)}}};function rf(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,tt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(rf,"getValidate");Kr.getValidate=rf;function Pi(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:u,opts:d}=i,p=d.passContext?Pn.default.this:tt.nil;n?l():m();function l(){if(!u.$async)throw new Error("async schema referenced by sync schema");let w=a.let("valid");a.try(()=>{a.code((0,tt._)`await ${(0,ef.callValidateCode)(e,t,p)}`),_(t),s||a.assign(w,!0)},y=>{a.if((0,tt._)`!(${y} instanceof ${i.ValidationError})`,()=>a.throw(y)),f(y),s||a.assign(w,!1)}),e.ok(w)}o(l,"callAsyncRef");function m(){e.result((0,ef.callValidateCode)(e,t,p),()=>_(t),()=>f(t))}o(m,"callSyncRef");function f(w){let y=(0,tt._)`${w}.errors`;a.assign(Pn.default.vErrors,(0,tt._)`${Pn.default.vErrors} === null ? ${y} : ${Pn.default.vErrors}.concat(${y})`),a.assign(Pn.default.errors,(0,tt._)`${Pn.default.vErrors}.length`)}o(f,"addErrorsFrom");function _(w){var y;if(!i.opts.unevaluated)return;let S=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(i.props=xi.mergeEvaluated.props(a,S.props,i.props));else{let v=a.var("props",(0,tt._)`${w}.evaluated.props`);i.props=xi.mergeEvaluated.props(a,v,i.props,tt.Name)}if(i.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(i.items=xi.mergeEvaluated.items(a,S.items,i.items));else{let v=a.var("items",(0,tt._)`${w}.evaluated.items`);i.items=xi.mergeEvaluated.items(a,v,i.items,tt.Name)}}o(_,"addEvaluatedFrom")}o(Pi,"callRef");Kr.callRef=Pi;Kr.default=AT});var of=A(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var kT=Qh(),ET=nf(),xT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",kT.default,ET.default];Ju.default=xT});var af=A(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var Oi=Z(),Ir=Oi.operators,Ui={maximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},minimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},exclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},exclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},PT={message:o(({keyword:e,schemaCode:t})=>(0,Oi.str)`must be ${Ui[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Oi._)`{comparison: ${Ui[e].okStr}, limit: ${t}}`,"params")},OT={keyword:Object.keys(Ui),type:"number",schemaType:"number",$data:!0,error:PT,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Oi._)`${r} ${Ui[t].fail} ${n} || isNaN(${r})`)}};Yu.default=OT});var sf=A(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var Ko=Z(),UT={message:o(({schemaCode:e})=>(0,Ko.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Ko._)`{multipleOf: ${e}}`,"params")},NT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:UT,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),u=i?(0,Ko._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Ko._)`${s} !== parseInt(${s})`;e.fail$data((0,Ko._)`(${n} === 0 || (${s} = ${r}/${n}, ${u}))`)}};Xu.default=NT});var uf=A(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});function cf(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}o(cf,"ucs2length");Qu.default=cf;cf.code='require("ajv/dist/runtime/ucs2length").default'});var df=A(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Zr=Z(),zT=oe(),$T=uf(),DT={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Zr.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,Zr._)`{limit: ${e}}`,"params")},MT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:DT,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Zr.operators.GT:Zr.operators.LT,s=a.opts.unicode===!1?(0,Zr._)`${r}.length`:(0,Zr._)`${(0,zT.useFunc)(e.gen,$T.default)}(${r})`;e.fail$data((0,Zr._)`${s} ${i} ${n}`)}};ed.default=MT});var lf=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var qT=mt(),Ni=Z(),LT={message:o(({schemaCode:e})=>(0,Ni.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ni._)`{pattern: ${e}}`,"params")},jT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LT,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",u=r?(0,Ni._)`(new RegExp(${a}, ${s}))`:(0,qT.usePattern)(e,n);e.fail$data((0,Ni._)`!${u}.test(${t})`)}};td.default=jT});var pf=A(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Zo=Z(),HT={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Zo.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Zo._)`{limit: ${e}}`,"params")},GT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:HT,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Zo.operators.GT:Zo.operators.LT;e.fail$data((0,Zo._)`Object.keys(${r}).length ${a} ${n}`)}};rd.default=GT});var mf=A(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var Wo=mt(),Jo=Z(),BT=oe(),FT={message:o(({params:{missingProperty:e}})=>(0,Jo.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Jo._)`{missingProperty: ${e}}`,"params")},VT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:FT,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:u}=s;if(!i&&r.length===0)return;let d=r.length>=u.loopRequired;if(s.allErrors?p():l(),u.strictRequired){let _=e.parentSchema.properties,{definedProperties:w}=e.it;for(let y of r)if(_?.[y]===void 0&&!w.has(y)){let S=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${y}" is not defined at "${S}" (strictRequired)`;(0,BT.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Jo.nil,m);else for(let _ of r)(0,Wo.checkReportMissingProp)(e,_)}o(p,"allErrorsMode");function l(){let _=t.let("missing");if(d||i){let w=t.let("valid",!0);e.block$data(w,()=>f(_,w)),e.ok(w)}else t.if((0,Wo.checkMissingProp)(e,r,_)),(0,Wo.reportMissingProp)(e,_),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,_=>{e.setParams({missingProperty:_}),t.if((0,Wo.noPropertyInData)(t,a,_,u.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function f(_,w){e.setParams({missingProperty:_}),t.forOf(_,n,()=>{t.assign(w,(0,Wo.propertyInData)(t,a,_,u.ownProperties)),t.if((0,Jo.not)(w),()=>{e.error(),t.break()})},Jo.nil)}o(f,"loopUntilMissing")}};nd.default=VT});var hf=A(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var Yo=Z(),KT={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Yo.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Yo._)`{limit: ${e}}`,"params")},ZT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:KT,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Yo.operators.GT:Yo.operators.LT;e.fail$data((0,Yo._)`${r}.length ${a} ${n}`)}};od.default=ZT});var zi=A(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var ff=Eu();ff.code='require("ajv/dist/runtime/equal").default';ad.default=ff});var gf=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var id=Do(),Ne=Z(),WT=oe(),JT=zi(),YT={message:o(({params:{i:e,j:t}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,Ne._)`{i: ${e}, j: ${t}}`,"params")},XT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:YT,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:u}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,id.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,Ne._)`${s} === false`),e.ok(d);function l(){let w=t.let("i",(0,Ne._)`${r}.length`),y=t.let("j");e.setParams({i:w,j:y}),t.assign(d,!0),t.if((0,Ne._)`${w} > 1`,()=>(m()?f:_)(w,y))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(w=>w==="object"||w==="array")}o(m,"canOptimize");function f(w,y){let S=t.name("item"),v=(0,id.checkDataTypes)(p,S,u.opts.strictNumbers,id.DataType.Wrong),R=t.const("indices",(0,Ne._)`{}`);t.for((0,Ne._)`;${w}--;`,()=>{t.let(S,(0,Ne._)`${r}[${w}]`),t.if(v,(0,Ne._)`continue`),p.length>1&&t.if((0,Ne._)`typeof ${S} == "string"`,(0,Ne._)`${S} += "_"`),t.if((0,Ne._)`typeof ${R}[${S}] == "number"`,()=>{t.assign(y,(0,Ne._)`${R}[${S}]`),e.error(),t.assign(d,!1).break()}).code((0,Ne._)`${R}[${S}] = ${w}`)})}o(f,"loopN");function _(w,y){let S=(0,WT.useFunc)(t,JT.default),v=t.name("outer");t.label(v).for((0,Ne._)`;${w}--;`,()=>t.for((0,Ne._)`${y} = ${w}; ${y}--;`,()=>t.if((0,Ne._)`${S}(${r}[${w}], ${r}[${y}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(_,"loopN2")}};sd.default=XT});var _f=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var cd=Z(),QT=oe(),eA=zi(),tA={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,cd._)`{allowedValue: ${e}}`,"params")},rA={keyword:"const",$data:!0,error:tA,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,cd._)`!${(0,QT.useFunc)(t,eA.default)}(${r}, ${a})`):e.fail((0,cd._)`${i} !== ${r}`)}};ud.default=rA});var yf=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var Xo=Z(),nA=oe(),oA=zi(),aA={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Xo._)`{allowedValues: ${e}}`,"params")},iA={keyword:"enum",schemaType:"array",$data:!0,error:aA,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:s}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let u=a.length>=s.opts.loopEnum,d,p=o(()=>d??(d=(0,nA.useFunc)(t,oA.default)),"getEql"),l;if(u||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let _=t.const("vSchema",i);l=(0,Xo.or)(...a.map((w,y)=>f(_,y)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,_=>t.if((0,Xo._)`${p()}(${r}, ${_})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function f(_,w){let y=a[w];return typeof y=="object"&&y!==null?(0,Xo._)`${p()}(${r}, ${_}[${w}])`:(0,Xo._)`${r} === ${y}`}o(f,"equalCode")}};dd.default=iA});var wf=A(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var sA=af(),cA=sf(),uA=df(),dA=lf(),lA=pf(),pA=mf(),mA=hf(),hA=gf(),fA=_f(),gA=yf(),_A=[sA.default,cA.default,uA.default,dA.default,lA.default,pA.default,mA.default,hA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},fA.default,gA.default];ld.default=_A});var md=A(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.validateAdditionalItems=void 0;var Wr=Z(),pd=oe(),yA={message:o(({params:{len:e}})=>(0,Wr.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Wr._)`{limit: ${e}}`,"params")},wA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:yA,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,pd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Sf(e,n)}};function Sf(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let u=r.const("len",(0,Wr._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Wr._)`${u} <= ${t.length}`);else if(typeof n=="object"&&!(0,pd.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,Wr._)`${u} <= ${t.length}`);r.if((0,Wr.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,u,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:pd.Type.Num},p),s.allErrors||r.if((0,Wr.not)(p),()=>r.break())})}o(d,"validateItems")}o(Sf,"validateAdditionalItems");Qo.validateAdditionalItems=Sf;Qo.default=wA});var hd=A(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.validateTuple=void 0;var vf=Z(),$i=oe(),SA=mt(),vA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Rf(e,"additionalItems",t);r.items=!0,!(0,$i.alwaysValidSchema)(r,t)&&e.ok((0,SA.validateArray)(e))}};function Rf(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:s,it:u}=e;l(a),u.opts.unevaluated&&r.length&&u.items!==!0&&(u.items=$i.mergeEvaluated.items(n,r.length,u.items));let d=n.name("valid"),p=n.const("len",(0,vf._)`${i}.length`);r.forEach((m,f)=>{(0,$i.alwaysValidSchema)(u,m)||(n.if((0,vf._)`${p} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},d)),e.ok(d))});function l(m){let{opts:f,errSchemaPath:_}=u,w=r.length,y=w===m.minItems&&(w===m.maxItems||m[t]===!1);if(f.strictTuples&&!y){let S=`"${s}" is ${w}-tuple, but minItems or maxItems/${t} are not specified or different at path "${_}"`;(0,$i.checkStrictMode)(u,S,f.strictTuples)}}o(l,"checkStrictTuple")}o(Rf,"validateTuple");ea.validateTuple=Rf;ea.default=vA});var bf=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var RA=hd(),bA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,RA.validateTuple)(e,"items"),"code")};fd.default=bA});var If=A(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var Cf=Z(),CA=oe(),IA=mt(),TA=md(),AA={message:o(({params:{len:e}})=>(0,Cf.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Cf._)`{limit: ${e}}`,"params")},kA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:AA,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,CA.alwaysValidSchema)(n,t)&&(a?(0,TA.validateAdditionalItems)(e,a):e.ok((0,IA.validateArray)(e)))}};gd.default=kA});var Tf=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var ft=Z(),Di=oe(),EA={message:o(({params:{min:e,max:t}})=>t===void 0?(0,ft.str)`must contain at least ${e} valid item(s)`:(0,ft.str)`must contain at least ${e} and no more than ${t} valid item(s)`,"message"),params:o(({params:{min:e,max:t}})=>t===void 0?(0,ft._)`{minContains: ${e}}`:(0,ft._)`{minContains: ${e}, maxContains: ${t}}`,"params")},xA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:EA,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,s,u,{minContains:d,maxContains:p}=n;i.opts.next?(s=d===void 0?1:d,u=p):s=1;let l=t.const("len",(0,ft._)`${a}.length`);if(e.setParams({min:s,max:u}),u===void 0&&s===0){(0,Di.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(u!==void 0&&s>u){(0,Di.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Di.alwaysValidSchema)(i,r)){let y=(0,ft._)`${l} >= ${s}`;u!==void 0&&(y=(0,ft._)`${y} && ${l} <= ${u}`),e.pass(y);return}i.items=!0;let m=t.name("valid");u===void 0&&s===1?_(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),u!==void 0&&t.if((0,ft._)`${a}.length > 0`,f)):(t.let(m,!1),f()),e.result(m,()=>e.reset());function f(){let y=t.name("_valid"),S=t.let("count",0);_(y,()=>t.if(y,()=>w(S)))}o(f,"validateItemsWithCount");function _(y,S){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Di.Type.Num,compositeRule:!0},y),S()})}o(_,"validateItems");function w(y){t.code((0,ft._)`${y}++`),u===void 0?t.if((0,ft._)`${y} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,ft._)`${y} > ${u}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,ft._)`${y} >= ${s}`,()=>t.assign(m,!0)))}o(w,"checkLimits")}};_d.default=xA});var Ef=A(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.validateSchemaDeps=Nt.validatePropertyDeps=Nt.error=void 0;var yd=Z(),PA=oe(),ta=mt();Nt.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,yd.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,yd._)`{property: ${e},
25
+ import{$ as ge,H as Hp,I as tc,J as Rv,K as Lp,L as f,M as Bp,N as ee,O as ae,P as Gp,Q as Vp,R as we,S as C,T as I,U as Ce,V as me,W as rc,X as nc,Y as ue,Z as nt,_ as O,a as sr,aa as Fp,b as jp,ba as oc,ca as Zp,da as Kp,ea as u,fa as ie,j as uo,k as Dp,q as ec,z as Dt}from"../chunk-RQLHORT4.js";import{d as lo}from"../chunk-GDWI24KD.js";import{a as K}from"../chunk-NW4YQXGC.js";import{X as qa,Y as jt,Z as Np,a as o,c as x,e as qp}from"../chunk-JAEQKE5H.js";var Io=x(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Ro=class{static{o(this,"_CodeOrName")}};te._CodeOrName=Ro;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Mr=class extends Ro{static{o(this,"Name")}constructor(t){if(super(),!te.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=Mr;var ut=class extends Ro{static{o(this,"_Code")}constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Mr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};te._Code=ut;te.nil=new ut("");function pm(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Nc(r,t[n]),r.push(e[++n]);return new ut(r)}o(pm,"_");te._=pm;var qc=new ut("+");function mm(e,...t){let r=[Co(e[0])],n=0;for(;n<t.length;)r.push(qc),Nc(r,t[n]),r.push(qc,Co(e[++n]));return Kb(r),new ut(r)}o(mm,"str");te.str=mm;function Nc(e,t){t instanceof ut?e.push(...t._items):t instanceof Mr?e.push(t):e.push(Yb(t))}o(Nc,"addCodeArg");te.addCodeArg=Nc;function Kb(e){let t=1;for(;t<e.length-1;){if(e[t]===qc){let r=Wb(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(Kb,"optimize");function Wb(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Mr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Mr))return`"${e}${t.slice(1)}`}o(Wb,"mergeExprItems");function Jb(e,t){return t.emptyStr()?e:e.emptyStr()?t:mm`${e}${t}`}o(Jb,"strConcat");te.strConcat=Jb;function Yb(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Co(Array.isArray(e)?e.join(","):e)}o(Yb,"interpolate");function Qb(e){return new ut(Co(e))}o(Qb,"stringify");te.stringify=Qb;function Co(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(Co,"safeStringify");te.safeStringify=Co;function Xb(e){return typeof e=="string"&&te.IDENTIFIER.test(e)?new ut(`.${e}`):pm`[${e}]`}o(Xb,"getProperty");te.getProperty=Xb;function eR(e){if(typeof e=="string"&&te.IDENTIFIER.test(e))return new ut(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(eR,"getEsmExportName");te.getEsmExportName=eR;function tR(e){return new ut(e.toString())}o(tR,"regexpCode");te.regexpCode=tR});var Hc=x(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.ValueScope=We.ValueScopeName=We.Scope=We.varKinds=We.UsedValueState=void 0;var Ke=Io(),jc=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Xa;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Xa||(We.UsedValueState=Xa={}));We.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var ei=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ke.Name?t:this.name(t)}name(t){return new Ke.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};We.Scope=ei;var ti=class extends Ke.Name{static{o(this,"ValueScopeName")}constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ke._)`.${new Ke.Name(r)}[${n}]`}};We.ValueScopeName=ti;var rR=(0,Ke._)`\n`,Dc=class extends ei{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?rR:Ke.nil}}get(){return this._scope}name(t){return new ti(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,s=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let l=c.get(s);if(l)return l}else c=this._values[i]=new Map;c.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:i,itemIndex:p}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ke._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Ke.nil;for(let s in t){let c=t[s];if(!c)continue;let d=n[s]=n[s]||new Map;c.forEach(p=>{if(d.has(p))return;d.set(p,Xa.Started);let l=r(p);if(l){let m=this.opts.es5?We.varKinds.var:We.varKinds.const;i=(0,Ke._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Ke._)`${i}${l}${this.opts._n}`;else throw new jc(p);d.set(p,Xa.Completed)})}return i}};We.ValueScope=Dc});var F=x(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.or=Z.and=Z.not=Z.CodeGen=Z.operators=Z.varKinds=Z.ValueScopeName=Z.ValueScope=Z.Scope=Z.Name=Z.regexpCode=Z.stringify=Z.getProperty=Z.nil=Z.strConcat=Z.str=Z._=void 0;var Y=Io(),_t=Hc(),gr=Io();Object.defineProperty(Z,"_",{enumerable:!0,get:o(function(){return gr._},"get")});Object.defineProperty(Z,"str",{enumerable:!0,get:o(function(){return gr.str},"get")});Object.defineProperty(Z,"strConcat",{enumerable:!0,get:o(function(){return gr.strConcat},"get")});Object.defineProperty(Z,"nil",{enumerable:!0,get:o(function(){return gr.nil},"get")});Object.defineProperty(Z,"getProperty",{enumerable:!0,get:o(function(){return gr.getProperty},"get")});Object.defineProperty(Z,"stringify",{enumerable:!0,get:o(function(){return gr.stringify},"get")});Object.defineProperty(Z,"regexpCode",{enumerable:!0,get:o(function(){return gr.regexpCode},"get")});Object.defineProperty(Z,"Name",{enumerable:!0,get:o(function(){return gr.Name},"get")});var ai=Hc();Object.defineProperty(Z,"Scope",{enumerable:!0,get:o(function(){return ai.Scope},"get")});Object.defineProperty(Z,"ValueScope",{enumerable:!0,get:o(function(){return ai.ValueScope},"get")});Object.defineProperty(Z,"ValueScopeName",{enumerable:!0,get:o(function(){return ai.ValueScopeName},"get")});Object.defineProperty(Z,"varKinds",{enumerable:!0,get:o(function(){return ai.varKinds},"get")});Z.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Gt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},Lc=class extends Gt{static{o(this,"Def")}constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?_t.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Sn(this.rhs,t,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},ri=class extends Gt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Y.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Sn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return oi(t,this.rhs)}},Bc=class extends ri{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Gc=class extends Gt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Vc=class extends Gt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Fc=class extends Gt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Zc=class extends Gt{static{o(this,"AnyCode")}constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Sn(this.code,t,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},Po=class extends Gt{static{o(this,"ParentNode")}constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(nR(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>jr(t,r.names),{})}},Vt=class extends Po{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Kc=class extends Po{static{o(this,"Root")}},yn=class extends Vt{static{o(this,"Else")}};yn.kind="else";var qr=class e extends Vt{static{o(this,"If")}constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new yn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(fm(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Sn(this.condition,t,r),this}get names(){let t=super.names;return oi(t,this.condition),this.else&&jr(t,this.else.names),t}};qr.kind="if";var Nr=class extends Vt{static{o(this,"For")}};Nr.kind="for";var Wc=class extends Nr{static{o(this,"ForLoop")}constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Sn(this.iteration,t,r),this}get names(){return jr(super.names,this.iteration.names)}},Jc=class extends Nr{static{o(this,"ForRange")}constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?_t.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=oi(super.names,this.from);return oi(t,this.to)}},ni=class extends Nr{static{o(this,"ForIter")}constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Sn(this.iterable,t,r),this}get names(){return jr(super.names,this.iterable.names)}},xo=class extends Vt{static{o(this,"Func")}constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};xo.kind="func";var Ao=class extends Po{static{o(this,"Return")}render(t){return"return "+super.render(t)}};Ao.kind="return";var Yc=class extends Vt{static{o(this,"Try")}render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&jr(t,this.catch.names),this.finally&&jr(t,this.finally.names),t}},To=class extends Vt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};To.kind="catch";var ko=class extends Vt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};ko.kind="finally";var Qc=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
26
+ `:""},this._extScope=t,this._scope=new _t.Scope({parent:t}),this._nodes=[new Kc]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new Lc(t,i,n)),i}const(t,r,n){return this._def(_t.varKinds.const,t,r,n)}let(t,r,n){return this._def(_t.varKinds.let,t,r,n)}var(t,r,n){return this._def(_t.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ri(t,r,n))}add(t,r){return this._leafNode(new Bc(t,Z.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Y.nil&&this._leafNode(new Zc(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,a));return r.push("}"),new Y._Code(r)}if(t,r,n){if(this._blockNode(new qr(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new qr(t))}else(){return this._elseNode(new yn)}endIf(){return this._endBlockNode(qr,yn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Wc(t),r)}forRange(t,r,n,a,i=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let s=this._scope.toName(t);return this._for(new Jc(i,s,r,n),()=>a(s))}forOf(t,r,n,a=_t.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${s}.length`,c=>{this.var(i,(0,Y._)`${s}[${c}]`),n(i)})}return this._for(new ni("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Y._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ni("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Nr)}label(t){return this._leafNode(new Gc(t))}break(t){return this._leafNode(new Vc(t))}return(t){let r=new Ao;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ao)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Yc;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new To(i),r(i)}return n&&(this._currNode=a.finally=new ko,this.code(n)),this._endBlockNode(To,ko)}throw(t){return this._leafNode(new Fc(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Y.nil,n,a){return this._blockNode(new xo(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(xo)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof qr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Z.CodeGen=Qc;function jr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(jr,"addNames");function oi(e,t){return t instanceof Y._CodeOrName?jr(e,t.names):e}o(oi,"addExprNames");function Sn(e,t,r){if(e instanceof Y.Name)return n(e);if(!a(e))return e;return new Y._Code(e._items.reduce((i,s)=>(s instanceof Y.Name&&(s=n(s)),s instanceof Y._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof Y._Code&&i._items.some(s=>s instanceof Y.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(Sn,"optimizeExpr");function nR(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(nR,"subtractNames");function fm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Y._)`!${Xc(e)}`}o(fm,"not");Z.not=fm;var oR=hm(Z.operators.AND);function aR(...e){return e.reduce(oR)}o(aR,"and");Z.and=aR;var iR=hm(Z.operators.OR);function sR(...e){return e.reduce(iR)}o(sR,"or");Z.or=sR;function hm(e){return(t,r)=>t===Y.nil?r:r===Y.nil?t:(0,Y._)`${Xc(t)} ${e} ${Xc(r)}`}o(hm,"mappend");function Xc(e){return e instanceof Y.Name?e:(0,Y._)`(${e})`}o(Xc,"par")});var re=x(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var se=F(),cR=Io();function uR(e){let t={};for(let r of e)t[r]=!0;return t}o(uR,"toHash");W.toHash=uR;function dR(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Sm(e,t),!_m(t,e.self.RULES.all))}o(dR,"alwaysValidSchema");W.alwaysValidSchema=dR;function Sm(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||bm(e,`unknown keyword: "${i}"`)}o(Sm,"checkUnknownRules");W.checkUnknownRules=Sm;function _m(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(_m,"schemaHasRules");W.schemaHasRules=_m;function lR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(lR,"schemaHasRulesButRef");W.schemaHasRulesButRef=lR;function pR({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${e}${t}${(0,se.getProperty)(n)}`}o(pR,"schemaRefOrVal");W.schemaRefOrVal=pR;function mR(e){return wm(decodeURIComponent(e))}o(mR,"unescapeFragment");W.unescapeFragment=mR;function fR(e){return encodeURIComponent(tu(e))}o(fR,"escapeFragment");W.escapeFragment=fR;function tu(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(tu,"escapeJsonPointer");W.escapeJsonPointer=tu;function wm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(wm,"unescapeJsonPointer");W.unescapeJsonPointer=wm;function hR(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(hR,"eachItem");W.eachItem=hR;function gm({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof se.Name?(i instanceof se.Name?e(a,i,s):t(a,i,s),s):i instanceof se.Name?(t(a,s,i),i):r(i,s);return c===se.Name&&!(d instanceof se.Name)?n(a,d):d}}o(gm,"makeMergeEvaluated");W.mergeEvaluated={props:gm({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,se._)`${r} || {}`),ru(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:vm}),items:gm({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,se._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function vm(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,se._)`{}`);return t!==void 0&&ru(e,r,t),r}o(vm,"evaluatedPropsToName");W.evaluatedPropsToName=vm;function ru(e,t,r){Object.keys(r).forEach(n=>e.assign((0,se._)`${t}${(0,se.getProperty)(n)}`,!0))}o(ru,"setEvaluated");W.setEvaluated=ru;var ym={};function gR(e,t){return e.scopeValue("func",{ref:t,code:ym[t.code]||(ym[t.code]=new cR._Code(t.code))})}o(gR,"useFunc");W.useFunc=gR;var eu;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(eu||(W.Type=eu={}));function yR(e,t,r){if(e instanceof se.Name){let n=t===eu.Num;return r?n?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:n?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(e).toString():"/"+tu(e)}o(yR,"getErrorPath");W.getErrorPath=yR;function bm(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}o(bm,"checkStrictMode");W.checkStrictMode=bm});var Ft=x(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ne=F(),SR={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};nu.default=SR});var Eo=x(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var X=F(),ii=re(),Ve=Ft();je.keywordError={message:o(({keyword:e})=>(0,X.str)`must pass "${e}" keyword validation`,"message")};je.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,X.str)`"${e}" keyword must be ${t} ($data)`:(0,X.str)`"${e}" keyword is invalid ($data)`,"message")};function _R(e,t=je.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=Im(e,t,r);n??(s||c)?Rm(i,d):Cm(a,(0,X._)`[${d}]`)}o(_R,"reportError");je.reportError=_R;function wR(e,t=je.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=Im(e,t,r);Rm(a,c),i||s||Cm(n,Ve.default.vErrors)}o(wR,"reportExtraError");je.reportExtraError=wR;function vR(e,t){e.assign(Ve.default.errors,t),e.if((0,X._)`${Ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,X._)`${Ve.default.vErrors}.length`,t),()=>e.assign(Ve.default.vErrors,null)))}o(vR,"resetErrorsCount");je.resetErrorsCount=vR;function bR({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ve.default.errors,c=>{e.const(s,(0,X._)`${Ve.default.vErrors}[${c}]`),e.if((0,X._)`${s}.instancePath === undefined`,()=>e.assign((0,X._)`${s}.instancePath`,(0,X.strConcat)(Ve.default.instancePath,i.errorPath))),e.assign((0,X._)`${s}.schemaPath`,(0,X.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,X._)`${s}.schema`,r),e.assign((0,X._)`${s}.data`,n))})}o(bR,"extendErrors");je.extendErrors=bR;function Rm(e,t){let r=e.const("err",t);e.if((0,X._)`${Ve.default.vErrors} === null`,()=>e.assign(Ve.default.vErrors,(0,X._)`[${r}]`),(0,X._)`${Ve.default.vErrors}.push(${r})`),e.code((0,X._)`${Ve.default.errors}++`)}o(Rm,"addError");function Cm(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,X._)`new ${e.ValidationError}(${t})`):(r.assign((0,X._)`${n}.errors`,t),r.return(!1))}o(Cm,"returnErrors");var Dr={keyword:new X.Name("keyword"),schemaPath:new X.Name("schemaPath"),params:new X.Name("params"),propertyName:new X.Name("propertyName"),message:new X.Name("message"),schema:new X.Name("schema"),parentSchema:new X.Name("parentSchema")};function Im(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,X._)`{}`:RR(e,t,r)}o(Im,"errorObjectCode");function RR(e,t,r={}){let{gen:n,it:a}=e,i=[CR(a,r),IR(e,r)];return PR(e,t,i),n.object(...i)}o(RR,"errorObject");function CR({errorPath:e},{instancePath:t}){let r=t?(0,X.str)`${e}${(0,ii.getErrorPath)(t,ii.Type.Str)}`:e;return[Ve.default.instancePath,(0,X.strConcat)(Ve.default.instancePath,r)]}o(CR,"errorInstancePath");function IR({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,X.str)`${t}/${e}`;return r&&(a=(0,X.str)`${a}${(0,ii.getErrorPath)(r,ii.Type.Str)}`),[Dr.schemaPath,a]}o(IR,"errorSchemaPath");function PR(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:s,it:c}=e,{opts:d,propertyName:p,topSchemaRef:l,schemaPath:m}=c;n.push([Dr.keyword,a],[Dr.params,typeof t=="function"?t(e):t||(0,X._)`{}`]),d.messages&&n.push([Dr.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([Dr.schema,s],[Dr.parentSchema,(0,X._)`${l}${m}`],[Ve.default.data,i]),p&&n.push([Dr.propertyName,p])}o(PR,"extraErrorProps")});var xm=x(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.boolOrEmptySchema=_n.topBoolOrEmptySchema=void 0;var xR=Eo(),AR=F(),TR=Ft(),kR={message:"boolean schema is false"};function ER(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Pm(e,!1):typeof r=="object"&&r.$async===!0?t.return(TR.default.data):(t.assign((0,AR._)`${n}.errors`,null),t.return(!0))}o(ER,"topBoolOrEmptySchema");_n.topBoolOrEmptySchema=ER;function UR(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Pm(e)):r.var(t,!0)}o(UR,"boolOrEmptySchema");_n.boolOrEmptySchema=UR;function Pm(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,xR.reportError)(a,kR,void 0,t)}o(Pm,"falseSchemaError")});var ou=x(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.getRules=wn.isJSONType=void 0;var OR=["string","number","integer","boolean","null","object","array"],$R=new Set(OR);function zR(e){return typeof e=="string"&&$R.has(e)}o(zR,"isJSONType");wn.isJSONType=zR;function MR(){let 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:{}}}o(MR,"getRules");wn.getRules=MR});var au=x(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.shouldUseRule=yr.shouldUseGroup=yr.schemaHasRulesForType=void 0;function qR({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Am(e,n)}o(qR,"schemaHasRulesForType");yr.schemaHasRulesForType=qR;function Am(e,t){return t.rules.some(r=>Tm(e,r))}o(Am,"shouldUseGroup");yr.shouldUseGroup=Am;function Tm(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}o(Tm,"shouldUseRule");yr.shouldUseRule=Tm});var Uo=x(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var NR=ou(),jR=au(),DR=Eo(),V=F(),km=re(),vn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(vn||(De.DataType=vn={}));function HR(e){let t=Em(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}o(HR,"getSchemaTypes");De.getSchemaTypes=HR;function Em(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(NR.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Em,"getJSONTypes");De.getJSONTypes=Em;function LR(e,t){let{gen:r,data:n,opts:a}=e,i=BR(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,jR.schemaHasRulesForType)(e,t[0]));if(s){let c=su(t,n,a.strictNumbers,vn.Wrong);r.if(c,()=>{i.length?GR(e,t,i):cu(e)})}return s}o(LR,"coerceAndCheckDataType");De.coerceAndCheckDataType=LR;var Um=new Set(["string","number","integer","boolean","null"]);function BR(e,t){return t?e.filter(r=>Um.has(r)||t==="array"&&r==="array"):[]}o(BR,"coerceToTypes");function GR(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,V._)`typeof ${a}`),c=n.let("coerced",(0,V._)`undefined`);i.coerceTypes==="array"&&n.if((0,V._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,V._)`${a}[0]`).assign(s,(0,V._)`typeof ${a}`).if(su(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,V._)`${c} !== undefined`);for(let p of r)(Um.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),cu(e),n.endIf(),n.if((0,V._)`${c} !== undefined`,()=>{n.assign(a,c),VR(e,c)});function d(p){switch(p){case"string":n.elseIf((0,V._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,V._)`"" + ${a}`).elseIf((0,V._)`${a} === null`).assign(c,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${s} == "boolean" || ${a} === null
27
+ || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,V._)`+${a}`);return;case"integer":n.elseIf((0,V._)`${s} === "boolean" || ${a} === null
28
+ || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,V._)`+${a}`);return;case"boolean":n.elseIf((0,V._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,V._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,V._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,V._)`${s} === "string" || ${s} === "number"
29
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,V._)`[${a}]`)}}o(d,"coerceSpecificType")}o(GR,"coerceData");function VR({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${r}]`,n))}o(VR,"assignParentData");function iu(e,t,r,n=vn.Correct){let a=n===vn.Correct?V.operators.EQ:V.operators.NEQ,i;switch(e){case"null":return(0,V._)`${t} ${a} null`;case"array":i=(0,V._)`Array.isArray(${t})`;break;case"object":i=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,V._)`typeof ${t} ${a} ${e}`}return n===vn.Correct?i:(0,V.not)(i);function s(c=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,c,r?(0,V._)`isFinite(${t})`:V.nil)}}o(iu,"checkDataType");De.checkDataType=iu;function su(e,t,r,n){if(e.length===1)return iu(e[0],t,r,n);let a,i=(0,km.toHash)(e);if(i.array&&i.object){let s=(0,V._)`typeof ${t} != "object"`;a=i.null?s:(0,V._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=V.nil;i.number&&delete i.integer;for(let s in i)a=(0,V.and)(a,iu(s,t,r,n));return a}o(su,"checkDataTypes");De.checkDataTypes=su;var FR={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`,"params")};function cu(e){let t=ZR(e);(0,DR.reportError)(t,FR)}o(cu,"reportTypeError");De.reportTypeError=cu;function ZR(e){let{gen:t,data:r,schema:n}=e,a=(0,km.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(ZR,"getTypeErrorContext")});var $m=x(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.assignDefaults=void 0;var bn=F(),KR=re();function WR(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Om(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>Om(e,i,a.default))}o(WR,"assignDefaults");si.assignDefaults=WR;function Om(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,bn._)`${i}${(0,bn.getProperty)(t)}`;if(a){(0,KR.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,bn._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,bn._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,bn._)`${c} = ${(0,bn.stringify)(r)}`)}o(Om,"assignDefault")});var dt=x(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.validateUnion=oe.validateArray=oe.usePattern=oe.callValidateCode=oe.schemaProperties=oe.allSchemaProperties=oe.noPropertyInData=oe.propertyInData=oe.isOwnProperty=oe.hasPropFunc=oe.reportMissingProp=oe.checkMissingProp=oe.checkReportMissingProp=void 0;var de=F(),uu=re(),Sr=Ft(),JR=re();function YR(e,t){let{gen:r,data:n,it:a}=e;r.if(lu(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,de._)`${t}`},!0),e.error()})}o(YR,"checkReportMissingProp");oe.checkReportMissingProp=YR;function QR({gen:e,data:t,it:{opts:r}},n,a){return(0,de.or)(...n.map(i=>(0,de.and)(lu(e,t,i,r.ownProperties),(0,de._)`${a} = ${i}`)))}o(QR,"checkMissingProp");oe.checkMissingProp=QR;function XR(e,t){e.setParams({missingProperty:t},!0),e.error()}o(XR,"reportMissingProp");oe.reportMissingProp=XR;function zm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}o(zm,"hasPropFunc");oe.hasPropFunc=zm;function du(e,t,r){return(0,de._)`${zm(e)}.call(${t}, ${r})`}o(du,"isOwnProperty");oe.isOwnProperty=du;function eC(e,t,r,n){let a=(0,de._)`${t}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${a} && ${du(e,t,r)}`:a}o(eC,"propertyInData");oe.propertyInData=eC;function lu(e,t,r,n){let a=(0,de._)`${t}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(a,(0,de.not)(du(e,t,r))):a}o(lu,"noPropertyInData");oe.noPropertyInData=lu;function Mm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(Mm,"allSchemaProperties");oe.allSchemaProperties=Mm;function tC(e,t){return Mm(t).filter(r=>!(0,uu.alwaysValidSchema)(e,t[r]))}o(tC,"schemaProperties");oe.schemaProperties=tC;function rC({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,de._)`${e}, ${t}, ${n}${a}`:t,m=[[Sr.default.instancePath,(0,de.strConcat)(Sr.default.instancePath,i)],[Sr.default.parentData,s.parentData],[Sr.default.parentDataProperty,s.parentDataProperty],[Sr.default.rootData,Sr.default.rootData]];s.opts.dynamicRef&&m.push([Sr.default.dynamicAnchors,Sr.default.dynamicAnchors]);let h=(0,de._)`${l}, ${r.object(...m)}`;return d!==de.nil?(0,de._)`${c}.call(${d}, ${h})`:(0,de._)`${c}(${h})`}o(rC,"callValidateCode");oe.callValidateCode=rC;var nC=(0,de._)`new RegExp`;function oC({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,de._)`${a.code==="new RegExp"?nC:(0,JR.useFunc)(e,a)}(${r}, ${n})`})}o(oC,"usePattern");oe.usePattern=oC;function aC(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(i,!0),s(()=>t.break()),i;function s(c){let d=t.const("len",(0,de._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:uu.Type.Num},i),t.if((0,de.not)(i),c)})}o(s,"validateItems")}o(aC,"validateArray");oe.validateArray=aC;function iC(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,uu.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},c);t.assign(s,(0,de._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,de.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(iC,"validateUnion");oe.validateUnion=iC});var jm=x(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;var Fe=F(),Hr=Ft(),sC=dt(),cC=Eo();function uC(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=Nm(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(uC,"macroKeywordCode");Pt.macroKeywordCode=uC;function dC(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;pC(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=Nm(n,a,p),m=n.let("valid");e.block$data(m,h),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function h(){if(t.errors===!1)S(),t.modifying&&qm(e),w(()=>e.error());else{let v=t.async?y():_();t.modifying&&qm(e),w(()=>lC(e,v))}}o(h,"validateKeyword");function y(){let v=n.let("ruleErrs",null);return n.try(()=>S((0,Fe._)`await `),b=>n.assign(m,!1).if((0,Fe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Fe._)`${b}.errors`),()=>n.throw(b))),v}o(y,"validateAsync");function _(){let v=(0,Fe._)`${l}.errors`;return n.assign(v,null),S(Fe.nil),v}o(_,"validateSync");function S(v=t.async?(0,Fe._)`await `:Fe.nil){let b=d.opts.passContext?Hr.default.this:Hr.default.self,R=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Fe._)`${v}${(0,sC.callValidateCode)(e,l,b,R)}`,t.modifying)}o(S,"assignValid");function w(v){var b;n.if((0,Fe.not)((b=t.valid)!==null&&b!==void 0?b:m),v)}o(w,"reportErrs")}o(dC,"funcKeywordCode");Pt.funcKeywordCode=dC;function qm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}o(qm,"modifyData");function lC(e,t){let{gen:r}=e;r.if((0,Fe._)`Array.isArray(${t})`,()=>{r.assign(Hr.default.vErrors,(0,Fe._)`${Hr.default.vErrors} === null ? ${t} : ${Hr.default.vErrors}.concat(${t})`).assign(Hr.default.errors,(0,Fe._)`${Hr.default.vErrors}.length`),(0,cC.extendErrors)(e)},()=>e.error())}o(lC,"addErrs");function pC({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(pC,"checkAsyncKeyword");function Nm(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}o(Nm,"useKeyword");function mC(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}o(mC,"validSchemaType");Pt.validSchemaType=mC;function fC({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let s=a.dependencies;if(s?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let d=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}o(fC,"validateKeywordUsage");Pt.validateKeywordUsage=fC});var Hm=x(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.extendSubschemaMode=_r.extendSubschemaData=_r.getSubschema=void 0;var xt=F(),Dm=re();function hC(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,xt._)`${e.schemaPath}${(0,xt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,xt._)`${e.schemaPath}${(0,xt.getProperty)(t)}${(0,xt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Dm.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}o(hC,"getSubschema");_r.getSubschema=hC;function gC(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:s}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:p,dataPathArr:l,opts:m}=t,h=c.let("data",(0,xt._)`${t.data}${(0,xt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,xt.str)`${p}${(0,Dm.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,xt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof xt.Name?a:c.let("data",a,!0);d(p),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(p){e.data=p,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,p]}o(d,"dataContextProps")}o(gC,"extendSubschemaData");_r.extendSubschemaData=gC;function yC(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}o(yC,"extendSubschemaMode");_r.extendSubschemaMode=yC});var pu=x(($H,Lm)=>{"use strict";Lm.exports=o(function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var s=i[a];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r},"equal")});var Gm=x((MH,Bm)=>{"use strict";var wr=Bm.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};ci(t,n,a,e,"",e)};wr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wr.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 ci(e,t,r,n,a,i,s,c,d,p){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,s,c,d,p);for(var l in n){var m=n[l];if(Array.isArray(m)){if(l in wr.arrayKeywords)for(var h=0;h<m.length;h++)ci(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in wr.propsKeywords){if(m&&typeof m=="object")for(var y in m)ci(e,t,r,m[y],a+"/"+l+"/"+SC(y),i,a,l,n,y)}else(l in wr.keywords||e.allKeys&&!(l in wr.skipKeywords))&&ci(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(ci,"_traverse");function SC(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(SC,"escapeJsonPtr")});var Oo=x(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.getSchemaRefs=Je.resolveUrl=Je.normalizeId=Je._getFullPath=Je.getFullPath=Je.inlineRef=void 0;var _C=re(),wC=pu(),vC=Gm(),bC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function RC(e,t=!0){return typeof e=="boolean"?!0:t===!0?!mu(e):t?Vm(e)<=t:!1}o(RC,"inlineRef");Je.inlineRef=RC;var CC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mu(e){for(let t in e){if(CC.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(mu)||typeof r=="object"&&mu(r))return!0}return!1}o(mu,"hasRef");function Vm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!bC.has(r)&&(typeof e[r]=="object"&&(0,_C.eachItem)(e[r],n=>t+=Vm(n)),t===1/0))return 1/0}return t}o(Vm,"countKeys");function Fm(e,t="",r){r!==!1&&(t=Rn(t));let n=e.parse(t);return Zm(e,n)}o(Fm,"getFullPath");Je.getFullPath=Fm;function Zm(e,t){return e.serialize(t).split("#")[0]+"#"}o(Zm,"_getFullPath");Je._getFullPath=Zm;var IC=/#\/?$/;function Rn(e){return e?e.replace(IC,""):""}o(Rn,"normalizeId");Je.normalizeId=Rn;function PC(e,t,r){return r=Rn(r),e.resolve(t,r)}o(PC,"resolveUrl");Je.resolveUrl=PC;var xC=/^[a-z_][-a-z0-9._]*$/i;function AC(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Rn(e[r]||t),i={"":a},s=Fm(n,a,!1),c={},d=new Set;return vC(e,{allKeys:!0},(m,h,y,_)=>{if(_===void 0)return;let S=s+h,w=i[_];typeof m[r]=="string"&&(w=v.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),i[h]=w;function v(R){let q=this.opts.uriResolver.resolve;if(R=Rn(w?q(w,R):R),d.has(R))throw l(R);d.add(R);let N=this.refs[R];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?p(m,N.schema,R):R!==Rn(S)&&(R[0]==="#"?(p(m,c[R],R),c[R]=m):this.refs[R]=S),R}o(v,"addRef");function b(R){if(typeof R=="string"){if(!xC.test(R))throw new Error(`invalid anchor "${R}"`);v.call(this,`#${R}`)}}o(b,"addAnchor")}),c;function p(m,h,y){if(h!==void 0&&!wC(m,h))throw l(y)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(AC,"getSchemaRefs");Je.getSchemaRefs=AC});var Mo=x(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var Qm=xm(),Km=Uo(),hu=au(),ui=Uo(),TC=$m(),zo=jm(),fu=Hm(),$=F(),L=Ft(),kC=Oo(),Zt=re(),$o=Eo();function EC(e){if(tf(e)&&(rf(e),ef(e))){$C(e);return}Xm(e,()=>(0,Qm.topBoolOrEmptySchema)(e))}o(EC,"validateFunctionCode");vr.validateFunctionCode=EC;function Xm({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,$._)`${L.default.data}, ${L.default.valCxt}`,n.$async,()=>{e.code((0,$._)`"use strict"; ${Wm(r,a)}`),OC(e,a),e.code(i)}):e.func(t,(0,$._)`${L.default.data}, ${UC(a)}`,n.$async,()=>e.code(Wm(r,a)).code(i))}o(Xm,"validateFunction");function UC(e){return(0,$._)`{${L.default.instancePath}="", ${L.default.parentData}, ${L.default.parentDataProperty}, ${L.default.rootData}=${L.default.data}${e.dynamicRef?(0,$._)`, ${L.default.dynamicAnchors}={}`:$.nil}}={}`}o(UC,"destructureValCxt");function OC(e,t){e.if(L.default.valCxt,()=>{e.var(L.default.instancePath,(0,$._)`${L.default.valCxt}.${L.default.instancePath}`),e.var(L.default.parentData,(0,$._)`${L.default.valCxt}.${L.default.parentData}`),e.var(L.default.parentDataProperty,(0,$._)`${L.default.valCxt}.${L.default.parentDataProperty}`),e.var(L.default.rootData,(0,$._)`${L.default.valCxt}.${L.default.rootData}`),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,$._)`${L.default.valCxt}.${L.default.dynamicAnchors}`)},()=>{e.var(L.default.instancePath,(0,$._)`""`),e.var(L.default.parentData,(0,$._)`undefined`),e.var(L.default.parentDataProperty,(0,$._)`undefined`),e.var(L.default.rootData,L.default.data),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,$._)`{}`)})}o(OC,"destructureValCxtES5");function $C(e){let{schema:t,opts:r,gen:n}=e;Xm(e,()=>{r.$comment&&t.$comment&&of(e),jC(e),n.let(L.default.vErrors,null),n.let(L.default.errors,0),r.unevaluated&&zC(e),nf(e),LC(e)})}o($C,"topSchemaObjCode");function zC(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,$._)`${r}.evaluated`),t.if((0,$._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,$._)`${e.evaluated}.props`,(0,$._)`undefined`)),t.if((0,$._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,$._)`${e.evaluated}.items`,(0,$._)`undefined`))}o(zC,"resetEvaluated");function Wm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,$._)`/*# sourceURL=${r} */`:$.nil}o(Wm,"funcSourceUrl");function MC(e,t){if(tf(e)&&(rf(e),ef(e))){qC(e,t);return}(0,Qm.boolOrEmptySchema)(e,t)}o(MC,"subschemaCode");function ef({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}o(ef,"schemaCxtHasRules");function tf(e){return typeof e.schema!="boolean"}o(tf,"isSchemaObj");function qC(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&of(e),DC(e),HC(e);let i=n.const("_errs",L.default.errors);nf(e,i),n.var(t,(0,$._)`${i} === ${L.default.errors}`)}o(qC,"subSchemaObjCode");function rf(e){(0,Zt.checkUnknownRules)(e),NC(e)}o(rf,"checkKeywords");function nf(e,t){if(e.opts.jtd)return Jm(e,[],!1,t);let r=(0,Km.getSchemaTypes)(e.schema),n=(0,Km.coerceAndCheckDataType)(e,r);Jm(e,r,!n,t)}o(nf,"typeAndKeywords");function NC(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Zt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(NC,"checkRefsAndKeywords");function jC(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Zt.checkStrictMode)(e,"default is ignored in the schema root")}o(jC,"checkNoDefault");function DC(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,kC.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(DC,"updateContext");function HC(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(HC,"checkAsyncSchema");function of({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,$._)`${L.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,$.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,$._)`${L.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(of,"commentKeyword");function LC(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,$._)`${L.default.errors} === 0`,()=>t.return(L.default.data),()=>t.throw((0,$._)`new ${a}(${L.default.vErrors})`)):(t.assign((0,$._)`${n}.errors`,L.default.vErrors),i.unevaluated&&BC(e),t.return((0,$._)`${L.default.errors} === 0`))}o(LC,"returnResults");function BC({gen:e,evaluated:t,props:r,items:n}){r instanceof $.Name&&e.assign((0,$._)`${t}.props`,r),n instanceof $.Name&&e.assign((0,$._)`${t}.items`,n)}o(BC,"assignEvaluated");function Jm(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:c,opts:d,self:p}=e,{RULES:l}=p;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Zt.schemaHasRulesButRef)(i,l))){a.block(()=>sf(e,"$ref",l.all.$ref.definition));return}d.jtd||GC(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,hu.shouldUseGroup)(i,h)&&(h.type?(a.if((0,ui.checkDataType)(h.type,s,d.strictNumbers)),Ym(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,ui.reportTypeError)(e)),a.endIf()):Ym(e,h),c||a.if((0,$._)`${L.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(Jm,"schemaKeywords");function Ym(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,TC.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,hu.shouldUseRule)(n,i)&&sf(e,i.keyword,i.definition,t.type)})}o(Ym,"iterateKeywords");function GC(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(VC(e,t),e.opts.allowUnionTypes||FC(e,t),ZC(e,e.dataTypes))}o(GC,"checkStrictTypes");function VC(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{af(e.dataTypes,r)||gu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),WC(e,t)}}o(VC,"checkContextTypes");function FC(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&gu(e,"use allowUnionTypes to allow union type keyword")}o(FC,"checkMultipleTypes");function ZC(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,hu.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>KC(t,s))&&gu(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(ZC,"checkKeywordTypes");function KC(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(KC,"hasApplicableType");function af(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(af,"includesType");function WC(e,t){let r=[];for(let n of e.dataTypes)af(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(WC,"narrowSchemaTypes");function gu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Zt.checkStrictMode)(e,t,e.opts.strictTypes)}o(gu,"strictTypesError");var di=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,zo.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Zt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",cf(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,zo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",L.default.errors))}result(t,r,n){this.failResult((0,$.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,$.not)(t),void 0,r)}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);let{schemaCode:r}=this;this.fail((0,$._)`${r} !== undefined && (${(0,$.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?$o.reportExtraError:$o.reportError)(this,this.def.error,r)}$dataError(){(0,$o.reportError)(this,this.def.$dataError||$o.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$o.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=$.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=$.nil,r=$.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,$.or)((0,$._)`${a} === undefined`,r)),t!==$.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==$.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,$.or)(s(),c());function s(){if(n.length){if(!(r instanceof $.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,$._)`${(0,ui.checkDataTypes)(d,r,i.opts.strictNumbers,ui.DataType.Wrong)}`}return $.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,$._)`!${d}(${r})`}return $.nil}}subschema(t,r){let n=(0,fu.getSubschema)(this.it,t);(0,fu.extendSubschemaData)(n,this.it,t),(0,fu.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return MC(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Zt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Zt.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,$.Name)),!0}};vr.KeywordCxt=di;function sf(e,t,r,n){let a=new di(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,zo.funcKeywordCode)(a,r):"macro"in r?(0,zo.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,zo.funcKeywordCode)(a,r)}o(sf,"keywordCode");var JC=/^\/(?:[^~]|~0|~1)*$/,YC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cf(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return L.default.rootData;if(e[0]==="/"){if(!JC.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=L.default.rootData}else{let p=YC.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,c=a.split("/");for(let p of c)p&&(i=(0,$._)`${i}${(0,$.getProperty)((0,Zt.unescapeJsonPointer)(p))}`,s=(0,$._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(cf,"getData");vr.getData=cf});var li=x(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var yu=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Su.default=yu});var qo=x(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var _u=Oo(),wu=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,_u.resolveUrl)(t,r,n),this.missingSchema=(0,_u.normalizeId)((0,_u.getFullPath)(t,this.missingRef))}};vu.default=wu});var mi=x(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var wt=F(),QC=li(),Lr=Ft(),vt=Oo(),uf=re(),XC=Mo(),Cn=class{static{o(this,"SchemaEnv")}constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,vt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=Cn;function Ru(e){let t=df.call(this,e);if(t)return t;let r=(0,vt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new wt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:QC.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:Lr.default.data,parentData:Lr.default.parentData,parentDataProperty:Lr.default.parentDataProperty,dataNames:[Lr.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,wt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:wt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,XC.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(Lr.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let y=new Function(`${Lr.default.self}`,`${Lr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:_,items:S}=p;y.evaluated={props:_ instanceof wt.Name?void 0:_,items:S instanceof wt.Name?void 0:S,dynamicProps:_ instanceof wt.Name,dynamicItems:S instanceof wt.Name},y.source&&(y.source.evaluated=(0,wt.stringify)(y.evaluated))}return e.validate=y,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Ru,"compileSchema");lt.compileSchema=Ru;function eI(e,t,r){var n;r=(0,vt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=nI.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;s&&(i=new Cn({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=tI.call(this,i)}o(eI,"resolveRef");lt.resolveRef=eI;function tI(e){return(0,vt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Ru.call(this,e)}o(tI,"inlineOrCompile");function df(e){for(let t of this._compilations)if(rI(t,e))return t}o(df,"getCompilingSchema");lt.getCompilingSchema=df;function rI(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(rI,"sameSchemaEnv");function nI(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||pi.call(this,e,t)}o(nI,"resolve");function pi(e,t){let r=this.opts.uriResolver.parse(t),n=(0,vt._getFullPath)(this.opts.uriResolver,r),a=(0,vt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return bu.call(this,r,e);let i=(0,vt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=pi.call(this,e,s);return typeof c?.schema!="object"?void 0:bu.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Ru.call(this,s),i===(0,vt.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,vt.resolveUrl)(this.opts.uriResolver,a,p)),new Cn({schema:c,schemaId:d,root:e,baseId:a})}return bu.call(this,r,s)}}o(pi,"resolveSchema");lt.resolveSchema=pi;var oI=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bu(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,uf.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!oI.has(c)&&p&&(t=(0,vt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,uf.schemaHasRulesButRef)(r,this.RULES)){let c=(0,vt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=pi.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new Cn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(bu,"getJsonPointer")});var lf=x((KH,aI)=>{aI.exports={$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 Iu=x((WH,hf)=>{"use strict";var iI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mf=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 Cu(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(Cu,"stringArrayToHexStripped");var sI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pf(e){return e.length=0,!0}o(pf,"consumeIsZone");function cI(e,t,r){if(e.length){let n=Cu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(cI,"consumeHextets");function uI(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=cI;for(let d=0;d<e.length;d++){let p=e[d];if(!(p==="["||p==="]"))if(p===":"){if(i===!0&&(s=!0),!c(a,n,r))break;if(++t>7){r.error=!0;break}d>0&&e[d-1]===":"&&(i=!0),n.push(":");continue}else if(p==="%"){if(!c(a,n,r))break;c=pf}else{a.push(p);continue}}return a.length&&(c===pf?r.zone=a.join(""):s?n.push(a.join("")):n.push(Cu(a))),r.address=n.join(""),r}o(uI,"getIPV6");function ff(e){if(dI(e,":")<2)return{host:e,isIPV6:!1};let t=uI(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}o(ff,"normalizeIPv6");function dI(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(dI,"findToken");function lI(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}o(lI,"removeDotSegments");function pI(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}o(pI,"normalizeComponentEncoding");function mI(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!mf(r)){let n=ff(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}o(mI,"recomposeAuthority");hf.exports={nonSimpleDomain:sI,recomposeAuthority:mI,normalizeComponentEncoding:pI,removeDotSegments:lI,isIPv4:mf,isUUID:iI,normalizeIPv6:ff,stringArrayToHexStripped:Cu}});var wf=x((YH,_f)=>{"use strict";var{isUUID:fI}=Iu(),hI=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,gI=["http","https","ws","wss","urn","urn:uuid"];function yI(e){return gI.indexOf(e)!==-1}o(yI,"isValidSchemeName");function Pu(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}o(Pu,"wsIsSecure");function gf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(gf,"httpParse");function yf(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}o(yf,"httpSerialize");function SI(e){return e.secure=Pu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(SI,"wsParse");function _I(e){if((e.port===(Pu(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){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(_I,"wsSerialize");function wI(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(hI);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=xu(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(wI,"urnParse");function vI(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=xu(a);i&&(e=i.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}o(vI,"urnSerialize");function bI(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!fI(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(bI,"urnuuidParse");function RI(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(RI,"urnuuidSerialize");var Sf={scheme:"http",domainHost:!0,parse:gf,serialize:yf},CI={scheme:"https",domainHost:Sf.domainHost,parse:gf,serialize:yf},fi={scheme:"ws",domainHost:!0,parse:SI,serialize:_I},II={scheme:"wss",domainHost:fi.domainHost,parse:fi.parse,serialize:fi.serialize},PI={scheme:"urn",parse:wI,serialize:vI,skipNormalize:!0},xI={scheme:"urn:uuid",parse:bI,serialize:RI,skipNormalize:!0},hi={http:Sf,https:CI,ws:fi,wss:II,urn:PI,"urn:uuid":xI};Object.setPrototypeOf(hi,null);function xu(e){return e&&(hi[e]||hi[e.toLowerCase()])||void 0}o(xu,"getSchemeHandler");_f.exports={wsIsSecure:Pu,SCHEMES:hi,isValidSchemeName:yI,getSchemeHandler:xu}});var Rf=x((XH,yi)=>{"use strict";var{normalizeIPv6:AI,removeDotSegments:No,recomposeAuthority:TI,normalizeComponentEncoding:gi,isIPv4:kI,nonSimpleDomain:EI}=Iu(),{SCHEMES:UI,getSchemeHandler:vf}=wf();function OI(e,t){return typeof e=="string"?e=At(Kt(e,t),t):typeof e=="object"&&(e=Kt(At(e,t),t)),e}o(OI,"normalize");function $I(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=bf(Kt(e,n),Kt(t,n),n,!0);return n.skipEscape=!0,At(a,n)}o($I,"resolve");function bf(e,t,r,n){let a={};return n||(e=Kt(At(e,r),r),t=Kt(At(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=No(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=No(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=No(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=No(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}o(bf,"resolveComponent");function zI(e,t,r){return typeof e=="string"?(e=unescape(e),e=At(gi(Kt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=At(gi(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=At(gi(Kt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=At(gi(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(zI,"equal");function At(e,t){let r={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:""},n=Object.assign({},t),a=[],i=vf(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let s=TI(r);if(s!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(s),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=No(c)),s===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),a.push(c)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}o(At,"serialize");var MI=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Kt(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(MI);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host)if(kI(n.host)===!1){let d=AI(n.host);n.host=d.host.toLowerCase(),a=d.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=vf(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&EI(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(Kt,"parse");var Au={SCHEMES:UI,normalize:OI,resolve:$I,resolveComponent:bf,equal:zI,serialize:At,parse:Kt};yi.exports=Au;yi.exports.default=Au;yi.exports.fastUri=Au});var If=x(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});var Cf=Rf();Cf.code='require("ajv/dist/runtime/uri").default';Tu.default=Cf});var Of=x(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=void 0;var qI=Mo();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:o(function(){return qI.KeywordCxt},"get")});var In=F();Object.defineProperty(Ee,"_",{enumerable:!0,get:o(function(){return In._},"get")});Object.defineProperty(Ee,"str",{enumerable:!0,get:o(function(){return In.str},"get")});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:o(function(){return In.stringify},"get")});Object.defineProperty(Ee,"nil",{enumerable:!0,get:o(function(){return In.nil},"get")});Object.defineProperty(Ee,"Name",{enumerable:!0,get:o(function(){return In.Name},"get")});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:o(function(){return In.CodeGen},"get")});var NI=li(),kf=qo(),jI=ou(),jo=mi(),DI=F(),Do=Oo(),Si=Uo(),Eu=re(),Pf=lf(),HI=If(),Ef=o((e,t)=>new RegExp(e,t),"defaultRegExp");Ef.code="new RegExp";var LI=["removeAdditional","useDefaults","coerceTypes"],BI=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),GI={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."},VI={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},xf=200;function FI(e){var t,r,n,a,i,s,c,d,p,l,m,h,y,_,S,w,v,b,R,q,N,qe,it,dn,ir;let qt=e.strict,Er=(t=e.code)===null||t===void 0?void 0:t.optimize,no=Er===!0||Er===void 0?1:Er||0,oo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ef,ao=(a=e.uriResolver)!==null&&a!==void 0?a:HI.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:qt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:qt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:qt)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:qt)!==null&&h!==void 0?h:"log",strictRequired:(_=(y=e.strictRequired)!==null&&y!==void 0?y:qt)!==null&&_!==void 0?_:!1,code:e.code?{...e.code,optimize:no,regExp:oo}:{optimize:no,regExp:oo},loopRequired:(S=e.loopRequired)!==null&&S!==void 0?S:xf,loopEnum:(w=e.loopEnum)!==null&&w!==void 0?w:xf,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(R=e.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(q=e.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(N=e.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(qe=e.validateSchema)!==null&&qe!==void 0?qe:!0,validateFormats:(it=e.validateFormats)!==null&&it!==void 0?it:!0,unicodeRegExp:(dn=e.unicodeRegExp)!==null&&dn!==void 0?dn:!0,int32range:(ir=e.int32range)!==null&&ir!==void 0?ir:!0,uriResolver:ao}}o(FI,"requiredOptions");var Ho=class{static{o(this,"Ajv")}constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...FI(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new DI.ValueScope({scope:{},prefixes:BI,es5:r,lines:n}),this.logger=QI(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,jI.getRules)(),Af.call(this,GI,t,"NOT SUPPORTED"),Af.call(this,VI,t,"DEPRECATED","warn"),this._metaOpts=JI.call(this),t.formats&&KI.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&WI.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),ZI.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Pf;n==="id"&&(a={...Pf},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,m){await i.call(this,l.$schema);let h=this._addSchema(l,m);return h.validate||s.call(this,h)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(m){if(!(m instanceof kf.default))throw m;return c.call(this,m),await d.call(this,m.missingSchema),s.call(this,l)}}function c({missingSchema:l,missingRef:m}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${m} cannot be resolved`)}async function d(l){let m=await p.call(this,l);this.refs[l]||await i.call(this,m.$schema),this.refs[l]||this.addSchema(m,l,r)}async function p(l){let m=this._loading[l];if(m)return m;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Do.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=Tf.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new jo.SchemaEnv({schema:{},schemaId:n});if(r=jo.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Tf.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Do.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.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(eP.call(this,n,r),!r)return(0,Eu.eachItem)(n,i=>ku.call(this,i)),this;rP.call(this,r);let a={...r,type:(0,Si.getJSONTypes)(r.type),schemaType:(0,Si.getJSONTypes)(r.schemaType)};return(0,Eu.eachItem)(n,a.type.length===0?i=>ku.call(this,i,a):i=>a.type.forEach(s=>ku.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let c of i)s=s[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[c];p&&l&&(s[c]=Uf(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:c}=this.opts;if(typeof t=="object")s=t[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let d=this._cache.get(t);if(d!==void 0)return d;n=(0,Do.normalizeId)(s||n);let p=Do.getSchemaRefs.call(this,t,n);return d=new jo.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),a&&this.validateSchema(t,!0),d}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):jo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{jo.compileSchema.call(this,t)}finally{this.opts=r}}};Ho.ValidationError=NI.default;Ho.MissingRefError=kf.default;Ee.default=Ho;function Af(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}o(Af,"checkOptions");function Tf(e){return e=(0,Do.normalizeId)(e),this.schemas[e]||this.refs[e]}o(Tf,"getSchEnv");function ZI(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}o(ZI,"addInitialSchemas");function KI(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(KI,"addInitialFormats");function WI(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}o(WI,"addInitialKeywords");function JI(){let e={...this.opts};for(let t of LI)delete e[t];return e}o(JI,"getMetaSchemaOptions");var YI={log(){},warn(){},error(){}};function QI(e){if(e===!1)return YI;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}o(QI,"getLogger");var XI=/^[a-z_$][a-z0-9_$:-]*$/i;function eP(e,t){let{RULES:r}=this;if((0,Eu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XI.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}o(eP,"checkKeyword");function ku(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Si.getJSONTypes)(t.type),schemaType:(0,Si.getJSONTypes)(t.schemaType)}};t.before?tP.call(this,s,c,t.before):s.rules.push(c),i.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(ku,"addRule");function tP(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}o(tP,"addBeforeRule");function rP(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Uf(t)),e.validateSchema=this.compile(t,!0))}o(rP,"keywordMetaschema");var nP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Uf(e){return{anyOf:[e,nP]}}o(Uf,"schemaOrData")});var $f=x(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var oP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Uu.default=oP});var Nf=x(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.callRef=Br.getValidate=void 0;var aP=qo(),zf=dt(),Ye=F(),Pn=Ft(),Mf=mi(),_i=re(),iP={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:s,opts:c,self:d}=n,{root:p}=i;if((r==="#"||r==="#/")&&a===p.baseId)return m();let l=Mf.resolveRef.call(d,p,a,r);if(l===void 0)throw new aP.default(n.opts.uriResolver,a,r);if(l instanceof Mf.SchemaEnv)return h(l);return y(l);function m(){if(i===p)return wi(e,s,i,i.$async);let _=t.scopeValue("root",{ref:p});return wi(e,(0,Ye._)`${_}.validate`,p,p.$async)}function h(_){let S=qf(e,_);wi(e,S,_,_.$async)}function y(_){let S=t.scopeValue("schema",c.code.source===!0?{ref:_,code:(0,Ye.stringify)(_)}:{ref:_}),w=t.name("valid"),v=e.subschema({schema:_,dataTypes:[],schemaPath:Ye.nil,topSchemaRef:S,errSchemaPath:r},w);e.mergeEvaluated(v),e.ok(w)}}};function qf(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ye._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(qf,"getValidate");Br.getValidate=qf;function wi(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?Pn.default.this:Ye.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let _=a.let("valid");a.try(()=>{a.code((0,Ye._)`await ${(0,zf.callValidateCode)(e,t,p)}`),y(t),s||a.assign(_,!0)},S=>{a.if((0,Ye._)`!(${S} instanceof ${i.ValidationError})`,()=>a.throw(S)),h(S),s||a.assign(_,!1)}),e.ok(_)}o(l,"callAsyncRef");function m(){e.result((0,zf.callValidateCode)(e,t,p),()=>y(t),()=>h(t))}o(m,"callSyncRef");function h(_){let S=(0,Ye._)`${_}.errors`;a.assign(Pn.default.vErrors,(0,Ye._)`${Pn.default.vErrors} === null ? ${S} : ${Pn.default.vErrors}.concat(${S})`),a.assign(Pn.default.errors,(0,Ye._)`${Pn.default.vErrors}.length`)}o(h,"addErrorsFrom");function y(_){var S;if(!i.opts.unevaluated)return;let w=(S=r?.validate)===null||S===void 0?void 0:S.evaluated;if(i.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(i.props=_i.mergeEvaluated.props(a,w.props,i.props));else{let v=a.var("props",(0,Ye._)`${_}.evaluated.props`);i.props=_i.mergeEvaluated.props(a,v,i.props,Ye.Name)}if(i.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(i.items=_i.mergeEvaluated.items(a,w.items,i.items));else{let v=a.var("items",(0,Ye._)`${_}.evaluated.items`);i.items=_i.mergeEvaluated.items(a,v,i.items,Ye.Name)}}o(y,"addEvaluatedFrom")}o(wi,"callRef");Br.callRef=wi;Br.default=iP});var jf=x(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var sP=$f(),cP=Nf(),uP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sP.default,cP.default];Ou.default=uP});var Df=x($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var vi=F(),br=vi.operators,bi={maximum:{okStr:"<=",ok:br.LTE,fail:br.GT},minimum:{okStr:">=",ok:br.GTE,fail:br.LT},exclusiveMaximum:{okStr:"<",ok:br.LT,fail:br.GTE},exclusiveMinimum:{okStr:">",ok:br.GT,fail:br.LTE}},dP={message:o(({keyword:e,schemaCode:t})=>(0,vi.str)`must be ${bi[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,vi._)`{comparison: ${bi[e].okStr}, limit: ${t}}`,"params")},lP={keyword:Object.keys(bi),type:"number",schemaType:"number",$data:!0,error:dP,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,vi._)`${r} ${bi[t].fail} ${n} || isNaN(${r})`)}};$u.default=lP});var Hf=x(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var Lo=F(),pP={message:o(({schemaCode:e})=>(0,Lo.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Lo._)`{multipleOf: ${e}}`,"params")},mP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:pP,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,Lo._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Lo._)`${s} !== parseInt(${s})`;e.fail$data((0,Lo._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};zu.default=mP});var Bf=x(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});function Lf(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}o(Lf,"ucs2length");Mu.default=Lf;Lf.code='require("ajv/dist/runtime/ucs2length").default'});var Gf=x(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var Gr=F(),fP=re(),hP=Bf(),gP={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Gr.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,Gr._)`{limit: ${e}}`,"params")},yP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:gP,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Gr.operators.GT:Gr.operators.LT,s=a.opts.unicode===!1?(0,Gr._)`${r}.length`:(0,Gr._)`${(0,fP.useFunc)(e.gen,hP.default)}(${r})`;e.fail$data((0,Gr._)`${s} ${i} ${n}`)}};qu.default=yP});var Vf=x(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var SP=dt(),Ri=F(),_P={message:o(({schemaCode:e})=>(0,Ri.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ri._)`{pattern: ${e}}`,"params")},wP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_P,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,Ri._)`(new RegExp(${a}, ${s}))`:(0,SP.usePattern)(e,n);e.fail$data((0,Ri._)`!${c}.test(${t})`)}};Nu.default=wP});var Ff=x(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var Bo=F(),vP={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Bo.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Bo._)`{limit: ${e}}`,"params")},bP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:vP,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Bo.operators.GT:Bo.operators.LT;e.fail$data((0,Bo._)`Object.keys(${r}).length ${a} ${n}`)}};ju.default=bP});var Zf=x(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var Go=dt(),Vo=F(),RP=re(),CP={message:o(({params:{missingProperty:e}})=>(0,Vo.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Vo._)`{missingProperty: ${e}}`,"params")},IP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:CP,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:c}=s;if(!i&&r.length===0)return;let d=r.length>=c.loopRequired;if(s.allErrors?p():l(),c.strictRequired){let y=e.parentSchema.properties,{definedProperties:_}=e.it;for(let S of r)if(y?.[S]===void 0&&!_.has(S)){let w=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${S}" is not defined at "${w}" (strictRequired)`;(0,RP.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Vo.nil,m);else for(let y of r)(0,Go.checkReportMissingProp)(e,y)}o(p,"allErrorsMode");function l(){let y=t.let("missing");if(d||i){let _=t.let("valid",!0);e.block$data(_,()=>h(y,_)),e.ok(_)}else t.if((0,Go.checkMissingProp)(e,r,y)),(0,Go.reportMissingProp)(e,y),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,Go.noPropertyInData)(t,a,y,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(y,_){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(_,(0,Go.propertyInData)(t,a,y,c.ownProperties)),t.if((0,Vo.not)(_),()=>{e.error(),t.break()})},Vo.nil)}o(h,"loopUntilMissing")}};Du.default=IP});var Kf=x(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var Fo=F(),PP={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Fo.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Fo._)`{limit: ${e}}`,"params")},xP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:PP,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Fo.operators.GT:Fo.operators.LT;e.fail$data((0,Fo._)`${r}.length ${a} ${n}`)}};Hu.default=xP});var Ci=x(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var Wf=pu();Wf.code='require("ajv/dist/runtime/equal").default';Lu.default=Wf});var Jf=x(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var Bu=Uo(),Ue=F(),AP=re(),TP=Ci(),kP={message:o(({params:{i:e,j:t}})=>(0,Ue.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,Ue._)`{i: ${e}, j: ${t}}`,"params")},EP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:kP,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,Bu.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,Ue._)`${s} === false`),e.ok(d);function l(){let _=t.let("i",(0,Ue._)`${r}.length`),S=t.let("j");e.setParams({i:_,j:S}),t.assign(d,!0),t.if((0,Ue._)`${_} > 1`,()=>(m()?h:y)(_,S))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(_=>_==="object"||_==="array")}o(m,"canOptimize");function h(_,S){let w=t.name("item"),v=(0,Bu.checkDataTypes)(p,w,c.opts.strictNumbers,Bu.DataType.Wrong),b=t.const("indices",(0,Ue._)`{}`);t.for((0,Ue._)`;${_}--;`,()=>{t.let(w,(0,Ue._)`${r}[${_}]`),t.if(v,(0,Ue._)`continue`),p.length>1&&t.if((0,Ue._)`typeof ${w} == "string"`,(0,Ue._)`${w} += "_"`),t.if((0,Ue._)`typeof ${b}[${w}] == "number"`,()=>{t.assign(S,(0,Ue._)`${b}[${w}]`),e.error(),t.assign(d,!1).break()}).code((0,Ue._)`${b}[${w}] = ${_}`)})}o(h,"loopN");function y(_,S){let w=(0,AP.useFunc)(t,TP.default),v=t.name("outer");t.label(v).for((0,Ue._)`;${_}--;`,()=>t.for((0,Ue._)`${S} = ${_}; ${S}--;`,()=>t.if((0,Ue._)`${w}(${r}[${_}], ${r}[${S}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(y,"loopN2")}};Gu.default=EP});var Yf=x(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var Vu=F(),UP=re(),OP=Ci(),$P={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,Vu._)`{allowedValue: ${e}}`,"params")},zP={keyword:"const",$data:!0,error:$P,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Vu._)`!${(0,UP.useFunc)(t,OP.default)}(${r}, ${a})`):e.fail((0,Vu._)`${i} !== ${r}`)}};Fu.default=zP});var Qf=x(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var Zo=F(),MP=re(),qP=Ci(),NP={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Zo._)`{allowedValues: ${e}}`,"params")},jP={keyword:"enum",schemaType:"array",$data:!0,error:NP,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:s}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let c=a.length>=s.opts.loopEnum,d,p=o(()=>d??(d=(0,MP.useFunc)(t,qP.default)),"getEql"),l;if(c||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let y=t.const("vSchema",i);l=(0,Zo.or)(...a.map((_,S)=>h(y,S)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,y=>t.if((0,Zo._)`${p()}(${r}, ${y})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(y,_){let S=a[_];return typeof S=="object"&&S!==null?(0,Zo._)`${p()}(${r}, ${y}[${_}])`:(0,Zo._)`${r} === ${S}`}o(h,"equalCode")}};Zu.default=jP});var Xf=x(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var DP=Df(),HP=Hf(),LP=Gf(),BP=Vf(),GP=Ff(),VP=Zf(),FP=Kf(),ZP=Jf(),KP=Yf(),WP=Qf(),JP=[DP.default,HP.default,LP.default,BP.default,GP.default,VP.default,FP.default,ZP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},KP.default,WP.default];Ku.default=JP});var Ju=x(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.validateAdditionalItems=void 0;var Vr=F(),Wu=re(),YP={message:o(({params:{len:e}})=>(0,Vr.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Vr._)`{limit: ${e}}`,"params")},QP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:YP,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Wu.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}eh(e,n)}};function eh(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,Vr._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Vr._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Wu.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,Vr._)`${c} <= ${t.length}`);r.if((0,Vr.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Wu.Type.Num},p),s.allErrors||r.if((0,Vr.not)(p),()=>r.break())})}o(d,"validateItems")}o(eh,"validateAdditionalItems");Ko.validateAdditionalItems=eh;Ko.default=QP});var Yu=x(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.validateTuple=void 0;var th=F(),Ii=re(),XP=dt(),ex={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return rh(e,"additionalItems",t);r.items=!0,!(0,Ii.alwaysValidSchema)(r,t)&&e.ok((0,XP.validateArray)(e))}};function rh(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:s,it:c}=e;l(a),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Ii.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,th._)`${i}.length`);r.forEach((m,h)=>{(0,Ii.alwaysValidSchema)(c,m)||(n.if((0,th._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:y}=c,_=r.length,S=_===m.minItems&&(_===m.maxItems||m[t]===!1);if(h.strictTuples&&!S){let w=`"${s}" is ${_}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,Ii.checkStrictMode)(c,w,h.strictTuples)}}o(l,"checkStrictTuple")}o(rh,"validateTuple");Wo.validateTuple=rh;Wo.default=ex});var nh=x(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var tx=Yu(),rx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,tx.validateTuple)(e,"items"),"code")};Qu.default=rx});var ah=x(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var oh=F(),nx=re(),ox=dt(),ax=Ju(),ix={message:o(({params:{len:e}})=>(0,oh.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,oh._)`{limit: ${e}}`,"params")},sx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ix,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,nx.alwaysValidSchema)(n,t)&&(a?(0,ax.validateAdditionalItems)(e,a):e.ok((0,ox.validateArray)(e)))}};Xu.default=sx});var ih=x(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var pt=F(),Pi=re(),cx={message:o(({params:{min:e,max:t}})=>t===void 0?(0,pt.str)`must contain at least ${e} valid item(s)`:(0,pt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,"message"),params:o(({params:{min:e,max:t}})=>t===void 0?(0,pt._)`{minContains: ${e}}`:(0,pt._)`{minContains: ${e}, maxContains: ${t}}`,"params")},ux={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cx,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,s,c,{minContains:d,maxContains:p}=n;i.opts.next?(s=d===void 0?1:d,c=p):s=1;let l=t.const("len",(0,pt._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,Pi.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,Pi.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Pi.alwaysValidSchema)(i,r)){let S=(0,pt._)`${l} >= ${s}`;c!==void 0&&(S=(0,pt._)`${S} && ${l} <= ${c}`),e.pass(S);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?y(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,pt._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let S=t.name("_valid"),w=t.let("count",0);y(S,()=>t.if(S,()=>_(w)))}o(h,"validateItemsWithCount");function y(S,w){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Pi.Type.Num,compositeRule:!0},S),w()})}o(y,"validateItems");function _(S){t.code((0,pt._)`${S}++`),c===void 0?t.if((0,pt._)`${S} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,pt._)`${S} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,pt._)`${S} >= ${s}`,()=>t.assign(m,!0)))}o(_,"checkLimits")}};ed.default=ux});var uh=x(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateSchemaDeps=Tt.validatePropertyDeps=Tt.error=void 0;var td=F(),dx=re(),Jo=dt();Tt.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,td.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,td._)`{property: ${e},
30
30
  missingProperty: ${n},
31
31
  depsCount: ${t},
32
- deps: ${r}}`,"params")};var OA={keyword:"dependencies",type:"object",schemaType:"object",error:Nt.error,code(e){let[t,r]=UA(e);Af(e,t),kf(e,r)}};function UA({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}o(UA,"splitDependencies");function Af(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let u=t[s];if(u.length===0)continue;let d=(0,ta.propertyInData)(r,n,s,a.opts.ownProperties);e.setParams({property:s,depsCount:u.length,deps:u.join(", ")}),a.allErrors?r.if(d,()=>{for(let p of u)(0,ta.checkReportMissingProp)(e,p)}):(r.if((0,yd._)`${d} && (${(0,ta.checkMissingProp)(e,u,i)})`),(0,ta.reportMissingProp)(e,i),r.else())}}o(Af,"validatePropertyDeps");Nt.validatePropertyDeps=Af;function kf(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let u in t)(0,PA.alwaysValidSchema)(i,t[u])||(r.if((0,ta.propertyInData)(r,n,u,i.opts.ownProperties),()=>{let d=e.subschema({keyword:a,schemaProp:u},s);e.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),e.ok(s))}o(kf,"validateSchemaDeps");Nt.validateSchemaDeps=kf;Nt.default=OA});var Pf=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var xf=Z(),NA=oe(),zA={message:"property name must be valid",params:o(({params:e})=>(0,xf._)`{propertyName: ${e.propertyName}}`,"params")},$A={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zA,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,NA.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,xf.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};wd.default=$A});var vd=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Mi=mt(),Ct=Z(),DA=Xt(),qi=oe(),MA={message:"must NOT have additional properties",params:o(({params:e})=>(0,Ct._)`{additionalProperty: ${e.additionalProperty}}`,"params")},qA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:MA,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:u,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,qi.alwaysValidSchema)(s,r))return;let p=(0,Mi.allSchemaProperties)(n.properties),l=(0,Mi.allSchemaProperties)(n.patternProperties);m(),e.ok((0,Ct._)`${i} === ${DA.default.errors}`);function m(){t.forIn("key",a,S=>{!p.length&&!l.length?w(S):t.if(f(S),()=>w(S))})}o(m,"checkAdditionalProperties");function f(S){let v;if(p.length>8){let R=(0,qi.schemaRefOrVal)(s,n.properties,"properties");v=(0,Mi.isOwnProperty)(t,R,S)}else p.length?v=(0,Ct.or)(...p.map(R=>(0,Ct._)`${S} === ${R}`)):v=Ct.nil;return l.length&&(v=(0,Ct.or)(v,...l.map(R=>(0,Ct._)`${(0,Mi.usePattern)(e,R)}.test(${S})`))),(0,Ct.not)(v)}o(f,"isAdditional");function _(S){t.code((0,Ct._)`delete ${a}[${S}]`)}o(_,"deleteAdditional");function w(S){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){_(S);return}if(r===!1){e.setParams({additionalProperty:S}),e.error(),u||t.break();return}if(typeof r=="object"&&!(0,qi.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(y(S,v,!1),t.if((0,Ct.not)(v),()=>{e.reset(),_(S)})):(y(S,v),u||t.if((0,Ct.not)(v),()=>t.break()))}}o(w,"additionalPropertyCode");function y(S,v,R){let b={keyword:"additionalProperties",dataProp:S,dataPropType:qi.Type.Str};R===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,v)}o(y,"applyAdditionalSchema")}};Sd.default=qA});var Nf=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var LA=jo(),Of=mt(),Rd=oe(),Uf=vd(),jA={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Uf.default.code(new LA.KeywordCxt(i,Uf.default,"additionalProperties"));let s=(0,Of.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Rd.mergeEvaluated.props(t,(0,Rd.toHash)(s),i.props));let u=s.filter(m=>!(0,Rd.alwaysValidSchema)(i,r[m]));if(u.length===0)return;let d=t.name("valid");for(let m of u)p(m)?l(m):(t.if((0,Of.propertyInData)(t,a,m,i.opts.ownProperties)),l(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};bd.default=jA});var Mf=A(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var zf=mt(),Li=Z(),$f=oe(),Df=oe(),HA={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:s}=i,u=(0,zf.allSchemaProperties)(r),d=u.filter(y=>(0,$f.alwaysValidSchema)(i,r[y]));if(u.length===0||d.length===u.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof Li.Name)&&(i.props=(0,Df.evaluatedPropsToName)(t,i.props));let{props:m}=i;f();function f(){for(let y of u)p&&_(y),i.allErrors?w(y):(t.var(l,!0),w(y),t.if(l))}o(f,"validatePatternProperties");function _(y){for(let S in p)new RegExp(y).test(S)&&(0,$f.checkStrictMode)(i,`property ${S} matches pattern ${y} (use allowMatchingProperties)`)}o(_,"checkMatchingProperties");function w(y){t.forIn("key",n,S=>{t.if((0,Li._)`${(0,zf.usePattern)(e,y)}.test(${S})`,()=>{let v=d.includes(y);v||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:S,dataPropType:Df.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,Li._)`${m}[${S}]`,!0):!v&&!i.allErrors&&t.if((0,Li.not)(l),()=>t.break())})})}o(w,"validateProperties")}};Cd.default=HA});var qf=A(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var GA=oe(),BA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,GA.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Id.default=BA});var Lf=A(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var FA=mt(),VA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:FA.validateUnion,error:{message:"must match a schema in anyOf"}};Td.default=VA});var jf=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var ji=Z(),KA=oe(),ZA={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,ji._)`{passingSchemas: ${e.passing}}`,"params")},WA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ZA,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),u=t.let("passing",null),d=t.name("_valid");e.setParams({passing:u}),t.block(p),e.result(s,()=>e.reset(),()=>e.error(!0));function p(){i.forEach((l,m)=>{let f;(0,KA.alwaysValidSchema)(a,l)?t.var(d,!0):f=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,ji._)`${d} && ${s}`).assign(s,!1).assign(u,(0,ji._)`[${u}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(u,m),f&&e.mergeEvaluated(f,ji.Name)})})}o(p,"validateOneOf")}};Ad.default=WA});var Hf=A(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var JA=oe(),YA={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,s)=>{if((0,JA.alwaysValidSchema)(n,i))return;let u=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(u)})}};kd.default=YA});var Ff=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Hi=Z(),Bf=oe(),XA={message:o(({params:e})=>(0,Hi.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,Hi._)`{failingKeyword: ${e.ifClause}}`,"params")},QA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:XA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Bf.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=Gf(n,"then"),i=Gf(n,"else");if(!a&&!i)return;let s=t.let("valid",!0),u=t.name("_valid");if(d(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(u,p("then",l),p("else",l))}else a?t.if(u,p("then")):t.if((0,Hi.not)(u),p("else"));e.pass(s,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(l)}o(d,"validateIf");function p(l,m){return()=>{let f=e.subschema({keyword:l},u);t.assign(s,u),e.mergeValidEvaluated(f,s),m?t.assign(m,(0,Hi._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function Gf(e,t){let r=e.schema[t];return r!==void 0&&!(0,Bf.alwaysValidSchema)(e,r)}o(Gf,"hasSchema");Ed.default=QA});var Vf=A(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var ek=oe(),tk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,ek.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};xd.default=tk});var Kf=A(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var rk=md(),nk=bf(),ok=hd(),ak=If(),ik=Tf(),sk=Ef(),ck=Pf(),uk=vd(),dk=Nf(),lk=Mf(),pk=qf(),mk=Lf(),hk=jf(),fk=Hf(),gk=Ff(),_k=Vf();function yk(e=!1){let t=[pk.default,mk.default,hk.default,fk.default,gk.default,_k.default,ck.default,uk.default,sk.default,dk.default,lk.default];return e?t.push(nk.default,ak.default):t.push(rk.default,ok.default),t.push(ik.default),t}o(yk,"getApplicator");Pd.default=yk});var Zf=A(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var be=Z(),wk={message:o(({schemaCode:e})=>(0,be.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,be._)`{format: ${e}}`,"params")},Sk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:wk,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:u}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=u;if(!d.validateFormats)return;a?f():_();function f(){let w=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),y=r.const("fDef",(0,be._)`${w}[${s}]`),S=r.let("fType"),v=r.let("format");r.if((0,be._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(S,(0,be._)`${y}.type || "string"`).assign(v,(0,be._)`${y}.validate`),()=>r.assign(S,(0,be._)`"string"`).assign(v,y)),e.fail$data((0,be.or)(R(),b()));function R(){return d.strictSchema===!1?be.nil:(0,be._)`${s} && !${v}`}o(R,"unknownFmt");function b(){let q=l.$async?(0,be._)`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,be._)`${v}(${n})`,L=(0,be._)`(typeof ${v} == "function" ? ${q} : ${v}.test(${n}))`;return(0,be._)`${v} && ${v} !== true && ${S} === ${t} && !${L}`}o(b,"invalidFmt")}o(f,"validate$DataFormat");function _(){let w=m.formats[i];if(!w){R();return}if(w===!0)return;let[y,S,v]=b(w);y===t&&e.pass(q());function R(){if(d.strictSchema===!1){m.logger.warn(L());return}throw new Error(L());function L(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(R,"unknownFormat");function b(L){let je=L instanceof RegExp?(0,be.regexpCode)(L):d.code.formats?(0,be._)`${d.code.formats}${(0,be.getProperty)(i)}`:void 0,ut=r.scopeValue("formats",{key:i,ref:L,code:je});return typeof L=="object"&&!(L instanceof RegExp)?[L.type||"string",L.validate,(0,be._)`${ut}.validate`]:["string",L,ut]}o(b,"getFormat");function q(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!l.$async)throw new Error("async format in sync schema");return(0,be._)`await ${v}(${n})`}return typeof S=="function"?(0,be._)`${v}(${n})`:(0,be._)`${v}.test(${n})`}o(q,"validCondition")}o(_,"validateFormat")}};Od.default=Sk});var Wf=A(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var vk=Zf(),Rk=[vk.default];Ud.default=Rk});var Jf=A(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.contentVocabulary=On.metadataVocabulary=void 0;On.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];On.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Xf=A(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var bk=of(),Ck=wf(),Ik=Kf(),Tk=Wf(),Yf=Jf(),Ak=[bk.default,Ck.default,(0,Ik.default)(),Tk.default,Yf.metadataVocabulary,Yf.contentVocabulary];Nd.default=Ak});var eg=A(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.DiscrError=void 0;var Qf;(function(e){e.Tag="tag",e.Mapping="mapping"})(Qf||(Gi.DiscrError=Qf={}))});var rg=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Un=Z(),zd=eg(),tg=Ci(),kk=Ho(),Ek=oe(),xk={message:o(({params:{discrError:e,tagName:t}})=>e===zd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,Un._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},Pk={keyword:"discriminator",type:"object",schemaType:"object",error:xk,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:s}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let u=n.propertyName;if(typeof u!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),p=t.const("tag",(0,Un._)`${r}${(0,Un.getProperty)(u)}`);t.if((0,Un._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:zd.DiscrError.Tag,tag:p,tagName:u})),e.ok(d);function l(){let _=f();t.if(!1);for(let w in _)t.elseIf((0,Un._)`${p} === ${w}`),t.assign(d,m(_[w]));t.else(),e.error(!1,{discrError:zd.DiscrError.Mapping,tag:p,tagName:u}),t.endIf()}o(l,"validateMapping");function m(_){let w=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:_},w);return e.mergeEvaluated(y,Un.Name),w}o(m,"applyTagSchema");function f(){var _;let w={},y=v(a),S=!0;for(let q=0;q<s.length;q++){let L=s[q];if(L?.$ref&&!(0,Ek.schemaHasRulesButRef)(L,i.self.RULES)){let ut=L.$ref;if(L=tg.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,ut),L instanceof tg.SchemaEnv&&(L=L.schema),L===void 0)throw new kk.default(i.opts.uriResolver,i.baseId,ut)}let je=(_=L?.properties)===null||_===void 0?void 0:_[u];if(typeof je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${u}"`);S=S&&(y||v(L)),R(je,q)}if(!S)throw new Error(`discriminator: "${u}" must be required`);return w;function v({required:q}){return Array.isArray(q)&&q.includes(u)}function R(q,L){if(q.const)b(q.const,L);else if(q.enum)for(let je of q.enum)b(je,L);else throw new Error(`discriminator: "properties/${u}" must have "const" or "enum"`)}function b(q,L){if(typeof q!="string"||q in w)throw new Error(`discriminator: "${u}" values must be unique strings`);w[q]=L}}o(f,"getMapping")}};$d.default=Pk});var ng=A((IB,Ok)=>{Ok.exports={$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 Md=A((me,Dd)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv=void 0;var Uk=Xh(),Nk=Xf(),zk=rg(),og=ng(),$k=["/properties"],Bi="http://json-schema.org/draft-07/schema",Nn=class extends Uk.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),Nk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(zk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(og,$k):og;this.addMetaSchema(t,Bi,!1),this.refs["http://json-schema.org/schema"]=Bi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bi)?Bi:void 0)}};me.Ajv=Nn;Dd.exports=me=Nn;Dd.exports.Ajv=Nn;Object.defineProperty(me,"__esModule",{value:!0});me.default=Nn;var Dk=jo();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:o(function(){return Dk.KeywordCxt},"get")});var zn=Z();Object.defineProperty(me,"_",{enumerable:!0,get:o(function(){return zn._},"get")});Object.defineProperty(me,"str",{enumerable:!0,get:o(function(){return zn.str},"get")});Object.defineProperty(me,"stringify",{enumerable:!0,get:o(function(){return zn.stringify},"get")});Object.defineProperty(me,"nil",{enumerable:!0,get:o(function(){return zn.nil},"get")});Object.defineProperty(me,"Name",{enumerable:!0,get:o(function(){return zn.Name},"get")});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:o(function(){return zn.CodeGen},"get")});var Mk=Ri();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:o(function(){return Mk.default},"get")});var qk=Ho();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:o(function(){return qk.default},"get")})});var pg=A($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.formatNames=$t.fastFormats=$t.fullFormats=void 0;function zt(e,t){return{validate:e,compare:t}}o(zt,"fmtDef");$t.fullFormats={date:zt(cg,Hd),time:zt(Ld(!0),Gd),"date-time":zt(ag(!0),dg),"iso-time":zt(Ld(),ug),"iso-date-time":zt(ag(),lg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Fk,"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:Xk,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:Vk,int32:{type:"number",validate:Wk},int64:{type:"number",validate:Jk},float:{type:"number",validate:sg},double:{type:"number",validate:sg},password:!0,binary:!0};$t.fastFormats={...$t.fullFormats,date:zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Hd),time:zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Gd),"date-time":zt(/^\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,dg),"iso-time":zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ug),"iso-date-time":zt(/^\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,lg),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$t.formatNames=Object.keys($t.fullFormats);function Lk(e){return e%4===0&&(e%100!==0||e%400===0)}o(Lk,"isLeapYear");var jk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Hk=[0,31,28,31,30,31,30,31,31,30,31,30,31];function cg(e){let t=jk.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n===2&&Lk(r)?29:Hk[n])}o(cg,"date");function Hd(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Hd,"compareDate");var qd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ld(e){return o(function(r){let n=qd.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],u=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!u)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,f=a-p*d-(m<0?1:0);return(f===23||f===-1)&&(m===59||m===-1)&&s<61},"time")}o(Ld,"getTime");function Gd(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(Gd,"compareTime");function ug(e,t){if(!(e&&t))return;let r=qd.exec(e),n=qd.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(ug,"compareIsoTime");var jd=/t|\s/i;function ag(e){let t=Ld(e);return o(function(n){let a=n.split(jd);return a.length===2&&cg(a[0])&&t(a[1])},"date_time")}o(ag,"getDateTime");function dg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(dg,"compareDateTime");function lg(e,t){if(!(e&&t))return;let[r,n]=e.split(jd),[a,i]=t.split(jd),s=Hd(r,a);if(s!==void 0)return s||Gd(n,i)}o(lg,"compareIsoDateTime");var Gk=/\/|:/,Bk=/^(?:[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 Fk(e){return Gk.test(e)&&Bk.test(e)}o(Fk,"uri");var ig=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Vk(e){return ig.lastIndex=0,ig.test(e)}o(Vk,"byte");var Kk=-(2**31),Zk=2**31-1;function Wk(e){return Number.isInteger(e)&&e<=Zk&&e>=Kk}o(Wk,"validateInt32");function Jk(e){return Number.isInteger(e)}o(Jk,"validateInt64");function sg(){return!0}o(sg,"validateNumber");var Yk=/[^\\]\\Z/;function Xk(e){if(Yk.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(Xk,"regex")});var mg=A($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.formatLimitDefinition=void 0;var Qk=Md(),It=Z(),Tr=It.operators,Fi={formatMaximum:{okStr:"<=",ok:Tr.LTE,fail:Tr.GT},formatMinimum:{okStr:">=",ok:Tr.GTE,fail:Tr.LT},formatExclusiveMaximum:{okStr:"<",ok:Tr.LT,fail:Tr.GTE},formatExclusiveMinimum:{okStr:">",ok:Tr.GT,fail:Tr.LTE}},eE={message:o(({keyword:e,schemaCode:t})=>(0,It.str)`should be ${Fi[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,It._)`{comparison: ${Fi[e].okStr}, limit: ${t}}`,"params")};$n.formatLimitDefinition={keyword:Object.keys(Fi),type:"string",schemaType:"string",$data:!0,error:eE,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:i}=e,{opts:s,self:u}=i;if(!s.validateFormats)return;let d=new Qk.KeywordCxt(i,u.RULES.all.format.definition,"format");d.$data?p():l();function p(){let f=t.scopeValue("formats",{ref:u.formats,code:s.code.formats}),_=t.const("fmt",(0,It._)`${f}[${d.schemaCode}]`);e.fail$data((0,It.or)((0,It._)`typeof ${_} != "object"`,(0,It._)`${_} instanceof RegExp`,(0,It._)`typeof ${_}.compare != "function"`,m(_)))}o(p,"validate$DataFormat");function l(){let f=d.schema,_=u.formats[f];if(!_||_===!0)return;if(typeof _!="object"||_ instanceof RegExp||typeof _.compare!="function")throw new Error(`"${a}": format "${f}" does not define "compare" function`);let w=t.scopeValue("formats",{key:f,ref:_,code:s.code.formats?(0,It._)`${s.code.formats}${(0,It.getProperty)(f)}`:void 0});e.fail$data(m(w))}o(l,"validateFormat");function m(f){return(0,It._)`${f}.compare(${r}, ${n}) ${Fi[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var tE=o(e=>(e.addKeyword($n.formatLimitDefinition),e),"formatLimitPlugin");$n.default=tE});var _g=A((ra,gg)=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var Dn=pg(),rE=mg(),Bd=Z(),hg=new Bd.Name("fullFormats"),nE=new Bd.Name("fastFormats"),Fd=o((e,t={keywords:!0})=>{if(Array.isArray(t))return fg(e,t,Dn.fullFormats,hg),e;let[r,n]=t.mode==="fast"?[Dn.fastFormats,nE]:[Dn.fullFormats,hg],a=t.formats||Dn.formatNames;return fg(e,a,r,n),t.keywords&&(0,rE.default)(e),e},"formatsPlugin");Fd.get=(e,t="full")=>{let n=(t==="fast"?Dn.fastFormats:Dn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function fg(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,Bd._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(fg,"addFormats");gg.exports=ra=Fd;Object.defineProperty(ra,"__esModule",{value:!0});ra.default=Fd});Bv();function lr(e){return!!e._zod}o(lr,"isZ4Schema");function Ke(e,t){return lr(e)?yc(e,t):e.safeParse(t)}o(Ke,"safeParse");function gn(e){if(!e)return;let t;if(lr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(gn,"getObjectShape");function fm(e){if(lr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let 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]}let n=e.value;if(n!==void 0)return n}o(fm,"getLiteralValue");ae();var mr="2025-11-25",gm="2025-03-26",hr=[mr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fr="io.modelcontextprotocol/related-task",Ja="2.0",ke=pm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),_m=fe([h(),re().int()]),ym=h(),GM=Ae({ttl:re().optional(),pollInterval:re().optional()}),Kv=I({ttl:re().optional()}),Zv=I({taskId:h()}),Rc=Ae({progressToken:_m.optional(),[fr]:Zv.optional()}),st=I({_meta:Rc.optional()}),_o=st.extend({task:Kv.optional()}),wm=o(e=>_o.safeParse(e).success,"isTaskAugmentedRequestParams"),xe=I({method:h(),params:st.loose().optional()}),dt=I({_meta:Rc.optional()}),lt=I({method:h(),params:dt.loose().optional()}),Pe=Ae({_meta:Rc.optional()}),Ya=fe([h(),re().int()]),Sm=I({jsonrpc:O(Ja),id:Ya,...xe.shape}).strict(),xt=o(e=>Sm.safeParse(e).success,"isJSONRPCRequest"),vm=I({jsonrpc:O(Ja),...lt.shape}).strict(),Rm=o(e=>vm.safeParse(e).success,"isJSONRPCNotification"),bc=I({jsonrpc:O(Ja),id:Ya,result:Pe}).strict(),St=o(e=>bc.safeParse(e).success,"isJSONRPCResultResponse");var P;(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"})(P||(P={}));var Cc=I({jsonrpc:O(Ja),id:Ya.optional(),error:I({code:re().int(),message:h(),data:Re().optional()})}).strict();var yn=o(e=>Cc.safeParse(e).success,"isJSONRPCErrorResponse");var Mr=fe([Sm,vm,bc,Cc]),BM=fe([bc,Cc]),Kt=Pe.strict(),Wv=dt.extend({requestId:Ya.optional(),reason:h().optional()}),Xa=lt.extend({method:O("notifications/cancelled"),params:Wv}),Jv=I({src:h(),mimeType:h().optional(),sizes:C(h()).optional(),theme:it(["light","dark"]).optional()}),yo=I({icons:C(Jv).optional()}),_n=I({name:h(),title:h().optional()}),wn=_n.extend({..._n.shape,...yo.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),Yv=Sc(I({applyDefaults:ce().optional()}),le(h(),Re())),Xv=vc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Sc(I({form:Yv.optional(),url:ke.optional()}),le(h(),Re()).optional())),Qv=Ae({list:ke.optional(),cancel:ke.optional(),requests:Ae({sampling:Ae({createMessage:ke.optional()}).optional(),elicitation:Ae({create:ke.optional()}).optional()}).optional()}),eR=Ae({list:ke.optional(),cancel:ke.optional(),requests:Ae({tools:Ae({call:ke.optional()}).optional()}).optional()}),tR=I({experimental:le(h(),ke).optional(),sampling:I({context:ke.optional(),tools:ke.optional()}).optional(),elicitation:Xv.optional(),roots:I({listChanged:ce().optional()}).optional(),tasks:Qv.optional(),extensions:le(h(),ke).optional()}),rR=st.extend({protocolVersion:h(),capabilities:tR,clientInfo:wn}),Qa=xe.extend({method:O("initialize"),params:rR}),Ic=o(e=>Qa.safeParse(e).success,"isInitializeRequest"),nR=I({experimental:le(h(),ke).optional(),logging:ke.optional(),completions:ke.optional(),prompts:I({listChanged:ce().optional()}).optional(),resources:I({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:I({listChanged:ce().optional()}).optional(),tasks:eR.optional(),extensions:le(h(),ke).optional()}),Tc=Pe.extend({protocolVersion:h(),capabilities:nR,serverInfo:wn,instructions:h().optional()}),ei=lt.extend({method:O("notifications/initialized"),params:dt.optional()}),bm=o(e=>ei.safeParse(e).success,"isInitializedNotification"),ti=xe.extend({method:O("ping"),params:st.optional()}),oR=I({progress:re(),total:we(re()),message:we(h())}),aR=I({...dt.shape,...oR.shape,progressToken:_m}),ri=lt.extend({method:O("notifications/progress"),params:aR}),iR=st.extend({cursor:ym.optional()}),wo=xe.extend({params:iR.optional()}),So=Pe.extend({nextCursor:ym.optional()}),sR=it(["working","input_required","completed","failed","cancelled"]),vo=I({taskId:h(),status:sR,ttl:fe([re(),dm()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:we(re()),statusMessage:we(h())}),Zt=Pe.extend({task:vo}),cR=dt.merge(vo),Ro=lt.extend({method:O("notifications/tasks/status"),params:cR}),ni=xe.extend({method:O("tasks/get"),params:st.extend({taskId:h()})}),oi=Pe.merge(vo),ai=xe.extend({method:O("tasks/result"),params:st.extend({taskId:h()})}),FM=Pe.loose(),ii=wo.extend({method:O("tasks/list")}),si=So.extend({tasks:C(vo)}),ci=xe.extend({method:O("tasks/cancel"),params:st.extend({taskId:h()})}),Cm=Pe.merge(vo),Im=I({uri:h(),mimeType:we(h()),_meta:le(h(),Re()).optional()}),Tm=Im.extend({text:h()}),Ac=h().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Am=Im.extend({blob:Ac}),bo=it(["user","assistant"]),Sn=I({audience:C(bo).optional(),priority:re().min(0).max(1).optional(),lastModified:cm.datetime({offset:!0}).optional()}),km=I({..._n.shape,...yo.shape,uri:h(),description:we(h()),mimeType:we(h()),size:we(re()),annotations:Sn.optional(),_meta:we(Ae({}))}),uR=I({..._n.shape,...yo.shape,uriTemplate:h(),description:we(h()),mimeType:we(h()),annotations:Sn.optional(),_meta:we(Ae({}))}),kc=wo.extend({method:O("resources/list")}),Ec=So.extend({resources:C(km)}),dR=wo.extend({method:O("resources/templates/list")}),xc=So.extend({resourceTemplates:C(uR)}),Pc=st.extend({uri:h()}),lR=Pc,Oc=xe.extend({method:O("resources/read"),params:lR}),Uc=Pe.extend({contents:C(fe([Tm,Am]))}),Nc=lt.extend({method:O("notifications/resources/list_changed"),params:dt.optional()}),pR=Pc,mR=xe.extend({method:O("resources/subscribe"),params:pR}),hR=Pc,fR=xe.extend({method:O("resources/unsubscribe"),params:hR}),gR=dt.extend({uri:h()}),_R=lt.extend({method:O("notifications/resources/updated"),params:gR}),yR=I({name:h(),description:we(h()),required:we(ce())}),wR=I({..._n.shape,...yo.shape,description:we(h()),arguments:we(C(yR)),_meta:we(Ae({}))}),zc=wo.extend({method:O("prompts/list")}),$c=So.extend({prompts:C(wR)}),SR=st.extend({name:h(),arguments:le(h(),h()).optional()}),Dc=xe.extend({method:O("prompts/get"),params:SR}),Mc=I({type:O("text"),text:h(),annotations:Sn.optional(),_meta:le(h(),Re()).optional()}),qc=I({type:O("image"),data:Ac,mimeType:h(),annotations:Sn.optional(),_meta:le(h(),Re()).optional()}),Lc=I({type:O("audio"),data:Ac,mimeType:h(),annotations:Sn.optional(),_meta:le(h(),Re()).optional()}),vR=I({type:O("tool_use"),name:h(),id:h(),input:le(h(),Re()),_meta:le(h(),Re()).optional()}),RR=I({type:O("resource"),resource:fe([Tm,Am]),annotations:Sn.optional(),_meta:le(h(),Re()).optional()}),bR=km.extend({type:O("resource_link")}),jc=fe([Mc,qc,Lc,bR,RR]),CR=I({role:bo,content:jc}),Hc=Pe.extend({description:h().optional(),messages:C(CR)}),Gc=lt.extend({method:O("notifications/prompts/list_changed"),params:dt.optional()}),IR=I({title:h().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),TR=I({taskSupport:it(["required","optional","forbidden"]).optional()}),Em=I({..._n.shape,...yo.shape,description:h().optional(),inputSchema:I({type:O("object"),properties:le(h(),ke).optional(),required:C(h()).optional()}).catchall(Re()),outputSchema:I({type:O("object"),properties:le(h(),ke).optional(),required:C(h()).optional()}).catchall(Re()).optional(),annotations:IR.optional(),execution:TR.optional(),_meta:le(h(),Re()).optional()}),Bc=wo.extend({method:O("tools/list")}),Fc=So.extend({tools:C(Em)}),gr=Pe.extend({content:C(jc).default([]),structuredContent:le(h(),Re()).optional(),isError:ce().optional()}),VM=gr.or(Pe.extend({toolResult:Re()})),AR=_o.extend({name:h(),arguments:le(h(),Re()).optional()}),Co=xe.extend({method:O("tools/call"),params:AR}),Vc=lt.extend({method:O("notifications/tools/list_changed"),params:dt.optional()}),xm=I({autoRefresh:ce().default(!0),debounceMs:re().int().nonnegative().default(300)}),Io=it(["debug","info","notice","warning","error","critical","alert","emergency"]),kR=st.extend({level:Io}),Kc=xe.extend({method:O("logging/setLevel"),params:kR}),ER=dt.extend({level:Io,logger:h().optional(),data:Re()}),xR=lt.extend({method:O("notifications/message"),params:ER}),PR=I({name:h().optional()}),OR=I({hints:C(PR).optional(),costPriority:re().min(0).max(1).optional(),speedPriority:re().min(0).max(1).optional(),intelligencePriority:re().min(0).max(1).optional()}),UR=I({mode:it(["auto","required","none"]).optional()}),NR=I({type:O("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:C(jc).default([]),structuredContent:I({}).loose().optional(),isError:ce().optional(),_meta:le(h(),Re()).optional()}),zR=wc("type",[Mc,qc,Lc]),Wa=wc("type",[Mc,qc,Lc,vR,NR]),$R=I({role:bo,content:fe([Wa,C(Wa)]),_meta:le(h(),Re()).optional()}),DR=_o.extend({messages:C($R),modelPreferences:OR.optional(),systemPrompt:h().optional(),includeContext:it(["none","thisServer","allServers"]).optional(),temperature:re().optional(),maxTokens:re().int(),stopSequences:C(h()).optional(),metadata:ke.optional(),tools:C(Em).optional(),toolChoice:UR.optional()}),Zc=xe.extend({method:O("sampling/createMessage"),params:DR}),qr=Pe.extend({model:h(),stopReason:we(it(["endTurn","stopSequence","maxTokens"]).or(h())),role:bo,content:zR}),To=Pe.extend({model:h(),stopReason:we(it(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:bo,content:fe([Wa,C(Wa)])}),MR=I({type:O("boolean"),title:h().optional(),description:h().optional(),default:ce().optional()}),qR=I({type:O("string"),title:h().optional(),description:h().optional(),minLength:re().optional(),maxLength:re().optional(),format:it(["email","uri","date","date-time"]).optional(),default:h().optional()}),LR=I({type:it(["number","integer"]),title:h().optional(),description:h().optional(),minimum:re().optional(),maximum:re().optional(),default:re().optional()}),jR=I({type:O("string"),title:h().optional(),description:h().optional(),enum:C(h()),default:h().optional()}),HR=I({type:O("string"),title:h().optional(),description:h().optional(),oneOf:C(I({const:h(),title:h()})),default:h().optional()}),GR=I({type:O("string"),title:h().optional(),description:h().optional(),enum:C(h()),enumNames:C(h()).optional(),default:h().optional()}),BR=fe([jR,HR]),FR=I({type:O("array"),title:h().optional(),description:h().optional(),minItems:re().optional(),maxItems:re().optional(),items:I({type:O("string"),enum:C(h())}),default:C(h()).optional()}),VR=I({type:O("array"),title:h().optional(),description:h().optional(),minItems:re().optional(),maxItems:re().optional(),items:I({anyOf:C(I({const:h(),title:h()}))}),default:C(h()).optional()}),KR=fe([FR,VR]),ZR=fe([GR,BR,KR]),WR=fe([ZR,MR,qR,LR]),JR=_o.extend({mode:O("form").optional(),message:h(),requestedSchema:I({type:O("object"),properties:le(h(),WR),required:C(h()).optional()})}),YR=_o.extend({mode:O("url"),message:h(),elicitationId:h(),url:h().url()}),XR=fe([JR,YR]),Wc=xe.extend({method:O("elicitation/create"),params:XR}),QR=dt.extend({elicitationId:h()}),eb=lt.extend({method:O("notifications/elicitation/complete"),params:QR}),_r=Pe.extend({action:it(["accept","decline","cancel"]),content:vc(e=>e===null?void 0:e,le(h(),fe([h(),re(),ce(),C(h())])).optional())}),tb=I({type:O("ref/resource"),uri:h()});var rb=I({type:O("ref/prompt"),name:h()}),nb=st.extend({ref:fe([rb,tb]),argument:I({name:h(),value:h()}),context:I({arguments:le(h(),h()).optional()}).optional()}),ob=xe.extend({method:O("completion/complete"),params:nb});var Jc=Pe.extend({completion:Ae({values:C(h()).max(100),total:we(re().int()),hasMore:we(ce())})}),ab=I({uri:h().startsWith("file://"),name:h().optional(),_meta:le(h(),Re()).optional()}),ib=xe.extend({method:O("roots/list"),params:st.optional()}),Yc=Pe.extend({roots:C(ab)}),sb=lt.extend({method:O("notifications/roots/list_changed"),params:dt.optional()}),KM=fe([ti,Qa,ob,Kc,Dc,zc,kc,dR,Oc,mR,fR,Co,Bc,ni,ai,ii,ci]),ZM=fe([Xa,ri,ei,sb,Ro]),WM=fe([Kt,qr,To,_r,Yc,oi,si,Zt]),JM=fe([ti,Zc,Wc,ib,ni,ai,ii,ci]),YM=fe([Xa,ri,xR,_R,Nc,Vc,Gc,Ro,eb]),XM=fe([Kt,Tc,Jc,Hc,$c,Ec,xc,Uc,gr,Fc,oi,si,Zt]),k=class e extends Error{static{o(this,"McpError")}constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===P.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new pr(a.elicitations,r)}return new e(t,r,n)}},pr=class extends k{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(P.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function yr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(yr,"isTerminal");var cb=Symbol("Let zodToJsonSchema decide on which parser to use");var Wq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Xc(e){let r=gn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fm(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(Xc,"getMethodLiteral");function Qc(e,t){let r=Ke(e,t);if(!r.success)throw r.error;return r.data}o(Qc,"parseWithCompat");var hb=6e4,vn=class{static{o(this,"Protocol")}constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xa,r=>{this._oncancel(r)}),this.setNotificationHandler(ri,r=>{this._onprogress(r)}),this.setRequestHandler(ti,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ni,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new k(P.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(ai,async(r,n)=>{let a=o(async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let u;for(;u=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(u.type==="response"||u.type==="error"){let d=u.message,p=d.id,l=this._requestResolvers.get(p);if(l)if(this._requestResolvers.delete(p),u.type==="response")l(d);else{let m=d,f=new k(m.error.code,m.error.message,m.error.data);l(f)}else{let m=u.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${p}`))}continue}await this._transport?.send(u.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new k(P.InvalidParams,`Task not found: ${i}`);if(!yr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(yr(s.status)){let u=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...u,_meta:{...u._meta,[fr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(ii,async(r,n)=>{try{let{tasks:a,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:a,nextCursor:i,_meta:{}}}catch(a){throw new k(P.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(ci,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new k(P.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(a.status))throw new k(P.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new k(P.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof k?a:new k(P.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,a,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:a})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),k.fromError(P.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let a=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{a?.(i,s),St(i)||yn(i)?this._onresponse(i):xt(i)?this._onrequest(i,s):Rm(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=k.fromError(P.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,a=this._transport,i=t.params?._meta?.[fr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:P.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},a?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):a?.send(l).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let u=wm(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,p={signal:s.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async l=>{if(s.signal.aborted)return;let m={relatedRequestId:t.id};i&&(m.relatedTask={taskId:i}),await this.notification(l,m)},"sendNotification"),sendRequest:o(async(l,m,f)=>{if(s.signal.aborted)throw new k(P.ConnectionClosed,"Request was cancelled");let _={...f,relatedRequestId:t.id};i&&!_.relatedTask&&(_.relatedTask={taskId:i});let w=_.relatedTask?.taskId??i;return w&&d&&await d.updateTaskStatus(w,"input_required"),await this.request(l,m,_)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{u&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:P.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),i=this._progressHandlers.get(a);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(a),u=this._timeoutInfo.get(a);if(u&&s&&u.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(d);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),St(t))n(t);else{let s=new k(t.error.code,t.error.message,t.error.data);n(s)}return}let a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(St(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let u=s.task;typeof u.taskId=="string"&&(i=!0,this._taskProgressTokens.set(u.taskId,r))}}if(i||this._progressHandlers.delete(r),St(t))a(t);else{let s=k.fromError(t.error.code,t.error.message,t.error.data);a(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:a}=n??{};if(!a){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof k?s:new k(P.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Zt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new k(P.InternalError,"Task creation did not return a task");for(;;){let u=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:u},yr(u.status)){u.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:u.status==="failed"?yield{type:"error",error:new k(P.InternalError,`Task ${i} failed`)}:u.status==="cancelled"&&(yield{type:"error",error:new k(P.InternalError,`Task ${i} was cancelled`)});return}if(u.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let d=u.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,d)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof k?s:new k(P.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:u,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(R=>{l(R)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),u&&this.assertTaskCapability(t.method)}catch(R){m(R);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,_={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),_.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),u&&(_.params={..._.params,task:u}),d&&(_.params={..._.params,_meta:{..._.params?._meta||{},[fr]:d}});let w=o(R=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(R)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));let b=R instanceof k?R:new k(P.RequestTimeout,String(R));l(b)},"cancel");this._responseHandlers.set(f,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return l(R);try{let b=Ke(r,R.result);b.success?p(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{w(n?.signal?.reason)});let y=n?.timeout??hb,S=o(()=>w(k.fromError(P.RequestTimeout,"Request timed out",{timeout:y})),"timeoutHandler");this._setupTimeout(f,y,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let R=o(b=>{let q=this._responseHandlers.get(f);q?q(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))},"responseResolver");this._requestResolvers.set(f,R),this._enqueueTaskMessage(v,{type:"request",message:_,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),l(b)})}else this._transport.send(_,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(R=>{this._cleanupTimeout(f),l(R)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},oi,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},si,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Cm,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let u={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[fr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:u,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let u={...t,jsonrpc:"2.0"};r?.relatedTask&&(u={...u,params:{...u.params,_meta:{...u.params?._meta||{},[fr]:r.relatedTask}}}),this._transport?.send(u,r).catch(d=>this._onerror(d))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[fr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Xc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=Qc(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Xc(t);this._notificationHandlers.set(n,a=>{let i=Qc(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&xt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new k(P.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(t);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(r.aborted){i(new k(P.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new k(P.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:o(async a=>{if(!t)throw new Error("No request provided");return await n.createTask(a,t.id,{method:t.method,params:t.params},r)},"createTask"),getTask:o(async a=>{let i=await n.getTask(a,r);if(!i)throw new k(P.InvalidParams,"Failed to retrieve task: Task not found");return i},"getTask"),storeTaskResult:o(async(a,i,s)=>{await n.storeTaskResult(a,i,s,r);let u=await n.getTask(a,r);if(u){let d=Ro.parse({method:"notifications/tasks/status",params:u});await this.notification(d),yr(u.status)&&this._cleanupTaskProgressHandler(a)}},"storeTaskResult"),getTaskResult:o(a=>n.getTaskResult(a,r),"getTaskResult"),updateTaskStatus:o(async(a,i,s)=>{let u=await n.getTask(a,r);if(!u)throw new k(P.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(yr(u.status))throw new k(P.InvalidParams,`Cannot update task "${a}" from terminal status "${u.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,i,s,r);let d=await n.getTask(a,r);if(d){let p=Ro.parse({method:"notifications/tasks/status",params:d});await this.notification(p),yr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function Pm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Pm,"isPlainObject");function ui(e,t){let r={...e};for(let n in t){let a=n,i=t[a];if(i===void 0)continue;let s=r[a];Pm(s)&&Pm(i)?r[a]={...s,...i}:r[a]=i}return r}o(ui,"mergeCapabilities");var yg=nm(Md(),1),wg=nm(_g(),1);function oE(){let e=new yg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,wg.default)(e),e}o(oE,"createDefaultAjvInstance");var Mn=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??oE()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Vi=class{static{o(this,"ExperimentalServerTasks")}constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],i=Array.isArray(a.content)?a.content:[a.content],s=i.some(l=>l.type==="tool_result"),u=t.messages.length>1?t.messages[t.messages.length-2]:void 0,d=u?Array.isArray(u.content)?u.content:[u.content]:[],p=d.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let l=new Set(d.filter(f=>f.type==="tool_use").map(f=>f.id)),m=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==m.size||![...l].every(f=>m.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},qr,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),a=t.mode??"form";switch(a){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=a==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},_r,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Ki(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}o(Ki,"assertToolsCallTaskCapability");function Zi(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}o(Zi,"assertClientRequestTaskCapability");var Wi=class extends vn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Io.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Mn,this.setRequestHandler(Qa,n=>this._oninitialize(n)),this.setNotificationHandler(ei,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Kc,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,u=Io.safeParse(s);return u.success&&this._loggingLevels.set(i,u.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Vi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ui(this._capabilities,t)}setRequestHandler(t,r){let a=gn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(lr(a)){let u=a;i=u._zod?.def?.value??u.value}else{let u=a;i=u._def?.value??u.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let u=o(async(d,p)=>{let l=Ke(Co,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new k(P.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:m}=l.data,f=await Promise.resolve(r(d,p));if(m.task){let w=Ke(Zt,f);if(!w.success){let y=w.error instanceof Error?w.error.message:String(w.error);throw new k(P.InvalidParams,`Invalid task creation result: ${y}`)}return w.data}let _=Ke(gr,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new k(P.InvalidParams,`Invalid tools/call result: ${w}`)}return _.data},"wrappedHandler");return super.setRequestHandler(t,u)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Zi(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Ki(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:hr.includes(r)?r:mr,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"},Kt)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],i=a.some(p=>p.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,u=s?Array.isArray(s.content)?s.content:[s.content]:[],d=u.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==l.size||![...p].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},To,r):this.request({method:"sampling/createMessage",params:t},qr,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let a=t;return this.request({method:"elicitation/create",params:a},_r,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let a=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:a},_r,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let u=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!u.valid)throw new k(P.InvalidParams,`Elicitation response content does not match requested schema: ${u.errorMessage}`)}catch(s){throw s instanceof k?s:new k(P.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Yc,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ji=class{static{o(this,"WebStandardStreamableHTTPServerTransport")}constructor(t={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,a){let i={code:r,message:n};return a?.data!==void 0&&(i.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...a?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,a){if(!this._eventStore||a<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
32
+ deps: ${r}}`,"params")};var lx={keyword:"dependencies",type:"object",schemaType:"object",error:Tt.error,code(e){let[t,r]=px(e);sh(e,t),ch(e,r)}};function px({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}o(px,"splitDependencies");function sh(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let c=t[s];if(c.length===0)continue;let d=(0,Jo.propertyInData)(r,n,s,a.opts.ownProperties);e.setParams({property:s,depsCount:c.length,deps:c.join(", ")}),a.allErrors?r.if(d,()=>{for(let p of c)(0,Jo.checkReportMissingProp)(e,p)}):(r.if((0,td._)`${d} && (${(0,Jo.checkMissingProp)(e,c,i)})`),(0,Jo.reportMissingProp)(e,i),r.else())}}o(sh,"validatePropertyDeps");Tt.validatePropertyDeps=sh;function ch(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,dx.alwaysValidSchema)(i,t[c])||(r.if((0,Jo.propertyInData)(r,n,c,i.opts.ownProperties),()=>{let d=e.subschema({keyword:a,schemaProp:c},s);e.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),e.ok(s))}o(ch,"validateSchemaDeps");Tt.validateSchemaDeps=ch;Tt.default=lx});var lh=x(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var dh=F(),mx=re(),fx={message:"property name must be valid",params:o(({params:e})=>(0,dh._)`{propertyName: ${e.propertyName}}`,"params")},hx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fx,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,mx.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,dh.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};rd.default=hx});var od=x(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var xi=dt(),bt=F(),gx=Ft(),Ai=re(),yx={message:"must NOT have additional properties",params:o(({params:e})=>(0,bt._)`{additionalProperty: ${e.additionalProperty}}`,"params")},Sx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yx,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,Ai.alwaysValidSchema)(s,r))return;let p=(0,xi.allSchemaProperties)(n.properties),l=(0,xi.allSchemaProperties)(n.patternProperties);m(),e.ok((0,bt._)`${i} === ${gx.default.errors}`);function m(){t.forIn("key",a,w=>{!p.length&&!l.length?_(w):t.if(h(w),()=>_(w))})}o(m,"checkAdditionalProperties");function h(w){let v;if(p.length>8){let b=(0,Ai.schemaRefOrVal)(s,n.properties,"properties");v=(0,xi.isOwnProperty)(t,b,w)}else p.length?v=(0,bt.or)(...p.map(b=>(0,bt._)`${w} === ${b}`)):v=bt.nil;return l.length&&(v=(0,bt.or)(v,...l.map(b=>(0,bt._)`${(0,xi.usePattern)(e,b)}.test(${w})`))),(0,bt.not)(v)}o(h,"isAdditional");function y(w){t.code((0,bt._)`delete ${a}[${w}]`)}o(y,"deleteAdditional");function _(w){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(w);return}if(r===!1){e.setParams({additionalProperty:w}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,Ai.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(S(w,v,!1),t.if((0,bt.not)(v),()=>{e.reset(),y(w)})):(S(w,v),c||t.if((0,bt.not)(v),()=>t.break()))}}o(_,"additionalPropertyCode");function S(w,v,b){let R={keyword:"additionalProperties",dataProp:w,dataPropType:Ai.Type.Str};b===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(R,v)}o(S,"applyAdditionalSchema")}};nd.default=Sx});var fh=x(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var _x=Mo(),ph=dt(),ad=re(),mh=od(),wx={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&mh.default.code(new _x.KeywordCxt(i,mh.default,"additionalProperties"));let s=(0,ph.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=ad.mergeEvaluated.props(t,(0,ad.toHash)(s),i.props));let c=s.filter(m=>!(0,ad.alwaysValidSchema)(i,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,ph.propertyInData)(t,a,m,i.opts.ownProperties)),l(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};id.default=wx});var Sh=x(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var hh=dt(),Ti=F(),gh=re(),yh=re(),vx={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:s}=i,c=(0,hh.allSchemaProperties)(r),d=c.filter(S=>(0,gh.alwaysValidSchema)(i,r[S]));if(c.length===0||d.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof Ti.Name)&&(i.props=(0,yh.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let S of c)p&&y(S),i.allErrors?_(S):(t.var(l,!0),_(S),t.if(l))}o(h,"validatePatternProperties");function y(S){for(let w in p)new RegExp(S).test(w)&&(0,gh.checkStrictMode)(i,`property ${w} matches pattern ${S} (use allowMatchingProperties)`)}o(y,"checkMatchingProperties");function _(S){t.forIn("key",n,w=>{t.if((0,Ti._)`${(0,hh.usePattern)(e,S)}.test(${w})`,()=>{let v=d.includes(S);v||e.subschema({keyword:"patternProperties",schemaProp:S,dataProp:w,dataPropType:yh.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,Ti._)`${m}[${w}]`,!0):!v&&!i.allErrors&&t.if((0,Ti.not)(l),()=>t.break())})})}o(_,"validateProperties")}};sd.default=vx});var _h=x(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var bx=re(),Rx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,bx.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};cd.default=Rx});var wh=x(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Cx=dt(),Ix={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Cx.validateUnion,error:{message:"must match a schema in anyOf"}};ud.default=Ix});var vh=x(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var ki=F(),Px=re(),xx={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,ki._)`{passingSchemas: ${e.passing}}`,"params")},Ax={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:xx,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),c=t.let("passing",null),d=t.name("_valid");e.setParams({passing:c}),t.block(p),e.result(s,()=>e.reset(),()=>e.error(!0));function p(){i.forEach((l,m)=>{let h;(0,Px.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,ki._)`${d} && ${s}`).assign(s,!1).assign(c,(0,ki._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,ki.Name)})})}o(p,"validateOneOf")}};dd.default=Ax});var bh=x(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var Tx=re(),kx={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,s)=>{if((0,Tx.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};ld.default=kx});var Ih=x(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var Ei=F(),Ch=re(),Ex={message:o(({params:e})=>(0,Ei.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,Ei._)`{failingKeyword: ${e.ifClause}}`,"params")},Ux={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ex,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Ch.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=Rh(n,"then"),i=Rh(n,"else");if(!a&&!i)return;let s=t.let("valid",!0),c=t.name("_valid");if(d(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(c,p("then",l),p("else",l))}else a?t.if(c,p("then")):t.if((0,Ei.not)(c),p("else"));e.pass(s,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);e.mergeEvaluated(l)}o(d,"validateIf");function p(l,m){return()=>{let h=e.subschema({keyword:l},c);t.assign(s,c),e.mergeValidEvaluated(h,s),m?t.assign(m,(0,Ei._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function Rh(e,t){let r=e.schema[t];return r!==void 0&&!(0,Ch.alwaysValidSchema)(e,r)}o(Rh,"hasSchema");pd.default=Ux});var Ph=x(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Ox=re(),$x={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Ox.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};md.default=$x});var xh=x(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var zx=Ju(),Mx=nh(),qx=Yu(),Nx=ah(),jx=ih(),Dx=uh(),Hx=lh(),Lx=od(),Bx=fh(),Gx=Sh(),Vx=_h(),Fx=wh(),Zx=vh(),Kx=bh(),Wx=Ih(),Jx=Ph();function Yx(e=!1){let t=[Vx.default,Fx.default,Zx.default,Kx.default,Wx.default,Jx.default,Hx.default,Lx.default,Dx.default,Bx.default,Gx.default];return e?t.push(Mx.default,Nx.default):t.push(zx.default,qx.default),t.push(jx.default),t}o(Yx,"getApplicator");fd.default=Yx});var Ah=x(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var ve=F(),Qx={message:o(({schemaCode:e})=>(0,ve.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ve._)`{format: ${e}}`,"params")},Xx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Qx,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():y();function h(){let _=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),S=r.const("fDef",(0,ve._)`${_}[${s}]`),w=r.let("fType"),v=r.let("format");r.if((0,ve._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>r.assign(w,(0,ve._)`${S}.type || "string"`).assign(v,(0,ve._)`${S}.validate`),()=>r.assign(w,(0,ve._)`"string"`).assign(v,S)),e.fail$data((0,ve.or)(b(),R()));function b(){return d.strictSchema===!1?ve.nil:(0,ve._)`${s} && !${v}`}o(b,"unknownFmt");function R(){let q=l.$async?(0,ve._)`(${S}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ve._)`${v}(${n})`,N=(0,ve._)`(typeof ${v} == "function" ? ${q} : ${v}.test(${n}))`;return(0,ve._)`${v} && ${v} !== true && ${w} === ${t} && !${N}`}o(R,"invalidFmt")}o(h,"validate$DataFormat");function y(){let _=m.formats[i];if(!_){b();return}if(_===!0)return;let[S,w,v]=R(_);S===t&&e.pass(q());function b(){if(d.strictSchema===!1){m.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function R(N){let qe=N instanceof RegExp?(0,ve.regexpCode)(N):d.code.formats?(0,ve._)`${d.code.formats}${(0,ve.getProperty)(i)}`:void 0,it=r.scopeValue("formats",{key:i,ref:N,code:qe});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ve._)`${it}.validate`]:["string",N,it]}o(R,"getFormat");function q(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ve._)`await ${v}(${n})`}return typeof w=="function"?(0,ve._)`${v}(${n})`:(0,ve._)`${v}.test(${n})`}o(q,"validCondition")}o(y,"validateFormat")}};hd.default=Xx});var Th=x(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var eA=Ah(),tA=[eA.default];gd.default=tA});var kh=x(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Uh=x(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var rA=jf(),nA=Xf(),oA=xh(),aA=Th(),Eh=kh(),iA=[rA.default,nA.default,(0,oA.default)(),aA.default,Eh.metadataVocabulary,Eh.contentVocabulary];yd.default=iA});var $h=x(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.DiscrError=void 0;var Oh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Oh||(Ui.DiscrError=Oh={}))});var Mh=x(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var An=F(),Sd=$h(),zh=mi(),sA=qo(),cA=re(),uA={message:o(({params:{discrError:e,tagName:t}})=>e===Sd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,An._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},dA={keyword:"discriminator",type:"object",schemaType:"object",error:uA,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:s}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),p=t.const("tag",(0,An._)`${r}${(0,An.getProperty)(c)}`);t.if((0,An._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:Sd.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let y=h();t.if(!1);for(let _ in y)t.elseIf((0,An._)`${p} === ${_}`),t.assign(d,m(y[_]));t.else(),e.error(!1,{discrError:Sd.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(y){let _=t.name("valid"),S=e.subschema({keyword:"oneOf",schemaProp:y},_);return e.mergeEvaluated(S,An.Name),_}o(m,"applyTagSchema");function h(){var y;let _={},S=v(a),w=!0;for(let q=0;q<s.length;q++){let N=s[q];if(N?.$ref&&!(0,cA.schemaHasRulesButRef)(N,i.self.RULES)){let it=N.$ref;if(N=zh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,it),N instanceof zh.SchemaEnv&&(N=N.schema),N===void 0)throw new sA.default(i.opts.uriResolver,i.baseId,it)}let qe=(y=N?.properties)===null||y===void 0?void 0:y[c];if(typeof qe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);w=w&&(S||v(N)),b(qe,q)}if(!w)throw new Error(`discriminator: "${c}" must be required`);return _;function v({required:q}){return Array.isArray(q)&&q.includes(c)}function b(q,N){if(q.const)R(q.const,N);else if(q.enum)for(let qe of q.enum)R(qe,N);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function R(q,N){if(typeof q!="string"||q in _)throw new Error(`discriminator: "${c}" values must be unique strings`);_[q]=N}}o(h,"getMapping")}};_d.default=dA});var qh=x((gB,lA)=>{lA.exports={$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 vd=x((le,wd)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var pA=Of(),mA=Uh(),fA=Mh(),Nh=qh(),hA=["/properties"],Oi="http://json-schema.org/draft-07/schema",Tn=class extends pA.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),mA.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(fA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Nh,hA):Nh;this.addMetaSchema(t,Oi,!1),this.refs["http://json-schema.org/schema"]=Oi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Oi)?Oi:void 0)}};le.Ajv=Tn;wd.exports=le=Tn;wd.exports.Ajv=Tn;Object.defineProperty(le,"__esModule",{value:!0});le.default=Tn;var gA=Mo();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:o(function(){return gA.KeywordCxt},"get")});var kn=F();Object.defineProperty(le,"_",{enumerable:!0,get:o(function(){return kn._},"get")});Object.defineProperty(le,"str",{enumerable:!0,get:o(function(){return kn.str},"get")});Object.defineProperty(le,"stringify",{enumerable:!0,get:o(function(){return kn.stringify},"get")});Object.defineProperty(le,"nil",{enumerable:!0,get:o(function(){return kn.nil},"get")});Object.defineProperty(le,"Name",{enumerable:!0,get:o(function(){return kn.Name},"get")});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:o(function(){return kn.CodeGen},"get")});var yA=li();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:o(function(){return yA.default},"get")});var SA=qo();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:o(function(){return SA.default},"get")})});var Fh=x(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.formatNames=Et.fastFormats=Et.fullFormats=void 0;function kt(e,t){return{validate:e,compare:t}}o(kt,"fmtDef");Et.fullFormats={date:kt(Lh,Id),time:kt(Rd(!0),Pd),"date-time":kt(jh(!0),Gh),"iso-time":kt(Rd(),Bh),"iso-date-time":kt(jh(),Vh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:CA,"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:EA,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:IA,int32:{type:"number",validate:AA},int64:{type:"number",validate:TA},float:{type:"number",validate:Hh},double:{type:"number",validate:Hh},password:!0,binary:!0};Et.fastFormats={...Et.fullFormats,date:kt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Id),time:kt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Pd),"date-time":kt(/^\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,Gh),"iso-time":kt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Bh),"iso-date-time":kt(/^\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,Vh),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};Et.formatNames=Object.keys(Et.fullFormats);function _A(e){return e%4===0&&(e%100!==0||e%400===0)}o(_A,"isLeapYear");var wA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,vA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Lh(e){let t=wA.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n===2&&_A(r)?29:vA[n])}o(Lh,"date");function Id(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Id,"compareDate");var bd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Rd(e){return o(function(r){let n=bd.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],c=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!c)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&s<61},"time")}o(Rd,"getTime");function Pd(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(Pd,"compareTime");function Bh(e,t){if(!(e&&t))return;let r=bd.exec(e),n=bd.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(Bh,"compareIsoTime");var Cd=/t|\s/i;function jh(e){let t=Rd(e);return o(function(n){let a=n.split(Cd);return a.length===2&&Lh(a[0])&&t(a[1])},"date_time")}o(jh,"getDateTime");function Gh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(Gh,"compareDateTime");function Vh(e,t){if(!(e&&t))return;let[r,n]=e.split(Cd),[a,i]=t.split(Cd),s=Id(r,a);if(s!==void 0)return s||Pd(n,i)}o(Vh,"compareIsoDateTime");var bA=/\/|:/,RA=/^(?:[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 CA(e){return bA.test(e)&&RA.test(e)}o(CA,"uri");var Dh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IA(e){return Dh.lastIndex=0,Dh.test(e)}o(IA,"byte");var PA=-(2**31),xA=2**31-1;function AA(e){return Number.isInteger(e)&&e<=xA&&e>=PA}o(AA,"validateInt32");function TA(e){return Number.isInteger(e)}o(TA,"validateInt64");function Hh(){return!0}o(Hh,"validateNumber");var kA=/[^\\]\\Z/;function EA(e){if(kA.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(EA,"regex")});var Zh=x(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.formatLimitDefinition=void 0;var UA=vd(),Rt=F(),Rr=Rt.operators,$i={formatMaximum:{okStr:"<=",ok:Rr.LTE,fail:Rr.GT},formatMinimum:{okStr:">=",ok:Rr.GTE,fail:Rr.LT},formatExclusiveMaximum:{okStr:"<",ok:Rr.LT,fail:Rr.GTE},formatExclusiveMinimum:{okStr:">",ok:Rr.GT,fail:Rr.LTE}},OA={message:o(({keyword:e,schemaCode:t})=>(0,Rt.str)`should be ${$i[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Rt._)`{comparison: ${$i[e].okStr}, limit: ${t}}`,"params")};En.formatLimitDefinition={keyword:Object.keys($i),type:"string",schemaType:"string",$data:!0,error:OA,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:i}=e,{opts:s,self:c}=i;if(!s.validateFormats)return;let d=new UA.KeywordCxt(i,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:s.code.formats}),y=t.const("fmt",(0,Rt._)`${h}[${d.schemaCode}]`);e.fail$data((0,Rt.or)((0,Rt._)`typeof ${y} != "object"`,(0,Rt._)`${y} instanceof RegExp`,(0,Rt._)`typeof ${y}.compare != "function"`,m(y)))}o(p,"validate$DataFormat");function l(){let h=d.schema,y=c.formats[h];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let _=t.scopeValue("formats",{key:h,ref:y,code:s.code.formats?(0,Rt._)`${s.code.formats}${(0,Rt.getProperty)(h)}`:void 0});e.fail$data(m(_))}o(l,"validateFormat");function m(h){return(0,Rt._)`${h}.compare(${r}, ${n}) ${$i[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var $A=o(e=>(e.addKeyword(En.formatLimitDefinition),e),"formatLimitPlugin");En.default=$A});var Yh=x((Yo,Jh)=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Un=Fh(),zA=Zh(),xd=F(),Kh=new xd.Name("fullFormats"),MA=new xd.Name("fastFormats"),Ad=o((e,t={keywords:!0})=>{if(Array.isArray(t))return Wh(e,t,Un.fullFormats,Kh),e;let[r,n]=t.mode==="fast"?[Un.fastFormats,MA]:[Un.fullFormats,Kh],a=t.formats||Un.formatNames;return Wh(e,a,r,n),t.keywords&&(0,zA.default)(e),e},"formatsPlugin");Ad.get=(e,t="full")=>{let n=(t==="fast"?Un.fastFormats:Un.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Wh(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,xd._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(Wh,"addFormats");Jh.exports=Yo=Ad;Object.defineProperty(Yo,"__esModule",{value:!0});Yo.default=Ad});Rv();function cr(e){return!!e._zod}o(cr,"isZ4Schema");function Ge(e,t){return cr(e)?tc(e,t):e.safeParse(t)}o(Ge,"safeParse");function ln(e){if(!e)return;let t;if(cr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(ln,"getObjectShape");function Wp(e){if(cr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let 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]}let n=e.value;if(n!==void 0)return n}o(Wp,"getLiteralValue");ie();var dr="2025-11-25",Jp="2025-03-26",lr=[dr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],pr="io.modelcontextprotocol/related-task",ja="2.0",Ie=Fp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Yp=me([f(),ee().int()]),Qp=f(),$q=Ce({ttl:ee().optional(),pollInterval:ee().optional()}),Pv=I({ttl:ee().optional()}),xv=I({taskId:f()}),ac=Ce({progressToken:Yp.optional(),[pr]:xv.optional()}),ot=I({_meta:ac.optional()}),po=ot.extend({task:Pv.optional()}),Xp=o(e=>po.safeParse(e).success,"isTaskAugmentedRequestParams"),Ae=I({method:f(),params:ot.loose().optional()}),st=I({_meta:ac.optional()}),ct=I({method:f(),params:st.loose().optional()}),Te=Ce({_meta:ac.optional()}),Da=me([f(),ee().int()]),em=I({jsonrpc:O(ja),id:Da,...Ae.shape}).strict(),It=o(e=>em.safeParse(e).success,"isJSONRPCRequest"),tm=I({jsonrpc:O(ja),...ct.shape}).strict(),rm=o(e=>tm.safeParse(e).success,"isJSONRPCNotification"),ic=I({jsonrpc:O(ja),id:Da,result:Te}).strict(),St=o(e=>ic.safeParse(e).success,"isJSONRPCResultResponse");var U;(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"})(U||(U={}));var sc=I({jsonrpc:O(ja),id:Da.optional(),error:I({code:ee().int(),message:f(),data:we().optional()})}).strict();var mn=o(e=>sc.safeParse(e).success,"isJSONRPCErrorResponse");var $r=me([em,tm,ic,sc]),zq=me([ic,sc]),Ht=Te.strict(),Av=st.extend({requestId:Da.optional(),reason:f().optional()}),Ha=ct.extend({method:O("notifications/cancelled"),params:Av}),Tv=I({src:f(),mimeType:f().optional(),sizes:C(f()).optional(),theme:nt(["light","dark"]).optional()}),mo=I({icons:C(Tv).optional()}),pn=I({name:f(),title:f().optional()}),fn=pn.extend({...pn.shape,...mo.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),kv=nc(I({applyDefaults:ae().optional()}),ue(f(),we())),Ev=oc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,nc(I({form:kv.optional(),url:Ie.optional()}),ue(f(),we()).optional())),Uv=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({sampling:Ce({createMessage:Ie.optional()}).optional(),elicitation:Ce({create:Ie.optional()}).optional()}).optional()}),Ov=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({tools:Ce({call:Ie.optional()}).optional()}).optional()}),$v=I({experimental:ue(f(),Ie).optional(),sampling:I({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:Ev.optional(),roots:I({listChanged:ae().optional()}).optional(),tasks:Uv.optional(),extensions:ue(f(),Ie).optional()}),zv=ot.extend({protocolVersion:f(),capabilities:$v,clientInfo:fn}),La=Ae.extend({method:O("initialize"),params:zv}),cc=o(e=>La.safeParse(e).success,"isInitializeRequest"),Mv=I({experimental:ue(f(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:I({listChanged:ae().optional()}).optional(),resources:I({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:I({listChanged:ae().optional()}).optional(),tasks:Ov.optional(),extensions:ue(f(),Ie).optional()}),uc=Te.extend({protocolVersion:f(),capabilities:Mv,serverInfo:fn,instructions:f().optional()}),Ba=ct.extend({method:O("notifications/initialized"),params:st.optional()}),nm=o(e=>Ba.safeParse(e).success,"isInitializedNotification"),Ga=Ae.extend({method:O("ping"),params:ot.optional()}),qv=I({progress:ee(),total:ge(ee()),message:ge(f())}),Nv=I({...st.shape,...qv.shape,progressToken:Yp}),Va=ct.extend({method:O("notifications/progress"),params:Nv}),jv=ot.extend({cursor:Qp.optional()}),fo=Ae.extend({params:jv.optional()}),ho=Te.extend({nextCursor:Qp.optional()}),Dv=nt(["working","input_required","completed","failed","cancelled"]),go=I({taskId:f(),status:Dv,ttl:me([ee(),Gp()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ge(ee()),statusMessage:ge(f())}),Lt=Te.extend({task:go}),Hv=st.merge(go),yo=ct.extend({method:O("notifications/tasks/status"),params:Hv}),Fa=Ae.extend({method:O("tasks/get"),params:ot.extend({taskId:f()})}),Za=Te.merge(go),Ka=Ae.extend({method:O("tasks/result"),params:ot.extend({taskId:f()})}),Mq=Te.loose(),Wa=fo.extend({method:O("tasks/list")}),Ja=ho.extend({tasks:C(go)}),Ya=Ae.extend({method:O("tasks/cancel"),params:ot.extend({taskId:f()})}),om=Te.merge(go),am=I({uri:f(),mimeType:ge(f()),_meta:ue(f(),we()).optional()}),im=am.extend({text:f()}),dc=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),sm=am.extend({blob:dc}),So=nt(["user","assistant"]),hn=I({audience:C(So).optional(),priority:ee().min(0).max(1).optional(),lastModified:Lp.datetime({offset:!0}).optional()}),cm=I({...pn.shape,...mo.shape,uri:f(),description:ge(f()),mimeType:ge(f()),size:ge(ee()),annotations:hn.optional(),_meta:ge(Ce({}))}),Lv=I({...pn.shape,...mo.shape,uriTemplate:f(),description:ge(f()),mimeType:ge(f()),annotations:hn.optional(),_meta:ge(Ce({}))}),lc=fo.extend({method:O("resources/list")}),pc=ho.extend({resources:C(cm)}),Bv=fo.extend({method:O("resources/templates/list")}),mc=ho.extend({resourceTemplates:C(Lv)}),fc=ot.extend({uri:f()}),Gv=fc,hc=Ae.extend({method:O("resources/read"),params:Gv}),gc=Te.extend({contents:C(me([im,sm]))}),yc=ct.extend({method:O("notifications/resources/list_changed"),params:st.optional()}),Vv=fc,Fv=Ae.extend({method:O("resources/subscribe"),params:Vv}),Zv=fc,Kv=Ae.extend({method:O("resources/unsubscribe"),params:Zv}),Wv=st.extend({uri:f()}),Jv=ct.extend({method:O("notifications/resources/updated"),params:Wv}),Yv=I({name:f(),description:ge(f()),required:ge(ae())}),Qv=I({...pn.shape,...mo.shape,description:ge(f()),arguments:ge(C(Yv)),_meta:ge(Ce({}))}),Sc=fo.extend({method:O("prompts/list")}),_c=ho.extend({prompts:C(Qv)}),Xv=ot.extend({name:f(),arguments:ue(f(),f()).optional()}),wc=Ae.extend({method:O("prompts/get"),params:Xv}),vc=I({type:O("text"),text:f(),annotations:hn.optional(),_meta:ue(f(),we()).optional()}),bc=I({type:O("image"),data:dc,mimeType:f(),annotations:hn.optional(),_meta:ue(f(),we()).optional()}),Rc=I({type:O("audio"),data:dc,mimeType:f(),annotations:hn.optional(),_meta:ue(f(),we()).optional()}),eb=I({type:O("tool_use"),name:f(),id:f(),input:ue(f(),we()),_meta:ue(f(),we()).optional()}),tb=I({type:O("resource"),resource:me([im,sm]),annotations:hn.optional(),_meta:ue(f(),we()).optional()}),rb=cm.extend({type:O("resource_link")}),Cc=me([vc,bc,Rc,rb,tb]),nb=I({role:So,content:Cc}),Ic=Te.extend({description:f().optional(),messages:C(nb)}),Pc=ct.extend({method:O("notifications/prompts/list_changed"),params:st.optional()}),ob=I({title:f().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),ab=I({taskSupport:nt(["required","optional","forbidden"]).optional()}),um=I({...pn.shape,...mo.shape,description:f().optional(),inputSchema:I({type:O("object"),properties:ue(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()),outputSchema:I({type:O("object"),properties:ue(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()).optional(),annotations:ob.optional(),execution:ab.optional(),_meta:ue(f(),we()).optional()}),xc=fo.extend({method:O("tools/list")}),Ac=ho.extend({tools:C(um)}),mr=Te.extend({content:C(Cc).default([]),structuredContent:ue(f(),we()).optional(),isError:ae().optional()}),qq=mr.or(Te.extend({toolResult:we()})),ib=po.extend({name:f(),arguments:ue(f(),we()).optional()}),_o=Ae.extend({method:O("tools/call"),params:ib}),Tc=ct.extend({method:O("notifications/tools/list_changed"),params:st.optional()}),dm=I({autoRefresh:ae().default(!0),debounceMs:ee().int().nonnegative().default(300)}),wo=nt(["debug","info","notice","warning","error","critical","alert","emergency"]),sb=ot.extend({level:wo}),kc=Ae.extend({method:O("logging/setLevel"),params:sb}),cb=st.extend({level:wo,logger:f().optional(),data:we()}),ub=ct.extend({method:O("notifications/message"),params:cb}),db=I({name:f().optional()}),lb=I({hints:C(db).optional(),costPriority:ee().min(0).max(1).optional(),speedPriority:ee().min(0).max(1).optional(),intelligencePriority:ee().min(0).max(1).optional()}),pb=I({mode:nt(["auto","required","none"]).optional()}),mb=I({type:O("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:C(Cc).default([]),structuredContent:I({}).loose().optional(),isError:ae().optional(),_meta:ue(f(),we()).optional()}),fb=rc("type",[vc,bc,Rc]),Na=rc("type",[vc,bc,Rc,eb,mb]),hb=I({role:So,content:me([Na,C(Na)]),_meta:ue(f(),we()).optional()}),gb=po.extend({messages:C(hb),modelPreferences:lb.optional(),systemPrompt:f().optional(),includeContext:nt(["none","thisServer","allServers"]).optional(),temperature:ee().optional(),maxTokens:ee().int(),stopSequences:C(f()).optional(),metadata:Ie.optional(),tools:C(um).optional(),toolChoice:pb.optional()}),Ec=Ae.extend({method:O("sampling/createMessage"),params:gb}),zr=Te.extend({model:f(),stopReason:ge(nt(["endTurn","stopSequence","maxTokens"]).or(f())),role:So,content:fb}),vo=Te.extend({model:f(),stopReason:ge(nt(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:So,content:me([Na,C(Na)])}),yb=I({type:O("boolean"),title:f().optional(),description:f().optional(),default:ae().optional()}),Sb=I({type:O("string"),title:f().optional(),description:f().optional(),minLength:ee().optional(),maxLength:ee().optional(),format:nt(["email","uri","date","date-time"]).optional(),default:f().optional()}),_b=I({type:nt(["number","integer"]),title:f().optional(),description:f().optional(),minimum:ee().optional(),maximum:ee().optional(),default:ee().optional()}),wb=I({type:O("string"),title:f().optional(),description:f().optional(),enum:C(f()),default:f().optional()}),vb=I({type:O("string"),title:f().optional(),description:f().optional(),oneOf:C(I({const:f(),title:f()})),default:f().optional()}),bb=I({type:O("string"),title:f().optional(),description:f().optional(),enum:C(f()),enumNames:C(f()).optional(),default:f().optional()}),Rb=me([wb,vb]),Cb=I({type:O("array"),title:f().optional(),description:f().optional(),minItems:ee().optional(),maxItems:ee().optional(),items:I({type:O("string"),enum:C(f())}),default:C(f()).optional()}),Ib=I({type:O("array"),title:f().optional(),description:f().optional(),minItems:ee().optional(),maxItems:ee().optional(),items:I({anyOf:C(I({const:f(),title:f()}))}),default:C(f()).optional()}),Pb=me([Cb,Ib]),xb=me([bb,Rb,Pb]),Ab=me([xb,yb,Sb,_b]),Tb=po.extend({mode:O("form").optional(),message:f(),requestedSchema:I({type:O("object"),properties:ue(f(),Ab),required:C(f()).optional()})}),kb=po.extend({mode:O("url"),message:f(),elicitationId:f(),url:f().url()}),Eb=me([Tb,kb]),Uc=Ae.extend({method:O("elicitation/create"),params:Eb}),Ub=st.extend({elicitationId:f()}),Ob=ct.extend({method:O("notifications/elicitation/complete"),params:Ub}),fr=Te.extend({action:nt(["accept","decline","cancel"]),content:oc(e=>e===null?void 0:e,ue(f(),me([f(),ee(),ae(),C(f())])).optional())}),$b=I({type:O("ref/resource"),uri:f()});var zb=I({type:O("ref/prompt"),name:f()}),Mb=ot.extend({ref:me([zb,$b]),argument:I({name:f(),value:f()}),context:I({arguments:ue(f(),f()).optional()}).optional()}),qb=Ae.extend({method:O("completion/complete"),params:Mb});var Oc=Te.extend({completion:Ce({values:C(f()).max(100),total:ge(ee().int()),hasMore:ge(ae())})}),Nb=I({uri:f().startsWith("file://"),name:f().optional(),_meta:ue(f(),we()).optional()}),jb=Ae.extend({method:O("roots/list"),params:ot.optional()}),$c=Te.extend({roots:C(Nb)}),Db=ct.extend({method:O("notifications/roots/list_changed"),params:st.optional()}),Nq=me([Ga,La,qb,kc,wc,Sc,lc,Bv,hc,Fv,Kv,_o,xc,Fa,Ka,Wa,Ya]),jq=me([Ha,Va,Ba,Db,yo]),Dq=me([Ht,zr,vo,fr,$c,Za,Ja,Lt]),Hq=me([Ga,Ec,Uc,jb,Fa,Ka,Wa,Ya]),Lq=me([Ha,Va,ub,Jv,yc,Tc,Pc,yo,Ob]),Bq=me([Ht,uc,Oc,Ic,_c,pc,mc,gc,mr,Ac,Za,Ja,Lt]),A=class e extends Error{static{o(this,"McpError")}constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===U.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new ur(a.elicitations,r)}return new e(t,r,n)}},ur=class extends A{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function hr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(hr,"isTerminal");var Hb=Symbol("Let zodToJsonSchema decide on which parser to use");var DN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zc(e){let r=ln(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Wp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(zc,"getMethodLiteral");function Mc(e,t){let r=Ge(e,t);if(!r.success)throw r.error;return r.data}o(Mc,"parseWithCompat");var Zb=6e4,gn=class{static{o(this,"Protocol")}constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ha,r=>{this._oncancel(r)}),this.setNotificationHandler(Va,r=>{this._onprogress(r)}),this.setRequestHandler(Ga,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Fa,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(U.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Ka,async(r,n)=>{let a=o(async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(c.type==="response"||c.type==="error"){let d=c.message,p=d.id,l=this._requestResolvers.get(p);if(l)if(this._requestResolvers.delete(p),c.type==="response")l(d);else{let m=d,h=new A(m.error.code,m.error.message,m.error.data);l(h)}else{let m=c.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${p}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new A(U.InvalidParams,`Task not found: ${i}`);if(!hr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(hr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[pr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(Wa,async(r,n)=>{try{let{tasks:a,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:a,nextCursor:i,_meta:{}}}catch(a){throw new A(U.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(Ya,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(hr(a.status))throw new A(U.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new A(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof A?a:new A(U.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,a,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:a})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),A.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let a=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{a?.(i,s),St(i)||mn(i)?this._onresponse(i):It(i)?this._onrequest(i,s):rm(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=A.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,a=this._transport,i=t.params?._meta?.[pr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},a?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):a?.send(l).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let c=Xp(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,p={signal:s.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async l=>{if(s.signal.aborted)return;let m={relatedRequestId:t.id};i&&(m.relatedTask={taskId:i}),await this.notification(l,m)},"sendNotification"),sendRequest:o(async(l,m,h)=>{if(s.signal.aborted)throw new A(U.ConnectionClosed,"Request was cancelled");let y={...h,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let _=y.relatedTask?.taskId??i;return _&&d&&await d.updateTaskStatus(_,"input_required"),await this.request(l,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),i=this._progressHandlers.get(a);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(a),c=this._timeoutInfo.get(a);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(d);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),St(t))n(t);else{let s=new A(t.error.code,t.error.message,t.error.data);n(s)}return}let a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(St(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let c=s.task;typeof c.taskId=="string"&&(i=!0,this._taskProgressTokens.set(c.taskId,r))}}if(i||this._progressHandlers.delete(r),St(t))a(t);else{let s=A.fromError(t.error.code,t.error.message,t.error.data);a(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:a}=n??{};if(!a){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof A?s:new A(U.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Lt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(U.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},hr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new A(U.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new A(U.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,d)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:c,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(b=>{l(b)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),c&&this.assertTaskCapability(t.method)}catch(b){m(b);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(y.params={...y.params,task:c}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[pr]:d}});let _=o(b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));let R=b instanceof A?b:new A(U.RequestTimeout,String(b));l(R)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let R=Ge(r,b.result);R.success?p(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{_(n?.signal?.reason)});let S=n?.timeout??Zb,w=o(()=>_(A.fromError(U.RequestTimeout,"Request timed out",{timeout:S})),"timeoutHandler");this._setupTimeout(h,S,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let b=o(R=>{let q=this._responseHandlers.get(h);q?q(R):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(v,{type:"request",message:y,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(h),l(R)})}else this._transport.send(y,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Za,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ja,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},om,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let c={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[pr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let c={...t,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[pr]:r.relatedTask}}}),this._transport?.send(c,r).catch(d=>this._onerror(d))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=zc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=Mc(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=zc(t);this._notificationHandlers.set(n,a=>{let i=Mc(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&It(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new A(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(t);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(r.aborted){i(new A(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new A(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:o(async a=>{if(!t)throw new Error("No request provided");return await n.createTask(a,t.id,{method:t.method,params:t.params},r)},"createTask"),getTask:o(async a=>{let i=await n.getTask(a,r);if(!i)throw new A(U.InvalidParams,"Failed to retrieve task: Task not found");return i},"getTask"),storeTaskResult:o(async(a,i,s)=>{await n.storeTaskResult(a,i,s,r);let c=await n.getTask(a,r);if(c){let d=yo.parse({method:"notifications/tasks/status",params:c});await this.notification(d),hr(c.status)&&this._cleanupTaskProgressHandler(a)}},"storeTaskResult"),getTaskResult:o(a=>n.getTaskResult(a,r),"getTaskResult"),updateTaskStatus:o(async(a,i,s)=>{let c=await n.getTask(a,r);if(!c)throw new A(U.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(hr(c.status))throw new A(U.InvalidParams,`Cannot update task "${a}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,i,s,r);let d=await n.getTask(a,r);if(d){let p=yo.parse({method:"notifications/tasks/status",params:d});await this.notification(p),hr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function lm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(lm,"isPlainObject");function Qa(e,t){let r={...e};for(let n in t){let a=n,i=t[a];if(i===void 0)continue;let s=r[a];lm(s)&&lm(i)?r[a]={...s,...i}:r[a]=i}return r}o(Qa,"mergeCapabilities");var Qh=qp(vd(),1),Xh=qp(Yh(),1);function qA(){let e=new Qh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Xh.default)(e),e}o(qA,"createDefaultAjvInstance");var On=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??qA()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var zi=class{static{o(this,"ExperimentalServerTasks")}constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],i=Array.isArray(a.content)?a.content:[a.content],s=i.some(l=>l.type==="tool_result"),c=t.messages.length>1?t.messages[t.messages.length-2]:void 0,d=c?Array.isArray(c.content)?c.content:[c.content]:[],p=d.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let l=new Set(d.filter(h=>h.type==="tool_use").map(h=>h.id)),m=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==m.size||![...l].every(h=>m.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},zr,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),a=t.mode??"form";switch(a){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=a==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},fr,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Mi(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}o(Mi,"assertToolsCallTaskCapability");function qi(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}o(qi,"assertClientRequestTaskCapability");var Ni=class extends gn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(wo.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new On,this.setRequestHandler(La,n=>this._oninitialize(n)),this.setNotificationHandler(Ba,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(kc,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=wo.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new zi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qa(this._capabilities,t)}setRequestHandler(t,r){let a=ln(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(cr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let c=o(async(d,p)=>{let l=Ge(_o,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ge(Lt,h);if(!_.success){let S=_.error instanceof Error?_.error.message:String(_.error);throw new A(U.InvalidParams,`Invalid task creation result: ${S}`)}return _.data}let y=Ge(mr,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new A(U.InvalidParams,`Invalid tools/call result: ${_}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){qi(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Mi(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:lr.includes(r)?r:dr,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"},Ht)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],i=a.some(p=>p.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],d=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==l.size||![...p].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},vo,r):this.request({method:"sampling/createMessage",params:t},zr,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let a=t;return this.request({method:"elicitation/create",params:a},fr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let a=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:a},fr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new A(U.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof A?s:new A(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},$c,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var ji=class{static{o(this,"WebStandardStreamableHTTPServerTransport")}constructor(t={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,a){let i={code:r,message:n};return a?.data!==void 0&&(i.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...a?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,a){if(!this._eventStore||a<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
33
33
  data:
34
34
 
35
35
  `;this._retryInterval!==void 0&&(s=`id: ${i}
36
36
  retry: ${this._retryInterval}
37
37
  data:
38
38
 
39
- `),t.enqueue(r.encode(s))}async handleGetRequest(t){if(!t.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(t);if(n)return n;let a=this.validateProtocolVersion(t);if(a)return a;if(this._eventStore){let p=t.headers.get("last-event-id");if(p)return this.replayEvents(p)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let i=new TextEncoder,s,u=new ReadableStream({start:o(p=>{s=p},"start"),cancel:o(()=>{this._streamMapping.delete(this._standaloneSseStreamId)},"cancel")}),d={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};return this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:s,encoder:i,cleanup:o(()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{s.close()}catch{}},"cleanup")}),new Response(u,{headers:d})}async replayEvents(t){if(!this._eventStore)return this.onerror?.(new Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r;if(this._eventStore.getStreamIdForEventId){if(r=await this._eventStore.getStreamIdForEventId(t),!r)return this.onerror?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(r)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let a=new TextEncoder,i,s=new ReadableStream({start:o(d=>{i=d},"start"),cancel:o(()=>{},"cancel")}),u=await this._eventStore.replayEventsAfter(t,{send:o(async(d,p)=>{if(!this.writeSSEEvent(i,a,p,d)){this.onerror?.(new Error("Failed replay events"));try{i.close()}catch{}}},"send")});return this._streamMapping.set(u,{controller:i,encoder:a,cleanup:o(()=>{this._streamMapping.delete(u);try{i.close()}catch{}},"cleanup")}),new Response(s,{headers:n})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(t,r,n,a){try{let i=`event: message
39
+ `),t.enqueue(r.encode(s))}async handleGetRequest(t){if(!t.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(t);if(n)return n;let a=this.validateProtocolVersion(t);if(a)return a;if(this._eventStore){let p=t.headers.get("last-event-id");if(p)return this.replayEvents(p)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let i=new TextEncoder,s,c=new ReadableStream({start:o(p=>{s=p},"start"),cancel:o(()=>{this._streamMapping.delete(this._standaloneSseStreamId)},"cancel")}),d={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};return this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:s,encoder:i,cleanup:o(()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{s.close()}catch{}},"cleanup")}),new Response(c,{headers:d})}async replayEvents(t){if(!this._eventStore)return this.onerror?.(new Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r;if(this._eventStore.getStreamIdForEventId){if(r=await this._eventStore.getStreamIdForEventId(t),!r)return this.onerror?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(r)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let a=new TextEncoder,i,s=new ReadableStream({start:o(d=>{i=d},"start"),cancel:o(()=>{},"cancel")}),c=await this._eventStore.replayEventsAfter(t,{send:o(async(d,p)=>{if(!this.writeSSEEvent(i,a,p,d)){this.onerror?.(new Error("Failed replay events"));try{i.close()}catch{}}},"send")});return this._streamMapping.set(c,{controller:i,encoder:a,cleanup:o(()=>{this._streamMapping.delete(c);try{i.close()}catch{}},"cleanup")}),new Response(s,{headers:n})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(t,r,n,a){try{let i=`event: message
40
40
  `;return a&&(i+=`id: ${a}
41
41
  `),i+=`data: ${JSON.stringify(n)}
42
42
 
43
- `,t.enqueue(r.encode(i)),!0}catch(i){return this.onerror?.(i),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let a=t.headers.get("content-type");if(!a||!a.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},s;if(r?.parsedBody!==void 0)s=r.parsedBody;else try{s=await t.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let u;try{Array.isArray(s)?u=s.map(v=>Mr.parse(v)):u=[Mr.parse(s)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let d=u.some(Ic);if(d){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(u.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!d){let v=this.validateSession(t);if(v)return v;let R=this.validateProtocolVersion(t);if(R)return R}if(!u.some(xt)){for(let v of u)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=u.find(v=>Ic(v)),f=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??gm;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let R of u)xt(R)&&this._requestToStreamMapping.set(R.id,l);for(let R of u)this.onmessage?.(R,{authInfo:r?.authInfo,requestInfo:i})});let _=new TextEncoder,w,y=new ReadableStream({start:o(v=>{w=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),S={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(S["mcp-session-id"]=this.sessionId);for(let v of u)xt(v)&&(this._streamMapping.set(l,{controller:w,encoder:_,cleanup:o(()=>{this._streamMapping.delete(l);try{w.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(w,_,l,f);for(let v of u){let R,b;xt(v)&&this._eventStore&&f>="2025-11-25"&&(R=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),b=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:R,closeStandaloneSSEStream:b})}return new Response(y,{status:200,headers:S})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!hr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${hr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${hr.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((St(t)||yn(t))&&(n=t.id),n===void 0){if(St(t)||yn(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let u=this._streamMapping.get(this._standaloneSseStreamId);if(u===void 0)return;u.controller&&u.encoder&&this.writeSSEEvent(u.controller,u.encoder,t,s);return}let a=this._requestToStreamMapping.get(n);if(!a)throw new Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let s;this._eventStore&&(s=await this._eventStore.storeEvent(a,t)),this.writeSSEEvent(i.controller,i.encoder,t,s)}if(St(t)||yn(t)){this._requestResponseMap.set(n,t);let s=Array.from(this._requestToStreamMapping.entries()).filter(([d,p])=>p===a).map(([d])=>d);if(s.every(d=>this._requestResponseMap.has(d))){if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let d={"Content-Type":"application/json"};this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId);let p=s.map(l=>this._requestResponseMap.get(l));p.length===1?i.resolveJson(new Response(JSON.stringify(p[0]),{status:200,headers:d})):i.resolveJson(new Response(JSON.stringify(p),{status:200,headers:d}))}else i.cleanup();for(let d of s)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function Vd(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(Vd,"truncate");function Sg(e){return"cause"in e?e.cause:void 0}o(Sg,"readCause");function ze(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=Vd(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=Vd(r.message);let n=Sg(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=Vd(n.message),n=Sg(n)}}o(ze,"addErrorLogFields");function gt(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(gt,"safeHost");function vg(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(vg,"setLogProperties");function Kd(e,t){vg(e,{subjectId:t.subjectId})}o(Kd,"applyGatewayPrincipalLogProperties");function Rg(e,t){vg(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(Rg,"applyGatewayRouteLogProperties");var qn={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},bg={...qn.runtime,...qn.config,...qn.downstream_auth,...qn.downstream_oauth,...qn.upstream_auth,...qn.upstream_mcp};function na(e){return typeof e=="string"&&Object.hasOwn(bg,e)}o(na,"isGatewayProblemCode");function Yi(e){return na(e)&&rt(e).callbackFailure===!0}o(Yi,"isGatewayCallbackFailureCode");function rt(e){return bg[e]}o(rt,"readGatewayProblemDefinition");function Zd(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";default:return"internal_server_error"}}o(Zd,"readDefaultGatewayProblemCodeForStatus");var Cg="gatewayCode";function Ig(e){let t=rt(e);return{title:t.title,body:t.publicDetail}}o(Ig,"readGatewayCallbackFailureContent");function _e(e){if(!(e instanceof Za))return;let t=e.extensionMembers?.[Cg];return na(t)?t:void 0}o(_e,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=rt(n.code),i=n.privateDetail??(Xi(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=iE(n);return new Za({message:i,extensionMembers:{[Cg]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function _t(e,t,r){let n=rt(r.code),a=sE(r.code,r.detail),i=Xi(r.code)?r.title??n.title:n.title,u={problem:{...fo.getProblemFromStatus(n.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:n.status,title:i,detail:a,code:r.code}};return r.headers!==void 0&&(u.additionalHeaders=r.headers),fo.format(u,e,t)}o(_t,"gatewayProblemResponse");function Xi(e){return rt(e).status<500}o(Xi,"canExposeGatewayProblemDetail");function iE(e){return!e.privateDetail||Xi(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(iE,"readRuntimeErrorCause");function sE(e,t){let r=rt(e);return Xi(e)&&t||r.publicDetail}o(sE,"readSafeGatewayProblemDetail");ae();var cE=["shared-oauth","user_oauth","static_secret","user-secret","shared-secret"],uE=["none","client_secret_basic","client_secret_post"],$e=c.string().min(1).brand(),Se=c.string().min(1).brand(),De=c.string().min(1).brand(),Dt=c.string().min(1).brand(),Qi=c.enum(cE),Wd=c.enum(uE),es=c.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),Jd=c.object({name:es,value:c.string().min(1).optional(),required:c.boolean().default(!0)}).strict();var Yd=new Map;function ts(e){Yd.set(e.policyType,e)}o(ts,"registerMcpAuthorizationPolicy");function Xd(e){if(e!==void 0)return Yd.get(e)}o(Xd,"getMcpAuthorizationPolicy");function rs(e){return Xd(e)!==void 0}o(rs,"isRegisteredMcpAuthorizationPolicyType");function Qd(){return[...Yd.keys()]}o(Qd,"listMcpAuthorizationPolicyTypes");ae();var kg=$e,dE=c.object({mode:c.literal("auto")}).strict(),lE=c.object({mode:c.literal("manual"),clientId:c.string().trim().min(1),clientSecret:c.string().min(1).optional(),tokenEndpointAuthMethod:Wd.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:c.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),Eg=c.discriminatedUnion("mode",[dE,lE]),pE=Eg.default({mode:"auto"}),el=c.object({scopes:c.array(c.string().min(1)).default([]),scopeDelimiter:c.string().min(1).default(" "),clientRegistration:pE}).strict(),Tg=el.extend({redirectPath:c.string().startsWith("/auth/connections/")}).strict(),xg=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),mE=new Set([...xg,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),hE=c.object({kind:c.literal("bearer_token"),token:c.string().min(1)}).strict(),fE=c.object({kind:c.literal("headers"),headers:c.array(c.object({name:es,value:c.string().min(1)}).strict()).min(1)}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.headers.entries()){let i=a.name.toLowerCase();xg.has(i)&&t.addIssue({code:c.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for static secret injection`,path:["headers",n,"name"]}),r.has(i)&&t.addIssue({code:c.ZodIssueCode.custom,message:`Duplicate static secret header ${a.name}`,path:["headers",n,"name"]}),r.add(i)}}),tl=c.discriminatedUnion("kind",[hE,fE]),gE=c.object({kind:c.literal("basic_auth_app_password"),usernameLabel:c.string().min(1).default("Username"),passwordLabel:c.string().min(1).default("App password")}).strict(),_E=c.object({kind:c.literal("bearer_token"),label:c.string().min(1).default("API key"),capture:c.enum(["browser_login"]).optional()}).strict(),rl=c.discriminatedUnion("kind",[gE,_E]),nl=c.object({kind:c.literal("bearer_token"),label:c.string().min(1).default("API key")}).strict(),yE=c.discriminatedUnion("mode",[c.object({mode:c.literal("shared-oauth"),oauth:Tg}).strict(),c.object({mode:c.literal("user_oauth"),oauth:Tg}).strict(),c.object({mode:c.literal("static_secret"),secret:tl}).strict(),c.object({mode:c.literal("user-secret"),secret:rl}).strict(),c.object({mode:c.literal("shared-secret"),secret:nl}).strict()]),wE=c.object({baseUrl:c.url(),resourceMetadataUrl:c.url(),requestHeaders:c.array(Jd).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();mE.has(i)&&t.addIssue({code:c.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for native MCP transport request headers`,path:["requestHeaders",n,"name"]}),r.has(i)&&t.addIssue({code:c.ZodIssueCode.custom,message:`Duplicate native MCP transport request header ${a.name}`,path:["requestHeaders",n,"name"]}),r.add(i)}}),I2=c.object({displayName:c.string().min(1),description:c.string().min(1).optional(),serverInfo:wn.optional(),authProfiles:c.record(De,yE),transport:wE}).strict().superRefine((e,t)=>{Object.keys(e.authProfiles).length===0&&t.addIssue({code:c.ZodIssueCode.custom,message:"authProfiles must contain at least one profile",path:["authProfiles"]})}),SE=c.object({"shared-oauth":el.optional(),user_oauth:el.optional(),static_secret:c.object({secret:tl}).strict().optional(),"user-secret":c.object({secret:rl}).strict().optional(),"shared-secret":c.object({secret:nl}).strict().optional()}).strict().superRefine((e,t)=>{Object.values(e).every(r=>r===void 0)&&t.addIssue({code:c.ZodIssueCode.custom,message:"authProfiles must contain at least one upstream auth profile"})}),Ag=c.object({id:kg,displayName:c.string().min(1),description:c.string().min(1).optional(),serverInfo:wn.optional(),mcpUrl:c.url(),protectedResourceMetadataUrl:c.url(),requestHeaders:c.array(Jd).default([]),authProfiles:SE}).strict(),vE=c.object({name:es,value:c.string().min(1).optional(),required:c.boolean().default(!0)}).strict(),ns={id:kg.optional(),displayName:c.string().min(1),summary:c.string().min(1).optional(),serverInfo:wn.optional(),mcpUrl:c.url(),protectedResourceMetadataUrl:c.url().optional(),requestHeaders:c.array(vE).default([])},RE=c.discriminatedUnion("authMode",[c.object({...ns,authMode:c.enum(["shared-oauth","user_oauth"]),scopes:c.array(c.string().min(1)).default([]),scopeDelimiter:c.string().min(1).default(" "),clientRegistration:Eg.optional(),clientId:c.string().trim().min(1).optional(),clientSecret:c.string().min(1).optional(),tokenEndpointAuthMethod:Wd.optional()}).strict(),c.object({...ns,authMode:c.literal("static_secret"),secret:tl}).strict(),c.object({...ns,authMode:c.literal("user-secret"),secret:rl}).strict(),c.object({...ns,authMode:c.literal("shared-secret"),secret:nl}).strict()]);function Pg(e){throw g("internal_server_error",e)}o(Pg,"throwGatewayConfigError");function bE(e){let t="mcp-upstream-";return e.startsWith(t)||Pg(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),$e.parse(e.slice(t.length))}o(bE,"inferUpstreamConnectionIdFromPolicyName");function CE(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(CE,"buildDefaultProtectedResourceMetadataUrl");function Ln(e,t){return De.parse(`${e}:${t}`)}o(Ln,"buildUpstreamAuthProfileId");function os(e,t){let r=Ag.safeParse(e);if(r.success)return r.data;let n=RE.parse(e),a=n.id??(t===void 0?void 0:bE(t));a===void 0&&Pg("Upstream policy options must include id when policy name is unavailable.");let i=n.requestHeaders.map(u=>({name:u.name,value:u.value,required:u.required})),s=(()=>{switch(n.authMode){case"shared-oauth":case"user_oauth":{let u=n.clientRegistration??(n.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:n.clientId,...n.clientSecret===void 0?{}:{clientSecret:n.clientSecret},...n.tokenEndpointAuthMethod===void 0?{}:{tokenEndpointAuthMethod:n.tokenEndpointAuthMethod}});return{[n.authMode]:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,clientRegistration:u}}}case"static_secret":case"user-secret":case"shared-secret":return{[n.authMode]:{secret:n.secret}}}})();return Ag.parse({id:a,displayName:n.displayName,...n.summary===void 0?{}:{description:n.summary},...n.serverInfo===void 0?{}:{serverInfo:n.serverInfo},mcpUrl:n.mcpUrl,protectedResourceMetadataUrl:n.protectedResourceMetadataUrl??CE(n.mcpUrl),requestHeaders:i,authProfiles:s})}o(os,"parseUpstreamConnectionPolicyOptions");function Og(e){return e.mode==="shared-oauth"||e.mode==="user_oauth"}o(Og,"isUpstreamOAuthAuthConfig");ae();var IE=c.looseObject({name:c.string().min(1),version:c.string().min(1).optional()}),TE=c.looseObject({}),AE=c.looseObject({name:Dt,namespace:Dt.optional(),upstreamPolicy:c.string().min(1).optional(),enabled:c.boolean().optional(),inputSchema:TE}),kE=c.looseObject({name:Dt,namespace:Dt.optional(),upstreamPolicy:c.string().min(1).optional(),enabled:c.boolean().optional()}),EE=c.looseObject({name:Dt,uri:c.string().min(1),upstreamPolicy:c.string().min(1).optional(),upstreamUri:c.string().min(1).optional(),enabled:c.boolean().optional()}),xE=c.enum(["openapi","upstream_mcp"]),PE=c.object({catalogSource:xE.default("openapi"),serverInfo:IE.optional(),tools:c.array(AE).default([]),prompts:c.array(kE).default([]),resources:c.array(EE).default([])}).strict();function Ug(e){return PE.parse(e??{})}o(Ug,"parseVirtualServerRouteOptions");function as(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(as,"toMcpTool");function is(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(is,"toMcpPrompt");function ss(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(ss,"toMcpResource");var OE="mcp-upstream-connection-inbound",Ng="/mcp/";function Fe(e){throw new Ft(e)}o(Fe,"throwRegistryError");function zg(e){return e.policyType===OE}o(zg,"isUpstreamConnectionPolicy");function UE(e){return rs(e.policyType)}o(UE,"isMcpOAuthInboundPolicy");function NE(e){e.startsWith(Ng)||Fe(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(Ng.length);return(!t||t.includes("/"))&&Fe(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),Se.parse(t)}o(NE,"readVirtualServerIdFromPath");function zE(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Fe(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Fe(`Upstream policy ${e.policyName} does not declare an auth mode.`),Qi.parse(r)}o(zE,"readSingleAuthMode");function $E(e){let t=e.connection.authProfiles[e.authMode];t||Fe(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":case"user_oauth":{let n=t;return{mode:e.authMode,oauth:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,redirectPath:r,clientRegistration:n.clientRegistration}}}case"static_secret":return{mode:"static_secret",secret:t.secret};case"user-secret":return{mode:"user-secret",secret:t.secret};case"shared-secret":return{mode:"shared-secret",secret:t.secret}}}o($E,"buildResolvedAuthConfig");function DE(e){let t=zE({policyName:e.policyName,connection:e.connection}),r=Ln(e.connection.id,t),n=$E({connection:e.connection,authMode:t,authProfileId:r}),a={displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},authProfiles:{[r]:n},transport:{baseUrl:e.connection.mcpUrl,resourceMetadataUrl:e.connection.protectedResourceMetadataUrl,requestHeaders:e.connection.requestHeaders}};return{policyName:e.policyName,upstreamServerId:e.connection.id,config:a,authMode:t,authProfileId:r,authConfig:n}}o(DE,"buildRegisteredConnection");function ME(e){let t=new Map;for(let r of e)t.has(r.name)&&Fe(`Duplicate policy name ${r.name} in policies.json.`),t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}});return t}o(ME,"buildPolicyMap");function qE(e){let t=new Map,r=new Set;for(let n of e.values()){if(!zg(n))continue;let a=os(n.handler.options,n.name);r.has(a.id)&&Fe(`Duplicate upstream MCP connection id ${a.id} in policies.json.`),r.add(a.id);let i=DE({policyName:n.name,connection:a});t.set(n.name,i)}return t}o(qE,"buildConnectionsByPolicyName");function LE(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(LE,"readOperationId");function $g(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return Dt.parse(t)}catch{Fe(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o($g,"buildPublishedCapabilityName");function al(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Fe(`MCP virtual server route ${e.routePath} declares capability ${e.capabilityName} for upstream policy ${e.authoredPolicyName}, but that policy is not bound to the route.`),e.authoredPolicyName;if(e.connections.length===1)return e.connections[0]?.policyName;Fe(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(al,"readCapabilityUpstreamPolicy");function ol(e){e.seen.has(e.key)&&Fe(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(ol,"assertUniqueCatalogKey");function jE(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=$g({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:al({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(jE,"normalizeCatalogTool");function HE(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=$g({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:al({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(HE,"normalizeCatalogPrompt");function GE(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:al({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(GE,"normalizeCatalogResource");function BE(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>jE({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>HE({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>GE({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)ol({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)ol({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let u=new Set;for(let d of a)ol({kind:"resource",key:String(d.uri),routePath:e.routePath,seen:u});return{catalogSource:t,...e.catalog.serverInfo===void 0?{}:{serverInfo:e.catalog.serverInfo},tools:r,prompts:n,resources:a}}o(BE,"normalizeVirtualServerCatalog");function FE(e){let t=new Map,r=new Set;for(let n of e.routes){let a=n.policies?.inbound??[];if(a.length===0)continue;let i=a[0],s=i===void 0?void 0:e.policyByName.get(i);if(!s||!UE(s))continue;let u=LE(n);u||Fe(`MCP virtual server route ${n.path} must declare an operationId in routes.oas.json.`),r.has(u)&&Fe(`Duplicate MCP virtual server operationId ${u} across routes.`),r.add(u);let d=NE(n.path);t.has(d)&&Fe(`Duplicate MCP virtual server id ${d} across routes.`);let p=[];for(let f of a.slice(1)){let _=e.policyByName.get(f);if(!_||!zg(_))continue;let w=e.connectionsByPolicyName.get(f);w||Fe(`Upstream connection policy ${f} referenced by route ${n.path} could not be resolved.`),p.push(w)}let l=Ug(n.handler.options),m=BE({catalog:l,connections:p,routePath:n.path});m.catalogSource==="upstream_mcp"&&p.length!==1&&Fe(`MCP virtual server route ${n.path} uses upstream MCP catalog mode but declares ${p.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(d,{virtualServerId:d,operationId:u,routePath:n.path,handlerExport:n.handler.export,serverInfo:m.serverInfo,catalog:m,connections:p})}return t}o(FE,"buildVirtualServers");function Dg(e){let t=ME(e.policies),r=qE(t),n=FE({routes:e.routes,policyByName:t,connectionsByPolicyName:r}),a=new Map;for(let i of r.values())a.set(i.upstreamServerId,i);return{byVirtualServerId:n,connectionsById:a}}o(Dg,"buildGatewayConnectionRegistry");var cs;function Mg(e){cs=e}o(Mg,"setGatewayConnectionRegistry");function yt(){if(!cs)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return cs}o(yt,"getGatewayConnectionRegistry");function qg(e){let t=yt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return t}o(qg,"getRegisteredVirtualServer");function oa(e){let t=yt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(oa,"requireRegisteredVirtualServer");function Lg(){return cs}o(Lg,"tryGetGatewayConnectionRegistry");var jg=new Vt("gateway-route");function Hg(e,t){jg.set(e,t)}o(Hg,"setGatewayRouteContext");function aa(e){return jg.get(e)}o(aa,"readGatewayRouteContext");function jn(e){let t=aa(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(jn,"requireGatewayRouteContext");var Jr="2025-06-18";var VE=new Set(["localhost","::1"]);function wt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(wt,"normalizeHostname");function Ve(e){let t=wt(e.hostname);return e.protocol==="http:"&&(VE.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(Ve,"isLoopbackHttpUrl");function de(e){return new URL(e).origin}o(de,"readGatewayRequestOrigin");import{metrics as KE,context as us,propagation as Bg,SpanKind as Fg,SpanStatusCode as il,trace as ia}from"@opentelemetry/api";var ZE="mcp-gateway",WE="mcp-gateway",JE=Jr,YE="2.0",Vg=ia.getTracer(ZE),sl=KE.getMeter(WE),XE=sl.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),QE=sl.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),ex=sl.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),tx=["traceparent","tracestate","baggage"];function cl(){return performance.now()/1e3}o(cl,"nowSeconds");function Kg(e,t){t(Math.max(cl()-e,0))}o(Kg,"recordDurationSeconds");function Gg(e){return e===void 0?void 0:String(e)}o(Gg,"stringifyAttribute");function Me(e,t,r){r!==void 0&&(e[t]=r)}o(Me,"assignAttribute");function rx(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(rx,"readTargetName");function Zg(e){let t=rx({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(Zg,"buildMcpOperationSpanName");function ul(e){let t={"mcp.method.name":e.methodName};return Me(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??YE),Me(t,"jsonrpc.request.id",Gg(e.jsonRpcRequestId)),Me(t,"mcp.protocol.version",e.mcpProtocolVersion??JE),Me(t,"mcp.session.id",e.mcpSessionId),Me(t,"mcp.resource.uri",e.resourceUri),Me(t,"rpc.response.status_code",Gg(e.rpcResponseStatusCode)),Me(t,"error.type",e.errorType),e.capabilityType==="tool"&&(Me(t,"gen_ai.operation.name","execute_tool"),Me(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&Me(t,"gen_ai.prompt.name",e.capabilityName),Me(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),Me(t,"network.protocol.version",e.networkProtocolVersion),Me(t,"network.transport",e.networkTransport),Me(t,"server.address",e.serverAddress),Me(t,"server.port",e.serverPort),Me(t,"client.address",e.clientAddress),Me(t,"client.port",e.clientPort),t}o(ul,"buildMcpOperationAttributes");function nx(e){let t=ul({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(nx,"buildMcpSessionAttributes");function Wg(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:il.ERROR}),t instanceof Error&&e.recordException(t)}o(Wg,"setSpanError");function Jg(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(Jg,"readErrorType");function ox(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?us.active():Bg.extract(us.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(ox,"readServerParentContext");function ax(e){let t=ia.getSpanContext(us.active()),r=ia.getSpanContext(e);if(!(!t||!ia.isSpanContextValid(t))&&!(r&&ia.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(ax,"readAmbientSpanLink");function Yg(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(Yg,"readResultErrorType");async function Yr(e,t){let r=cl(),n=ul({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return Vg.startActiveSpan(Zg(e),{kind:Fg.CLIENT,attributes:n},async a=>{try{let i=await t(),s=Yg(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:il.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??Jg(i);throw n["error.type"]=s,Wg(a,i,s),i}finally{Kg(r,i=>{XE.record(i,n)}),a.end()}})}o(Yr,"runMcpClientOperation");async function Xr(e,t){let r=cl(),n=ox(e.params),a=ul({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=ax(n);return Vg.startActiveSpan(Zg(e),{kind:Fg.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let u=await t(),d=Yg(u);return d&&(s.setAttribute("error.type",d),s.setStatus({code:il.ERROR}),a["error.type"]=d),u}catch(u){let d=e.errorType??Jg(u);throw a["error.type"]=d,Wg(s,u,d),u}finally{Kg(r,u=>{QE.record(u,a)}),s.end()}})}o(Xr,"runMcpServerOperation");function Xg(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return Bg.inject(us.active(),t._meta,{set(r,n,a){tx.includes(n)&&(r[n]=a)}}),t}o(Xg,"injectMcpTraceContextIntoParams");function Qg(e,t){let r=nx({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});ex.record(Math.max(t,0),r)}o(Qg,"recordMcpClientSessionDuration");var dl=new Vt("route-upstream-bindings");function ix(e){let t=dl.get(e);if(t)return t;let r={bindings:[]};return dl.set(e,r),r}o(ix,"readOrCreateRouteUpstreamBindingRegistry");function e_(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(e_,"buildRouteBindingDuplicateKey");function ll(e,t){let r=ix(e),n=e_(t);if(r.bindings.find(i=>e_(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.bindings.push(t)}o(ll,"appendResolvedUpstreamBindingContext");function t_(e){return dl.get(e)?.bindings??[]}o(t_,"readResolvedUpstreamBindingContexts");ae();var Q=c.string().datetime({offset:!0}).brand();function z(e){return Q.parse(e.toISOString())}o(z,"toIsoTimestamp");function Tt(e,t){return new Date(e.getTime()+t*1e3)}o(Tt,"addSeconds");ae();var sa=c.string().trim().min(1),ca={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},sx=c.object({issuer:c.url(),jwksUrl:c.url(),audience:sa}),cx=c.object({url:c.url(),tokenUrl:c.url().optional(),clientId:sa.optional(),clientSecret:sa.optional(),scope:sa.default("openid profile email"),audience:sa.optional(),remoteTimeoutMs:c.coerce.number().int().positive().default(1e4),stateTtlSeconds:c.coerce.number().int().positive().default(900),sessionTtlSeconds:c.coerce.number().int().positive().default(28800)}).strict(),ux=c.object({accessTokenTtlSeconds:c.coerce.number().int().positive().default(ca.accessTokenTtlSeconds),refreshTokenTtlSeconds:c.coerce.number().int().positive().default(ca.refreshTokenTtlSeconds),cimdEnabled:c.boolean().default(ca.cimdEnabled)}).strict().default(ca),dx=c.object({oidc:sx,browserLogin:cx,gateway:ux.optional().default(ca)}).strict();function r_(e){return lx(e.browserLogin.url)?"local_dev":"federated_oidc"}o(r_,"readBrowserLoginKind");function lx(e){let t;try{t=new URL(e)}catch{return!1}return Ve(t)&&t.pathname==="/oauth/dev-login"}o(lx,"isLoopbackDevLoginUrl");function ds(e){return dx.parse(e)}o(ds,"parseMcpOAuthRuntimeConfig");var pl;function n_(e){pl=e}o(n_,"setGatewayOAuthConfig");function Ee(){if(!pl)throw g("internal_server_error","MCP gateway OAuth config has not been initialized. An `mcp-oauth-inbound` policy (or a provider-specific wrapper such as `mcp-auth0-oauth-inbound`) must be registered in policies.json so the gateway can derive its OAuth runtime configuration from policy options.");return pl}o(Ee,"getGatewayOAuthConfig");function At(e){return de(e)}o(At,"readGatewayOAuthIssuer");ae();var px=43,mx=128,hx=/^[A-Za-z0-9._~-]+$/,ml="S256",Hn=c.literal(ml),ls=c.string().min(px).max(mx).regex(hx);ae();var ps=["none","client_secret_post","client_secret_basic"],fx=[...ps,"private_key_jwt"],gx=["awaiting_login","awaiting_setup"],_x=c.string().min(1).brand(),ye=c.string().min(1).brand(),kt=c.uuid().brand(),Je=c.uuid().brand(),ms=c.uuid().brand(),ua=c.enum(ps),yx=c.enum(fx),hl=c.enum(gx),o_=c.object({client_id:ye,client_name:c.string().min(1),redirect_uris:c.array(c.string().min(1)).min(1),token_endpoint_auth_method:yx.default("none")}),da=c.object({clientId:ye,clientName:c.string().min(1),redirectUris:c.array(c.string().min(1)),tokenEndpointAuthMethod:ua,hashedClientSecret:c.string().optional(),clientSecretExpiresAt:Q.optional(),clientExpiresAt:Q,revokedAt:Q.optional(),createdAt:Q}),fl=c.object({clientId:ye,resource:c.string(),virtualServerId:Se,subjectId:_x,scope:c.string(),roles:c.array(c.string()),createdAt:Q,expiresAt:Q}),a_=fl.extend({id:Je,redirectUri:c.string(),clientState:c.string().optional(),codeChallenge:c.string(),codeChallengeMethod:Hn}),la=fl.extend({id:kt,currentRefreshTokenHash:c.string().optional(),previousRefreshTokenHash:c.string().optional(),revokedAt:Q.optional(),revokedReason:c.string().optional()}),Gn=fl.extend({tokenHash:c.string(),grantId:kt,revokedAt:Q.optional()});function gl(){return Je.parse(crypto.randomUUID())}o(gl,"createDownstreamAuthorizationTransactionId");function _l(){return ms.parse(crypto.randomUUID())}o(_l,"createDownstreamBrowserLoginStateId");function yl(){return kt.parse(crypto.randomUUID())}o(yl,"createDownstreamGrantId");var ve="mcp:tools";function fs(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return Ve(r)&&Ve(n)&&wt(r.hostname)===wt(n.hostname)&&r.pathname===n.pathname&&r.search===n.search}o(fs,"redirectUriMatchesRegistration");function i_(e){return Ve(e)&&e.pathname==="/oauth/dev-login"}o(i_,"isLoopbackDevLoginUrl");function hs(e,t){return new URL(e,At(t)).toString()}o(hs,"buildGatewayOAuthUrl");function wl(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,de(e.requestUrl)).toString()}o(wl,"buildScopedAuthorizationServerIssuer");function wx(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,de(e.requestUrl)).toString()}o(wx,"buildScopedAuthorizationEndpoint");function Sl(e){let t=Ee();return{issuer:At(e),authorization_endpoint:hs("/oauth/authorize",e),token_endpoint:hs("/oauth/token",e),registration_endpoint:hs("/oauth/register",e),revocation_endpoint:hs("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ve],code_challenge_methods_supported:[ml],token_endpoint_auth_methods_supported:ps,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":r_(t)}}o(Sl,"buildAuthorizationServerMetadata");function s_(e){let t=wl(e);return{...Sl(e.requestUrl),issuer:t,authorization_endpoint:wx(e)}}o(s_,"buildScopedAuthorizationServerMetadata");async function c_(e,t){try{let r=Se.parse(e.params.virtualServerId),n=oa(r);return Response.json(Sx(n.virtualServerId,e.url))}catch(r){let n=_e(r);return _t(e,t,{code:n==="unknown_virtual_server"?n:"not_found",detail:(r instanceof Error?r.message:void 0)??"The requested protected resource metadata document was not found."})}}o(c_,"protectedResourceMetadataHandler");function Sx(e,t){return{resource:Qr(e,t),resource_name:e,authorization_servers:[wl({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ve],mcp_protocol_version:Jr}}o(Sx,"buildProtectedResourceMetadataResponseBody");function Qr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,de(t)).toString()}o(Qr,"buildCanonicalMcpResourceForVirtualServer");function u_(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,de(t)).toString()}o(u_,"buildProtectedResourceMetadataUrlForVirtualServer");import{base64url as vl}from"jose";var vx="sha256:",Rx=32;function d_(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(d_,"copyToArrayBuffer");function bx(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}o(bx,"constantTimeEqual");function nt(){let e=crypto.getRandomValues(new Uint8Array(Rx));return vl.encode(e)}o(nt,"createOpaqueToken");async function ee(e){let t=await crypto.subtle.digest("SHA-256",d_(new TextEncoder().encode(e)));return`${vx}${vl.encode(new Uint8Array(t))}`}o(ee,"hashOpaqueValue");async function l_(e){let t=await ee(e.value);return bx(t,e.expectedHash)}o(l_,"verifyOpaqueValue");async function Rl(e){let t=await crypto.subtle.digest("SHA-256",d_(new TextEncoder().encode(e)));return vl.encode(new Uint8Array(t))}o(Rl,"calculatePkceS256Challenge");ae();var Cx=c.record(c.string(),c.unknown()),p_=c.string().min(1),Ix=c.union([p_.transform(e=>[e]),c.array(p_)]),ie=c.string().min(1).brand(),Tx=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Ax=["https://zuplo.com/roles","roles","role","permissions","groups"],m_=new Vt("gateway-principal");function kx(e){let t=Cx.safeParse(e);return t.success?t.data:{}}o(kx,"toClaimRecord");function Ex(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(Ex,"readValidationFailureDetail");function xx(e,t,r){for(let i of Tx){let s=ie.safeParse(t[i]);if(s.success)return s.data}let n=ie.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",Ex(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===At(r)?n.data:ie.parse(`${a}|${n.data}`)}o(xx,"readNormalizedSubjectId");function Px(e){let t=new Set;for(let r of Ax){let n=Ix.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(Px,"readRoles");function Bn(e,t){let r=kx(e?.data),n={subjectId:xx(e,r,t)},a=Px(r);return a&&(n.roles=a),n}o(Bn,"parseGatewayPrincipal");function h_(e){let t=Cl(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(h_,"requireGatewayPrincipal");function f_(e,t){m_.set(e,t)}o(f_,"setGatewayPrincipal");function Cl(e){return m_.get(e)}o(Cl,"readGatewayPrincipal");function gs(e){let r=['realm="OAuth"',`resource_metadata="${bl(u_(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${bl(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${bl(e.scope)}"`),`Bearer ${r.join(", ")}`}o(gs,"buildGatewayBearerChallenge");function bl(e){let t="";for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);n<=31||n===127||(t+=e[r])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}o(bl,"sanitizeQuotedHeaderParameter");ae();var Il=c.string().trim().min(1),Ox=c.object({TOKEN_ENCRYPTION_KEY:Il,OAUTH_STATE_SIGNING_KEY:Il,TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING:Il.optional()}),Ux=["TOKEN_ENCRYPTION_KEY","OAUTH_STATE_SIGNING_KEY","TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING"];function Nx(e){let t=go[e];return typeof t=="string"?t:void 0}o(Nx,"readEnvValue");function zx(){let e={};for(let t of Ux){let r=Nx(t);r!==void 0&&(e[t]=r)}return e}o(zx,"readRawEnv");var Tl;function $x(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.map(String).join("."):"environment"}: ${t.message}`)}o($x,"formatZodIssues");function Dx(e){return new Ft(["Invalid MCP gateway environment configuration.","Validation failed for these environment variables:",...$x(e)].join(`
44
- `),{cause:e})}o(Dx,"createEnvValidationError");function Mx(e){let t=Ox.safeParse(e);if(!t.success)throw Dx(t.error);return t.data}o(Mx,"parseGatewayEnv");function qx(){return Tl||(Tl=Mx(zx())),Tl}o(qx,"readEnv");function _s(){return qx()}o(_s,"getEnv");ae();ae();function Lx(e){if(e instanceof Date)return e;let t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error("Expected a valid timestamp",{cause:new Error(`received: ${String(e)}`)});return t}o(Lx,"parseDate");function Ar(e,t){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(r){throw new Error(`Persisted ${t} must be valid JSON`,{cause:r})}}o(Ar,"parseJsonValue");function Al(e,t){return c.array(c.string()).parse(Ar(e,t))}o(Al,"parseStringArray");var he=c.union([c.date(),c.string()]).transform(e=>Lx(e));var jx=c.object({current_state_hash:c.string(),phase:hl,consumed_at:he.nullable(),expires_at:he}),Hx=c.object({id:kt,revoked_at:he.nullable().optional(),expires_at:he,matched:c.enum(["current","previous"])}),Gx=c.object({id:kt,matched:c.literal("current")}),Bx=c.object({client_id:ye,client_name:c.string(),redirect_uris:c.unknown(),token_endpoint_auth_method:ua,hashed_client_secret:c.string().nullable(),client_secret_expires_at:he.nullable(),client_expires_at:he,revoked_at:he.nullable(),created_at:he}).transform(e=>{let t={clientId:e.client_id,clientName:e.client_name,redirectUris:Al(e.redirect_uris,"redirect_uris"),tokenEndpointAuthMethod:e.token_endpoint_auth_method,createdAt:z(e.created_at),clientExpiresAt:z(e.client_expires_at)};return e.hashed_client_secret&&(t.hashedClientSecret=e.hashed_client_secret),e.client_secret_expires_at&&(t.clientSecretExpiresAt=z(e.client_secret_expires_at)),e.revoked_at&&(t.revokedAt=z(e.revoked_at)),da.parse(t)}),kl=c.object({id:Je,current_state_hash:c.string(),phase:hl,principal_subject_id:ie.nullable(),principal_roles:c.unknown().nullable(),client_id:ye,redirect_uri:c.string(),resource:c.string(),virtual_server_id:Se,client_state:c.string().nullable(),scope:c.string(),code_challenge:c.string(),code_challenge_method:Hn,created_at:he,expires_at:he,consumed_at:he.nullable()}).transform(e=>{let t={id:e.id,currentStateHash:e.current_state_hash,clientId:e.client_id,redirectUri:e.redirect_uri,resource:e.resource,virtualServerId:e.virtual_server_id,scope:e.scope,codeChallenge:e.code_challenge,codeChallengeMethod:e.code_challenge_method,createdAt:z(e.created_at),expiresAt:z(e.expires_at)};if(e.client_state&&(t.clientState=e.client_state),e.consumed_at&&(t.consumedAt=z(e.consumed_at)),e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal_subject_id)throw new Error("Awaiting-setup pending authorization row is missing principal.");return{...t,phase:"awaiting_setup",principal:{subjectId:e.principal_subject_id,...e.principal_roles===null?{}:{roles:c.array(c.string()).parse(Ar(e.principal_roles,"principal_roles"))}}}}),Fx=c.object({id:Je});function __(e){return{clientId:e.client_id,resource:e.resource,virtualServerId:e.virtual_server_id,subjectId:e.subject_id,scope:e.scope,roles:Al(e.roles,"roles"),createdAt:z(e.created_at),expiresAt:z(e.expires_at)}}o(__,"downstreamGrantAccessFields");var g_=c.object({id:kt,client_id:ye,resource:c.string(),virtual_server_id:Se,subject_id:ie,scope:c.string(),roles:c.unknown(),current_refresh_token_hash:c.string().nullable(),previous_refresh_token_hash:c.string().nullable(),created_at:he,expires_at:he,revoked_at:he.nullable(),revoked_reason:c.string().nullable()}).transform(e=>{let t={id:e.id,...__(e)};return e.current_refresh_token_hash&&(t.currentRefreshTokenHash=e.current_refresh_token_hash),e.previous_refresh_token_hash&&(t.previousRefreshTokenHash=e.previous_refresh_token_hash),e.revoked_at&&(t.revokedAt=z(e.revoked_at)),e.revoked_reason&&(t.revokedReason=e.revoked_reason),la.parse(t)}),Vx=c.object({token_hash:c.string(),grant_id:kt,client_id:ye,resource:c.string(),virtual_server_id:Se,subject_id:ie,scope:c.string(),roles:c.unknown(),created_at:he,expires_at:he,revoked_at:he.nullable()}).transform(e=>{let t={tokenHash:e.token_hash,grantId:e.grant_id,...__(e)};return e.revoked_at&&(t.revokedAt=z(e.revoked_at)),Gn.parse(t)});function y_(e){return[e.clientId,e.redirectUri,e.resource,e.virtualServerId,e.subjectId,e.scope,JSON.stringify(e.roles),e.codeChallenge,e.codeChallengeMethod,new Date(e.createdAt),new Date(e.expiresAt)]}o(y_,"authorizationTransactionValues");function Kx(e,t){let r=a_.parse(t);return e.query(`INSERT INTO downstream_oauth_authorization_transactions (
45
- id, client_id, redirect_uri, resource, virtual_server_id,
46
- subject_id, scope, roles, code_challenge, code_challenge_method,
47
- created_at, expires_at
48
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11, $12)`,[r.id,...y_(r)])}o(Kx,"insertAuthorizationTransaction");function Zx(e,t){return e.query(`INSERT INTO downstream_oauth_authorization_codes (
49
- code_hash, transaction_id, grant_id, client_id, redirect_uri, resource,
50
- virtual_server_id, subject_id, scope, roles,
51
- code_challenge, code_challenge_method, created_at, expires_at
52
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, $12, $13, $14)`,[t.codeHash,t.id,t.grantId,...y_(t)])}o(Zx,"insertAuthorizationCode");function Wx(e,t){return e&&!e.revokedAt?new Date(e.expiresAt).getTime()<=t.getTime()?{kind:"expired"}:void 0:{kind:"revoked"}}o(Wx,"accessTokenGrantValidationFailure");var ys=class{constructor(t){this.db=t}static{o(this,"PostgresDownstreamOAuthRepository")}async readPendingAuthorizationStatus(t){return c.array(jx).parse(await this.db.query(`SELECT current_state_hash, phase, consumed_at, expires_at
53
- FROM downstream_oauth_pending_authorization_transactions
54
- WHERE id = $1
55
- LIMIT 1`,[t]))[0]}async readPendingAuthorizationAdvanceFailure(t){let r=await this.readPendingAuthorizationStatus(t.id);return r?r.consumed_at?{kind:"consumed"}:new Date(r.expires_at).getTime()<=t.now.getTime()?{kind:"expired"}:r.current_state_hash!==t.currentStateHash?{kind:"stale_hash"}:r.phase!==t.expectedPhase?{kind:"wrong_phase",current:r.phase}:{kind:"stale_hash"}:{kind:"missing"}}async readPendingAuthorizationConsumeFailure(t){let r=await this.readPendingAuthorizationStatus(t.id);return r?r.consumed_at?{kind:"consumed_already"}:new Date(r.expires_at).getTime()<=t.now.getTime()?{kind:"expired"}:r.current_state_hash!==t.currentStateHash?{kind:"stale_hash"}:{kind:"stale_hash"}:{kind:"missing"}}async getDcrClient(t){return c.array(Bx).parse(await this.db.query(`SELECT
56
- client_id,
57
- client_name,
58
- redirect_uris,
59
- token_endpoint_auth_method,
60
- hashed_client_secret,
61
- client_secret_expires_at,
62
- client_expires_at,
63
- revoked_at,
64
- created_at
65
- FROM downstream_oauth_dcr_clients
66
- WHERE client_id = $1
67
- AND revoked_at IS NULL
68
- AND client_expires_at > NOW()
69
- LIMIT 1`,[t]))[0]}async saveDcrClient(t){await this.db.query(`INSERT INTO downstream_oauth_dcr_clients (
70
- client_id,
71
- client_name,
72
- redirect_uris,
73
- token_endpoint_auth_method,
74
- hashed_client_secret,
75
- client_secret_expires_at,
76
- client_expires_at,
77
- revoked_at,
78
- created_at
79
- ) VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7, $8, $9)`,[t.clientId,t.clientName,JSON.stringify(t.redirectUris),t.tokenEndpointAuthMethod,t.hashedClientSecret??null,t.clientSecretExpiresAt?new Date(t.clientSecretExpiresAt):null,new Date(t.clientExpiresAt),t.revokedAt?new Date(t.revokedAt):null,new Date(t.createdAt)])}async savePendingAuthorizationTransaction(t){return c.array(Fx).parse(await this.db.query(`INSERT INTO downstream_oauth_pending_authorization_transactions (
80
- id, current_state_hash, phase, principal_subject_id,
81
- principal_roles, client_id, redirect_uri,
82
- resource, virtual_server_id, client_state, scope, code_challenge,
83
- code_challenge_method, created_at, expires_at, consumed_at
84
- ) VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
85
- ON CONFLICT (id) DO NOTHING
86
- RETURNING id`,[t.id,t.currentStateHash,t.phase,t.phase==="awaiting_setup"?t.principal.subjectId:null,t.phase==="awaiting_setup"&&t.principal.roles!==void 0?JSON.stringify(t.principal.roles):null,t.clientId,t.redirectUri,t.resource,t.virtualServerId,t.clientState??null,t.scope,t.codeChallenge,t.codeChallengeMethod,new Date(t.createdAt),new Date(t.expiresAt),t.consumedAt?new Date(t.consumedAt):null])).length>0?{kind:"saved"}:{kind:"already_exists"}}async advancePendingAuthorizationTransaction(t){let n=c.array(kl).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
87
- SET current_state_hash = $4,
88
- phase = $5,
89
- principal_subject_id = $6,
90
- principal_roles = $7::jsonb
91
- WHERE id = $1
92
- AND current_state_hash = $2
93
- AND phase = $3
94
- AND consumed_at IS NULL
95
- AND expires_at > $8
96
- RETURNING *`,[t.id,t.currentStateHash,t.expectedPhase,t.nextStateHash,t.nextPhase,t.principal.subjectId,t.principal.roles===void 0?null:JSON.stringify(t.principal.roles),t.now]))[0];return n?{kind:"advanced",record:n}:this.readPendingAuthorizationAdvanceFailure(t)}async getPendingAuthorizationTransaction(t){let n=c.array(kl).parse(await this.db.query(`SELECT *
97
- FROM downstream_oauth_pending_authorization_transactions
98
- WHERE id = $1
99
- LIMIT 1`,[t.id]))[0];return n?n.consumedAt?{kind:"consumed"}:new Date(n.expiresAt).getTime()<=t.now.getTime()?{kind:"expired"}:n.currentStateHash!==t.currentStateHash?{kind:"stale_hash"}:{kind:"available",record:n}:{kind:"missing"}}async consumePendingAuthorizationTransaction(t){let n=c.array(kl).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
100
- SET consumed_at = $3
101
- WHERE id = $1
102
- AND current_state_hash = $2
103
- AND consumed_at IS NULL
104
- AND expires_at > $3
105
- RETURNING *`,[t.id,t.currentStateHash,t.now]))[0];return n?{kind:"consumed",record:n}:this.readPendingAuthorizationConsumeFailure(t)}async issueAuthorizationCode(t){await this.db.transaction(r=>[Kx(r,t),Zx(r,t)])}async exchangeAuthorizationCode(t){let n=c.array(c.object({redirect_uri:c.string()})).parse(await this.db.query(`SELECT redirect_uri
106
- FROM downstream_oauth_authorization_codes
107
- WHERE code_hash = $1
108
- LIMIT 1`,[t.codeHash]))[0]?.redirect_uri,a=n!==void 0&&fs(n,t.redirectUri)?n:t.redirectUri,s=c.array(c.record(c.string(),c.unknown())).parse(await this.db.query(`WITH candidate AS (
109
- SELECT *
110
- FROM downstream_oauth_authorization_codes
111
- WHERE code_hash = $1
112
- LIMIT 1
113
- ),
114
- claimed AS (
115
- UPDATE downstream_oauth_authorization_codes
116
- SET consumed_at = $8
117
- WHERE code_hash = $1
118
- AND consumed_at IS NULL
119
- AND expires_at > $8
120
- AND client_id = $2
121
- AND redirect_uri = $3
122
- AND ($4::text IS NULL OR resource = $4)
123
- AND code_challenge = $5
124
- RETURNING *
125
- ),
126
- replayed_grant AS (
127
- UPDATE downstream_oauth_grants AS grants
128
- SET revoked_at = $8,
129
- revoked_reason = 'authorization_code_replay'
130
- FROM candidate
131
- WHERE candidate.consumed_at IS NOT NULL
132
- AND grants.id = candidate.grant_id
133
- AND grants.revoked_at IS NULL
134
- RETURNING grants.id
135
- ),
136
- replayed_access AS (
137
- UPDATE downstream_oauth_access_tokens AS access_tokens
138
- SET revoked_at = $8
139
- FROM candidate
140
- WHERE candidate.consumed_at IS NOT NULL
141
- AND access_tokens.grant_id = candidate.grant_id
142
- AND access_tokens.revoked_at IS NULL
143
- RETURNING access_tokens.token_hash
144
- ),
145
- replayed_code AS (
146
- UPDATE downstream_oauth_authorization_codes AS codes
147
- SET replayed_at = COALESCE(codes.replayed_at, $8)
148
- FROM candidate
149
- WHERE candidate.consumed_at IS NOT NULL
150
- AND codes.code_hash = candidate.code_hash
151
- RETURNING codes.code_hash
152
- ),
153
- inserted_grant AS (
154
- INSERT INTO downstream_oauth_grants (
155
- id, client_id, resource, virtual_server_id, subject_id,
156
- scope, roles, current_refresh_token_hash, previous_refresh_token_hash,
157
- created_at, expires_at, revoked_at, revoked_reason
158
- )
159
- SELECT
160
- grant_id, client_id, resource, virtual_server_id,
161
- subject_id, scope, roles, $6, NULL, $8, $9, NULL, NULL
162
- FROM claimed
163
- RETURNING *
164
- ),
165
- revoked_prior_grants AS (
166
- UPDATE downstream_oauth_grants AS grants
167
- SET revoked_at = $8,
168
- revoked_reason = 'reauthorized'
169
- FROM inserted_grant
170
- WHERE grants.subject_id = inserted_grant.subject_id
171
- AND grants.client_id = inserted_grant.client_id
172
- AND grants.resource = inserted_grant.resource
173
- AND grants.id <> inserted_grant.id
174
- AND grants.revoked_at IS NULL
175
- RETURNING grants.id
176
- ),
177
- revoked_prior_access AS (
178
- UPDATE downstream_oauth_access_tokens AS access_tokens
179
- SET revoked_at = $8
180
- FROM revoked_prior_grants
181
- WHERE access_tokens.grant_id = revoked_prior_grants.id
182
- AND access_tokens.revoked_at IS NULL
183
- RETURNING access_tokens.token_hash
184
- ),
185
- inserted_access AS (
186
- INSERT INTO downstream_oauth_access_tokens (
187
- token_hash, grant_id, client_id, resource, virtual_server_id,
188
- subject_id, scope, roles, created_at, expires_at,
189
- revoked_at
190
- )
191
- SELECT
192
- $7, id, client_id, resource, virtual_server_id,
193
- subject_id, scope, roles, $8, $10, NULL
194
- FROM inserted_grant
195
- RETURNING token_hash
196
- )
197
- SELECT
198
- CASE
199
- WHEN EXISTS (SELECT 1 FROM inserted_grant) THEN 'exchanged'
200
- WHEN NOT EXISTS (SELECT 1 FROM candidate) THEN 'missing'
201
- WHEN (SELECT consumed_at FROM candidate) IS NOT NULL THEN 'consumed'
202
- WHEN (SELECT expires_at FROM candidate) <= $8 THEN 'expired'
203
- WHEN (SELECT client_id FROM candidate) = $2
204
- AND (SELECT redirect_uri FROM candidate) = $3
205
- AND (SELECT code_challenge FROM candidate) = $5
206
- AND $4::text IS NOT NULL
207
- AND (SELECT resource FROM candidate) <> $4
208
- THEN 'resource_mismatch'
209
- ELSE 'binding_mismatch'
210
- END AS kind,
211
- inserted_grant.*
212
- FROM (SELECT 1) AS marker
213
- LEFT JOIN inserted_grant ON TRUE`,[t.codeHash,t.clientId,a,t.resource,t.codeChallenge,t.currentRefreshTokenHash,t.accessTokenHash,t.now,new Date(t.grantExpiresAt),new Date(t.accessTokenExpiresAt)]))[0],u=c.enum(["exchanged","consumed","missing","expired","resource_mismatch","binding_mismatch"]).parse(s?.kind??"missing");return u!=="exchanged"?{kind:u}:{kind:"exchanged",grant:g_.parse(s)}}async getGrant(t){return c.array(g_).parse(await this.db.query(`SELECT *
214
- FROM downstream_oauth_grants
215
- WHERE id = $1
216
- LIMIT 1`,[t]))[0]}async saveAccessToken(t){await this.db.query(`INSERT INTO downstream_oauth_access_tokens (
217
- token_hash, grant_id, client_id, resource, virtual_server_id,
218
- subject_id, scope, roles, created_at, expires_at, revoked_at
219
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11)`,[t.tokenHash,t.grantId,t.clientId,t.resource,t.virtualServerId,t.subjectId,t.scope,JSON.stringify(t.roles),new Date(t.createdAt),new Date(t.expiresAt),t.revokedAt?new Date(t.revokedAt):null])}async validateAccessToken(t){let n=c.array(Vx).parse(await this.db.query(`SELECT access_tokens.*
220
- FROM downstream_oauth_access_tokens AS access_tokens
221
- JOIN downstream_oauth_grants AS grants
222
- ON grants.id = access_tokens.grant_id
223
- WHERE access_tokens.token_hash = $1
224
- LIMIT 1`,[t.tokenHash]))[0];if(!n)return{kind:"missing"};if(n.revokedAt)return{kind:"revoked"};if(new Date(n.expiresAt).getTime()<=t.now.getTime())return{kind:"expired"};let a=await this.getGrant(n.grantId),i=Wx(a,t.now);return i||{kind:"valid",record:n}}async rotateRefreshToken(t){let r=await this.rotateCurrentRefreshToken(t);if(!r)return this.resolveUnrotatedRefreshToken(t);let n=await this.getGrant(r.id);return n?{kind:"rotated",grant:n,matched:r.matched}:{kind:"missing"}}async rotateCurrentRefreshToken(t){return c.array(Gx).parse(await this.db.query(`WITH candidate AS (
225
- SELECT id,
226
- 'current' AS matched
227
- FROM downstream_oauth_grants
228
- WHERE client_id = $3
229
- AND revoked_at IS NULL
230
- AND expires_at > $4
231
- AND ($5::text IS NULL OR resource = $5)
232
- AND current_refresh_token_hash = $1
233
- ORDER BY created_at DESC
234
- LIMIT 1
235
- )
236
- UPDATE downstream_oauth_grants AS grants
237
- SET previous_refresh_token_hash = $1,
238
- current_refresh_token_hash = $2
239
- FROM candidate
240
- WHERE grants.id = candidate.id
241
- AND grants.client_id = $3
242
- AND grants.revoked_at IS NULL
243
- AND grants.expires_at > $4
244
- AND ($5::text IS NULL OR grants.resource = $5)
245
- AND grants.current_refresh_token_hash = $1
246
- RETURNING grants.*, candidate.matched`,[t.currentTokenHash,t.nextTokenHash,t.clientId,t.now,t.resource??null]))[0]}async resolveUnrotatedRefreshToken(t){let r=await this.findRefreshTokenGrantStatus(t,!0),n=await this.refreshTokenGrantFailure(t,r);if(n)return n;if(r)return{kind:"missing"};let a=await this.findRefreshTokenGrantStatus(t,!1),i=await this.refreshTokenGrantFailure(t,a);return i||(a&&t.resource!==void 0?{kind:"resource_mismatch"}:{kind:"missing"})}async findRefreshTokenGrantStatus(t,r){let n=r?"AND ($3::text IS NULL OR resource = $3)":"",a=r?[t.clientId,t.currentTokenHash,t.resource??null]:[t.clientId,t.currentTokenHash];return c.array(Hx).parse(await this.db.query(`SELECT id,
247
- revoked_at,
248
- expires_at,
249
- CASE
250
- WHEN current_refresh_token_hash = $2 THEN 'current'
251
- ELSE 'previous'
252
- END AS matched
253
- FROM downstream_oauth_grants
254
- WHERE client_id = $1
255
- ${n}
256
- AND (
257
- current_refresh_token_hash = $2
258
- OR previous_refresh_token_hash = $2
259
- )
260
- LIMIT 1`,a))[0]}async refreshTokenGrantFailure(t,r){if(r){if(r.revoked_at)return{kind:"revoked"};if(r.expires_at.getTime()<=t.now.getTime())return{kind:"expired"};if(r.matched==="previous")return await this.revokeGrant({grantId:r.id,now:t.now,reason:"refresh_token_replay"}),{kind:"revoked"}}}async revokeOAuthToken(t){let n=c.array(c.object({token_hash:c.string(),client_id:ye})).parse(await this.db.query(`SELECT token_hash, client_id
261
- FROM downstream_oauth_access_tokens
262
- WHERE token_hash = $1
263
- LIMIT 1`,[t.tokenHash]))[0];if(n)return n.client_id!==t.clientId?{kind:"client_mismatch"}:(await this.db.query(`UPDATE downstream_oauth_access_tokens
264
- SET revoked_at = $2
265
- WHERE token_hash = $1 AND revoked_at IS NULL`,[t.tokenHash,t.now]),{kind:"revoked_access_token"});let i=c.array(c.object({id:kt,client_id:ye})).parse(await this.db.query(`SELECT id, client_id
266
- FROM downstream_oauth_grants
267
- WHERE current_refresh_token_hash = $1
268
- OR previous_refresh_token_hash = $1
269
- ORDER BY created_at DESC
270
- LIMIT 1`,[t.tokenHash]))[0];return i?this.revokeRefreshTokenGrantForOAuthToken(t,i):{kind:"missing"}}async revokeRefreshTokenGrantForOAuthToken(t,r){return r.client_id!==t.clientId?{kind:"client_mismatch"}:this.revokeGrantForOAuthToken(t,r.id)}async revokeGrantForOAuthToken(t,r){return await this.revokeGrant({grantId:r,now:t.now,reason:"token_revocation"}),{kind:"revoked_grant"}}async revokeGrant(t){await this.db.transaction(r=>[r.query(`UPDATE downstream_oauth_grants
271
- SET revoked_at = $2,
272
- revoked_reason = $3
273
- WHERE id = $1 AND revoked_at IS NULL`,[t.grantId,t.now,t.reason]),r.query(`UPDATE downstream_oauth_access_tokens
274
- SET revoked_at = $2
275
- WHERE grant_id = $1 AND revoked_at IS NULL`,[t.grantId,t.now])])}};var ws=class{constructor(t,r){this.raw=t;this.singleShotExecutor=r}static{o(this,"HttpPgQuery")}[Symbol.toStringTag]="HttpPgQuery";then(t,r){return this.singleShotExecutor(this.raw).then(t,r)}catch(t){return this.singleShotExecutor(this.raw).catch(t)}finally(t){return this.singleShotExecutor(this.raw).finally(t)}};function Jx(e){return e instanceof ws}o(Jx,"isHttpPgQuery");function Yx(e){let t;try{t=new URL(e)}catch(n){throw new Error("Database connection string is not a valid URL. Expected: postgresql://user:password@host.tld/dbname",{cause:n})}if(t.protocol!=="postgresql:"&&t.protocol!=="postgres:")throw g("internal_server_error",`Database connection string must use postgres:// or postgresql:// (got ${t.protocol})`);if(!t.hostname)throw g("internal_server_error","Database connection string is missing the host.");let r=t.hostname.replace(/^[^.]+\./,"api.");return{host:t.hostname,fetchEndpoint:`https://${r}/sql`}}o(Yx,"parseConnectionString");function Xx(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"?e.message??"Unknown postgres error":"Unknown postgres error"}o(Xx,"readErrorMessage");function Qx(e){return typeof e=="object"&&e!==null&&Array.isArray(e.rows)}o(Qx,"isSingleResponse");function eP(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}o(eP,"isBatchResponse");function w_(e,t={}){let{fetchEndpoint:r}=Yx(e),n=t.fetchFn??fetch;async function a(d){let p=await i({query:d.query,params:d.params});if(!Qx(p))throw g("internal_server_error","Unexpected postgres response shape: missing `rows`.");return p.rows}o(a,"runSingle");async function i(d){let p=await n(r,{method:"POST",headers:{"content-type":"application/json","Neon-Connection-String":e,"Neon-Raw-Text-Output":"true"},body:JSON.stringify(d)});if(!p.ok){let l;try{l=await p.json()}catch{l=void 0}let m=new Error(Xx(l));throw g({code:"internal_server_error",privateDetail:`Postgres HTTP request failed (status ${p.status})`,cause:m})}return p.json()}o(i,"runRequest");function s(){return{query(d,p){return new ws({query:d,params:p??[]},a)}}}o(s,"buildQueryDatabase");let u=s();return{query:u.query,async transaction(d){let l=d(u).map((f,_)=>{if(!Jx(f))throw new Error(`transaction callback returned an unexpected query operation at index ${_}. Each statement must be a direct \`db.query(...)\` call (do not \`await\` inside the callback).`);return f.raw}),m=await i({queries:l.map(f=>({query:f.query,params:f.params}))});if(!eP(m))throw new Error("Unexpected postgres response shape: missing `results` for transaction.");return m.results.map(f=>f.rows)}}}o(w_,"createHttpPostgresGatewayDatabase");var tP=`
276
- DO $$
277
- BEGIN
278
- IF to_regclass('public.downstream_oauth_pending_authorization_transactions') IS NULL THEN
279
- -- Fresh DB: 0000_messy_makkari created the right shape already.
280
- RETURN;
281
- END IF;
282
-
283
- -- Old prototype shape (0000_narrow_cerise) used login_state_hash as part of
284
- -- a composite PK. 0004_famous_mastermind renamed it. If we still have the old
285
- -- column name, rename it instead of creating a new column so existing rows
286
- -- (and any prototype data) survive.
287
- IF EXISTS (
288
- SELECT 1
289
- FROM information_schema.columns
290
- WHERE table_schema = 'public'
291
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
292
- AND column_name = 'login_state_hash'
293
- ) AND NOT EXISTS (
294
- SELECT 1
295
- FROM information_schema.columns
296
- WHERE table_schema = 'public'
297
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
298
- AND column_name = 'current_state_hash'
299
- ) THEN
300
- -- 0004_famous_mastermind unconditionally truncated the table on rename
301
- -- because the principal/phase columns are NOT NULL on the new shape and
302
- -- there is no sane backfill. We mirror that here.
303
- EXECUTE 'TRUNCATE TABLE public.downstream_oauth_pending_authorization_transactions';
304
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions RENAME COLUMN login_state_hash TO current_state_hash';
305
- END IF;
306
-
307
- -- If neither column exists, we are in the rewritten-0000_messy_makkari case
308
- -- where the prototype edited the migration after applying it, leaving the
309
- -- column out entirely. Add it (NOT NULL); the table is dev-only so any rows
310
- -- that violate it are fine to drop.
311
- IF NOT EXISTS (
312
- SELECT 1
313
- FROM information_schema.columns
314
- WHERE table_schema = 'public'
315
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
316
- AND column_name = 'current_state_hash'
317
- ) THEN
318
- EXECUTE 'TRUNCATE TABLE public.downstream_oauth_pending_authorization_transactions';
319
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD COLUMN current_state_hash text NOT NULL';
320
- END IF;
321
-
322
- -- Composite PK (id, login_state_hash) -> single-column PK (id).
323
- IF EXISTS (
324
- SELECT 1
325
- FROM pg_constraint
326
- WHERE conname = 'downstream_oauth_pending_authorization_transactions_id_login_state_hash_pk'
327
- ) THEN
328
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions DROP CONSTRAINT downstream_oauth_pending_authorization_transactions_id_login_state_hash_pk';
329
- END IF;
330
-
331
- IF NOT EXISTS (
332
- SELECT 1
333
- FROM pg_constraint
334
- WHERE conname = 'downstream_oauth_pending_authorization_transactions_id_pk'
335
- ) THEN
336
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_transactions_id_pk PRIMARY KEY (id)';
337
- END IF;
338
-
339
- -- 0004_famous_mastermind columns.
340
- IF NOT EXISTS (
341
- SELECT 1
342
- FROM information_schema.columns
343
- WHERE table_schema = 'public'
344
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
345
- AND column_name = 'phase'
346
- ) THEN
347
- EXECUTE 'TRUNCATE TABLE public.downstream_oauth_pending_authorization_transactions';
348
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD COLUMN phase text NOT NULL';
349
- END IF;
350
-
351
- IF NOT EXISTS (
352
- SELECT 1
353
- FROM information_schema.columns
354
- WHERE table_schema = 'public'
355
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
356
- AND column_name = 'principal_subject_id'
357
- ) THEN
358
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD COLUMN principal_subject_id text';
359
- END IF;
360
-
361
- IF NOT EXISTS (
362
- SELECT 1
363
- FROM information_schema.columns
364
- WHERE table_schema = 'public'
365
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
366
- AND column_name = 'principal_tenant_id'
367
- ) THEN
368
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD COLUMN principal_tenant_id text';
369
- END IF;
370
-
371
- IF NOT EXISTS (
372
- SELECT 1
373
- FROM information_schema.columns
374
- WHERE table_schema = 'public'
375
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
376
- AND column_name = 'principal_roles'
377
- ) THEN
378
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD COLUMN principal_roles jsonb';
379
- END IF;
380
-
381
- -- UNIQUE on current_state_hash.
382
- IF NOT EXISTS (
383
- SELECT 1
384
- FROM pg_constraint
385
- WHERE conname = 'downstream_oauth_pending_authorization_current_state_hash_unique'
386
- ) THEN
387
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_current_state_hash_unique UNIQUE (current_state_hash)';
388
- END IF;
389
-
390
- -- CHECK constraints from 0004_famous_mastermind.
391
- IF NOT EXISTS (
392
- SELECT 1
393
- FROM pg_constraint
394
- WHERE conname = 'downstream_oauth_pending_authorization_phase_check'
395
- ) THEN
396
- EXECUTE $check$ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_phase_check CHECK ("downstream_oauth_pending_authorization_transactions"."phase" IN ('awaiting_login', 'awaiting_setup'))$check$;
397
- END IF;
398
-
399
- IF NOT EXISTS (
400
- SELECT 1
401
- FROM pg_constraint
402
- WHERE conname = 'downstream_oauth_pending_authorization_phase_principal_check'
403
- ) THEN
404
- EXECUTE $check$ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_phase_principal_check CHECK ((
405
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_login'
406
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NULL
407
- AND "downstream_oauth_pending_authorization_transactions"."principal_tenant_id" IS NULL
408
- AND "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
409
- ) OR (
410
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_setup'
411
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NOT NULL
412
- AND "downstream_oauth_pending_authorization_transactions"."principal_tenant_id" IS NOT NULL
413
- AND (
414
- "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
415
- OR jsonb_typeof("downstream_oauth_pending_authorization_transactions"."principal_roles") = 'array'
416
- )
417
- ))$check$;
418
- END IF;
419
-
420
- IF NOT EXISTS (
421
- SELECT 1
422
- FROM pg_constraint
423
- WHERE conname = 'downstream_oauth_pending_authorization_code_challenge_method_check'
424
- ) THEN
425
- EXECUTE $check$ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_code_challenge_method_check CHECK ("downstream_oauth_pending_authorization_transactions"."code_challenge_method" = 'S256')$check$;
426
- END IF;
427
- END $$;
428
- `,rP=`
429
- DROP INDEX IF EXISTS public.downstream_oauth_cimd_metadata_cache_expiry_idx;
430
- `,nP=`
431
- DROP TABLE IF EXISTS public.downstream_oauth_cimd_metadata_cache;
432
- `,oP=`
433
- DO $$
434
- BEGIN
435
- IF to_regclass('public.upstream_connections') IS NULL THEN
436
- RETURN;
437
- END IF;
438
-
439
- IF EXISTS (
440
- SELECT 1
441
- FROM pg_constraint
442
- WHERE conname = 'upstream_connections_owner_shape_check'
443
- ) THEN
444
- EXECUTE 'ALTER TABLE public.upstream_connections DROP CONSTRAINT upstream_connections_owner_shape_check';
445
- END IF;
446
-
447
- EXECUTE $check$ALTER TABLE public.upstream_connections ADD CONSTRAINT upstream_connections_owner_shape_check CHECK (("upstream_connections"."owner_mode" = 'user' AND "upstream_connections"."tenant_id" IS NOT NULL AND "upstream_connections"."user_id" IS NOT NULL)
448
- OR ("upstream_connections"."owner_mode" = 'tenant_shared' AND "upstream_connections"."tenant_id" IS NOT NULL AND "upstream_connections"."user_id" IS NULL))$check$;
449
- END $$;
450
- `,aP=[tP,rP,nP,oP].join(`
451
- --> statement-breakpoint
452
- `),iP=`
453
- DO $$
454
- BEGIN
455
- IF to_regclass('public.upstream_connections') IS NULL THEN
456
- RETURN;
457
- END IF;
458
-
459
- IF EXISTS (
460
- SELECT 1
461
- FROM information_schema.columns
462
- WHERE table_schema = 'public'
463
- AND table_name = 'upstream_connections'
464
- AND column_name = 'id'
465
- AND data_type = 'uuid'
466
- ) THEN
467
- EXECUTE 'ALTER TABLE public.upstream_connections ALTER COLUMN id TYPE text USING id::text';
468
- END IF;
469
- END $$;
470
- `,sP=`
471
- DO $$
472
- BEGIN
473
- -- upstream_connections: drop CHECK + UNIQUE constraints that reference the
474
- -- legacy tenant_id column or the legacy owner_mode='tenant_shared' value
475
- -- before we rewrite rows. Without dropping owner_mode_check first, the
476
- -- UPDATE below would violate it.
477
- IF EXISTS (
478
- SELECT 1 FROM pg_constraint
479
- WHERE conname = 'upstream_connections_owner_shape_check'
480
- ) THEN
481
- EXECUTE 'ALTER TABLE public.upstream_connections DROP CONSTRAINT upstream_connections_owner_shape_check';
482
- END IF;
483
-
484
- IF EXISTS (
485
- SELECT 1 FROM pg_constraint
486
- WHERE conname = 'upstream_connections_owner_mode_check'
487
- ) THEN
488
- EXECUTE 'ALTER TABLE public.upstream_connections DROP CONSTRAINT upstream_connections_owner_mode_check';
489
- END IF;
490
-
491
- IF EXISTS (
492
- SELECT 1 FROM pg_constraint
493
- WHERE conname = 'upstream_connections_owner_key'
494
- ) THEN
495
- EXECUTE 'ALTER TABLE public.upstream_connections DROP CONSTRAINT upstream_connections_owner_key';
496
- END IF;
497
-
498
- -- Migrate persisted row values to the new naming before we re-add the
499
- -- CHECK constraints. owner_mode tenant_shared becomes shared; auth_profile_id
500
- -- suffixes :tenant_shared_oauth become :shared-oauth,
501
- -- :tenant_static_secret become :shared-secret,
502
- -- :user_static_secret become :user-secret.
503
- IF EXISTS (
504
- SELECT 1
505
- FROM information_schema.tables
506
- WHERE table_schema = 'public'
507
- AND table_name = 'upstream_connections'
508
- ) THEN
509
- EXECUTE $upd$UPDATE public.upstream_connections SET owner_mode = 'shared' WHERE owner_mode = 'tenant_shared'$upd$;
510
- EXECUTE $upd$UPDATE public.upstream_connections SET auth_profile_id = REPLACE(auth_profile_id, ':tenant_shared_oauth', ':shared-oauth') WHERE auth_profile_id LIKE '%:tenant_shared_oauth'$upd$;
511
- EXECUTE $upd$UPDATE public.upstream_connections SET auth_profile_id = REPLACE(auth_profile_id, ':tenant_static_secret', ':shared-secret') WHERE auth_profile_id LIKE '%:tenant_static_secret'$upd$;
512
- EXECUTE $upd$UPDATE public.upstream_connections SET auth_profile_id = REPLACE(auth_profile_id, ':user_static_secret', ':user-secret') WHERE auth_profile_id LIKE '%:user_static_secret'$upd$;
513
- END IF;
514
-
515
- IF EXISTS (
516
- SELECT 1
517
- FROM information_schema.columns
518
- WHERE table_schema = 'public'
519
- AND table_name = 'upstream_connections'
520
- AND column_name = 'tenant_id'
521
- ) THEN
522
- EXECUTE 'ALTER TABLE public.upstream_connections DROP COLUMN tenant_id';
523
- END IF;
524
-
525
- EXECUTE $check$ALTER TABLE public.upstream_connections ADD CONSTRAINT upstream_connections_owner_mode_check CHECK ("upstream_connections"."owner_mode" IN ('user', 'shared'))$check$;
526
-
527
- EXECUTE $check$ALTER TABLE public.upstream_connections ADD CONSTRAINT upstream_connections_owner_shape_check CHECK (("upstream_connections"."owner_mode" = 'user' AND "upstream_connections"."user_id" IS NOT NULL)
528
- OR ("upstream_connections"."owner_mode" = 'shared' AND "upstream_connections"."user_id" IS NULL))$check$;
529
-
530
- EXECUTE 'ALTER TABLE public.upstream_connections ADD CONSTRAINT upstream_connections_owner_key UNIQUE NULLS NOT DISTINCT ("owner_mode","user_id","upstream_server_id","auth_profile_id")';
531
-
532
- -- downstream_oauth_pending_authorization_transactions: drop phase_principal_check + principal_tenant_id column
533
- IF EXISTS (
534
- SELECT 1 FROM pg_constraint
535
- WHERE conname = 'downstream_oauth_pending_authorization_phase_principal_check'
536
- ) THEN
537
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions DROP CONSTRAINT downstream_oauth_pending_authorization_phase_principal_check';
538
- END IF;
539
-
540
- IF EXISTS (
541
- SELECT 1
542
- FROM information_schema.columns
543
- WHERE table_schema = 'public'
544
- AND table_name = 'downstream_oauth_pending_authorization_transactions'
545
- AND column_name = 'principal_tenant_id'
546
- ) THEN
547
- EXECUTE 'ALTER TABLE public.downstream_oauth_pending_authorization_transactions DROP COLUMN principal_tenant_id';
548
- END IF;
549
-
550
- EXECUTE $check$ALTER TABLE public.downstream_oauth_pending_authorization_transactions ADD CONSTRAINT downstream_oauth_pending_authorization_phase_principal_check CHECK ((
551
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_login'
552
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NULL
553
- AND "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
554
- ) OR (
555
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_setup'
556
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NOT NULL
557
- AND (
558
- "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
559
- OR jsonb_typeof("downstream_oauth_pending_authorization_transactions"."principal_roles") = 'array'
560
- )
561
- ))$check$;
562
-
563
- -- downstream_oauth_grants: drop index referencing tenant_id, then drop the column
564
- EXECUTE 'DROP INDEX IF EXISTS public.downstream_oauth_grants_subject_client_resource_idx';
565
-
566
- IF EXISTS (
567
- SELECT 1
568
- FROM information_schema.columns
569
- WHERE table_schema = 'public'
570
- AND table_name = 'downstream_oauth_grants'
571
- AND column_name = 'tenant_id'
572
- ) THEN
573
- EXECUTE 'ALTER TABLE public.downstream_oauth_grants DROP COLUMN tenant_id';
574
- END IF;
575
-
576
- EXECUTE 'CREATE INDEX "downstream_oauth_grants_subject_client_resource_idx" ON "downstream_oauth_grants" USING btree ("subject_id","client_id","resource") WHERE "downstream_oauth_grants"."revoked_at" IS NULL';
577
-
578
- -- downstream_oauth_access_tokens: drop tenant_id column
579
- IF EXISTS (
580
- SELECT 1
581
- FROM information_schema.columns
582
- WHERE table_schema = 'public'
583
- AND table_name = 'downstream_oauth_access_tokens'
584
- AND column_name = 'tenant_id'
585
- ) THEN
586
- EXECUTE 'ALTER TABLE public.downstream_oauth_access_tokens DROP COLUMN tenant_id';
587
- END IF;
588
-
589
- -- downstream_oauth_authorization_codes: drop tenant_id column
590
- IF EXISTS (
591
- SELECT 1
592
- FROM information_schema.columns
593
- WHERE table_schema = 'public'
594
- AND table_name = 'downstream_oauth_authorization_codes'
595
- AND column_name = 'tenant_id'
596
- ) THEN
597
- EXECUTE 'ALTER TABLE public.downstream_oauth_authorization_codes DROP COLUMN tenant_id';
598
- END IF;
599
-
600
- -- downstream_oauth_authorization_transactions: drop tenant_id column
601
- IF EXISTS (
602
- SELECT 1
603
- FROM information_schema.columns
604
- WHERE table_schema = 'public'
605
- AND table_name = 'downstream_oauth_authorization_transactions'
606
- AND column_name = 'tenant_id'
607
- ) THEN
608
- EXECUTE 'ALTER TABLE public.downstream_oauth_authorization_transactions DROP COLUMN tenant_id';
609
- END IF;
610
- END $$;
611
- `,S_=[{tag:"0000_messy_makkari",sql:`CREATE TABLE "browser_connect_ticket_consumptions" (
612
- "id" uuid PRIMARY KEY NOT NULL,
613
- "consumed_at" timestamp with time zone NOT NULL,
614
- "expires_at" timestamp with time zone NOT NULL
615
- );
616
- --> statement-breakpoint
617
- CREATE TABLE "downstream_oauth_access_tokens" (
618
- "token_hash" text PRIMARY KEY NOT NULL,
619
- "grant_id" uuid NOT NULL,
620
- "client_id" text NOT NULL,
621
- "resource" text NOT NULL,
622
- "virtual_server_id" text NOT NULL,
623
- "tenant_id" text NOT NULL,
624
- "subject_id" text NOT NULL,
625
- "scope" text NOT NULL,
626
- "roles" jsonb NOT NULL,
627
- "created_at" timestamp with time zone NOT NULL,
628
- "expires_at" timestamp with time zone NOT NULL,
629
- "revoked_at" timestamp with time zone,
630
- CONSTRAINT "downstream_oauth_access_tokens_roles_array_check" CHECK (jsonb_typeof("downstream_oauth_access_tokens"."roles") = 'array')
631
- );
632
- --> statement-breakpoint
633
- CREATE TABLE "downstream_oauth_authorization_codes" (
634
- "code_hash" text PRIMARY KEY NOT NULL,
635
- "transaction_id" uuid NOT NULL,
636
- "grant_id" uuid NOT NULL,
637
- "client_id" text NOT NULL,
638
- "resource" text NOT NULL,
639
- "virtual_server_id" text NOT NULL,
640
- "tenant_id" text NOT NULL,
641
- "subject_id" text NOT NULL,
642
- "scope" text NOT NULL,
643
- "roles" jsonb NOT NULL,
644
- "redirect_uri" text NOT NULL,
645
- "code_challenge" text NOT NULL,
646
- "code_challenge_method" text NOT NULL,
647
- "created_at" timestamp with time zone NOT NULL,
648
- "expires_at" timestamp with time zone NOT NULL,
649
- "consumed_at" timestamp with time zone,
650
- "replayed_at" timestamp with time zone,
651
- CONSTRAINT "downstream_oauth_authorization_codes_roles_array_check" CHECK (jsonb_typeof("downstream_oauth_authorization_codes"."roles") = 'array'),
652
- CONSTRAINT "downstream_oauth_authorization_codes_code_challenge_method_check" CHECK ("downstream_oauth_authorization_codes"."code_challenge_method" = 'S256')
653
- );
654
- --> statement-breakpoint
655
- CREATE TABLE "downstream_oauth_authorization_transactions" (
656
- "id" uuid PRIMARY KEY NOT NULL,
657
- "client_id" text NOT NULL,
658
- "resource" text NOT NULL,
659
- "virtual_server_id" text NOT NULL,
660
- "tenant_id" text NOT NULL,
661
- "subject_id" text NOT NULL,
662
- "scope" text NOT NULL,
663
- "roles" jsonb NOT NULL,
664
- "redirect_uri" text NOT NULL,
665
- "code_challenge" text NOT NULL,
666
- "code_challenge_method" text NOT NULL,
667
- "created_at" timestamp with time zone NOT NULL,
668
- "expires_at" timestamp with time zone NOT NULL,
669
- CONSTRAINT "downstream_oauth_authorization_transactions_roles_array_check" CHECK (jsonb_typeof("downstream_oauth_authorization_transactions"."roles") = 'array'),
670
- CONSTRAINT "downstream_oauth_authorization_transactions_code_challenge_method_check" CHECK ("downstream_oauth_authorization_transactions"."code_challenge_method" = 'S256')
671
- );
672
- --> statement-breakpoint
673
- CREATE TABLE "downstream_oauth_dcr_clients" (
674
- "client_id" text PRIMARY KEY NOT NULL,
675
- "client_name" text NOT NULL,
676
- "redirect_uris" jsonb NOT NULL,
677
- "token_endpoint_auth_method" text NOT NULL,
678
- "hashed_client_secret" text,
679
- "client_secret_expires_at" timestamp with time zone,
680
- "client_expires_at" timestamp with time zone NOT NULL,
681
- "revoked_at" timestamp with time zone,
682
- "created_at" timestamp with time zone NOT NULL,
683
- CONSTRAINT "downstream_oauth_dcr_clients_redirect_uris_array_check" CHECK (jsonb_typeof("downstream_oauth_dcr_clients"."redirect_uris") = 'array'),
684
- CONSTRAINT "downstream_oauth_dcr_clients_token_endpoint_auth_method_check" CHECK ("downstream_oauth_dcr_clients"."token_endpoint_auth_method" IN ('none', 'client_secret_post', 'client_secret_basic'))
685
- );
686
- --> statement-breakpoint
687
- CREATE TABLE "downstream_oauth_grants" (
688
- "id" uuid PRIMARY KEY NOT NULL,
689
- "client_id" text NOT NULL,
690
- "resource" text NOT NULL,
691
- "virtual_server_id" text NOT NULL,
692
- "tenant_id" text NOT NULL,
693
- "subject_id" text NOT NULL,
694
- "scope" text NOT NULL,
695
- "roles" jsonb NOT NULL,
696
- "current_refresh_token_hash" text,
697
- "previous_refresh_token_hash" text,
698
- "created_at" timestamp with time zone NOT NULL,
699
- "expires_at" timestamp with time zone NOT NULL,
700
- "revoked_at" timestamp with time zone,
701
- "revoked_reason" text,
702
- CONSTRAINT "downstream_oauth_grants_roles_array_check" CHECK (jsonb_typeof("downstream_oauth_grants"."roles") = 'array')
703
- );
704
- --> statement-breakpoint
705
- CREATE TABLE "downstream_oauth_pending_authorization_transactions" (
706
- "id" uuid NOT NULL,
707
- "current_state_hash" text NOT NULL,
708
- "phase" text NOT NULL,
709
- "principal_subject_id" text,
710
- "principal_tenant_id" text,
711
- "principal_roles" jsonb,
712
- "client_id" text NOT NULL,
713
- "redirect_uri" text NOT NULL,
714
- "resource" text NOT NULL,
715
- "virtual_server_id" text NOT NULL,
716
- "client_state" text,
717
- "scope" text NOT NULL,
718
- "code_challenge" text NOT NULL,
719
- "code_challenge_method" text NOT NULL,
720
- "created_at" timestamp with time zone NOT NULL,
721
- "expires_at" timestamp with time zone NOT NULL,
722
- "consumed_at" timestamp with time zone,
723
- CONSTRAINT "downstream_oauth_pending_authorization_transactions_id_pk" PRIMARY KEY("id"),
724
- CONSTRAINT "downstream_oauth_pending_authorization_current_state_hash_unique" UNIQUE("current_state_hash"),
725
- CONSTRAINT "downstream_oauth_pending_authorization_phase_check" CHECK ("downstream_oauth_pending_authorization_transactions"."phase" IN ('awaiting_login', 'awaiting_setup')),
726
- CONSTRAINT "downstream_oauth_pending_authorization_phase_principal_check" CHECK ((
727
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_login'
728
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NULL
729
- AND "downstream_oauth_pending_authorization_transactions"."principal_tenant_id" IS NULL
730
- AND "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
731
- ) OR (
732
- "downstream_oauth_pending_authorization_transactions"."phase" = 'awaiting_setup'
733
- AND "downstream_oauth_pending_authorization_transactions"."principal_subject_id" IS NOT NULL
734
- AND "downstream_oauth_pending_authorization_transactions"."principal_tenant_id" IS NOT NULL
735
- AND (
736
- "downstream_oauth_pending_authorization_transactions"."principal_roles" IS NULL
737
- OR jsonb_typeof("downstream_oauth_pending_authorization_transactions"."principal_roles") = 'array'
738
- )
739
- )),
740
- CONSTRAINT "downstream_oauth_pending_authorization_code_challenge_method_check" CHECK ("downstream_oauth_pending_authorization_transactions"."code_challenge_method" = 'S256')
741
- );
742
- --> statement-breakpoint
743
- CREATE TABLE "upstream_connections" (
744
- "id" text PRIMARY KEY NOT NULL,
745
- "tenant_id" text,
746
- "owner_mode" text NOT NULL,
747
- "user_id" text,
748
- "upstream_server_id" text NOT NULL,
749
- "auth_profile_id" text NOT NULL,
750
- "status" text NOT NULL,
751
- "encrypted_access_token" text,
752
- "encrypted_refresh_token" text,
753
- "scopes" jsonb DEFAULT '[]'::jsonb NOT NULL,
754
- "expires_at" timestamp with time zone,
755
- "metadata" jsonb,
756
- "created_at" timestamp with time zone NOT NULL,
757
- "updated_at" timestamp with time zone NOT NULL,
758
- CONSTRAINT "upstream_connections_owner_key" UNIQUE NULLS NOT DISTINCT("owner_mode","tenant_id","user_id","upstream_server_id","auth_profile_id"),
759
- CONSTRAINT "upstream_connections_owner_mode_check" CHECK ("upstream_connections"."owner_mode" IN ('user', 'tenant_shared')),
760
- CONSTRAINT "upstream_connections_status_check" CHECK ("upstream_connections"."status" IN ('active', 'not_connected', 'reconsent_required')),
761
- CONSTRAINT "upstream_connections_scopes_array_check" CHECK (jsonb_typeof("upstream_connections"."scopes") = 'array'),
762
- CONSTRAINT "upstream_connections_owner_shape_check" CHECK (("upstream_connections"."owner_mode" = 'user' AND "upstream_connections"."tenant_id" IS NOT NULL AND "upstream_connections"."user_id" IS NOT NULL)
763
- OR ("upstream_connections"."owner_mode" = 'tenant_shared' AND "upstream_connections"."tenant_id" IS NOT NULL AND "upstream_connections"."user_id" IS NULL))
764
- );
765
- --> statement-breakpoint
766
- CREATE TABLE "upstream_oauth_state_consumptions" (
767
- "id" uuid PRIMARY KEY NOT NULL,
768
- "consumed_at" timestamp with time zone NOT NULL,
769
- "expires_at" timestamp with time zone NOT NULL
770
- );
771
- --> statement-breakpoint
772
- CREATE TABLE "upstream_oauth_states" (
773
- "id" uuid PRIMARY KEY NOT NULL,
774
- "record" jsonb NOT NULL,
775
- "expires_at" timestamp with time zone NOT NULL,
776
- "created_at" timestamp with time zone NOT NULL,
777
- "updated_at" timestamp with time zone NOT NULL
778
- );
779
- --> statement-breakpoint
780
- ALTER TABLE "downstream_oauth_access_tokens" ADD CONSTRAINT "downstream_oauth_access_tokens_grant_id_downstream_oauth_grants_id_fk" FOREIGN KEY ("grant_id") REFERENCES "public"."downstream_oauth_grants"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
781
- ALTER TABLE "downstream_oauth_authorization_codes" ADD CONSTRAINT "downstream_oauth_authorization_codes_transaction_id_downstream_oauth_authorization_transactions_id_fk" FOREIGN KEY ("transaction_id") REFERENCES "public"."downstream_oauth_authorization_transactions"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
782
- CREATE INDEX "browser_connect_ticket_consumptions_expiry_idx" ON "browser_connect_ticket_consumptions" USING btree ("expires_at");--> statement-breakpoint
783
- CREATE INDEX "downstream_oauth_access_tokens_grant_idx" ON "downstream_oauth_access_tokens" USING btree ("grant_id");--> statement-breakpoint
784
- CREATE INDEX "downstream_oauth_access_tokens_expiry_idx" ON "downstream_oauth_access_tokens" USING btree ("expires_at");--> statement-breakpoint
785
- CREATE INDEX "downstream_oauth_authorization_codes_grant_idx" ON "downstream_oauth_authorization_codes" USING btree ("grant_id");--> statement-breakpoint
786
- CREATE INDEX "downstream_oauth_authorization_codes_expiry_idx" ON "downstream_oauth_authorization_codes" USING btree ("expires_at");--> statement-breakpoint
787
- CREATE INDEX "downstream_oauth_authorization_transactions_expiry_idx" ON "downstream_oauth_authorization_transactions" USING btree ("expires_at");--> statement-breakpoint
788
- CREATE INDEX "downstream_oauth_dcr_clients_expiry_idx" ON "downstream_oauth_dcr_clients" USING btree ("client_expires_at") WHERE "downstream_oauth_dcr_clients"."revoked_at" IS NULL;--> statement-breakpoint
789
- CREATE INDEX "downstream_oauth_grants_refresh_current_idx" ON "downstream_oauth_grants" USING btree ("current_refresh_token_hash") WHERE "downstream_oauth_grants"."current_refresh_token_hash" IS NOT NULL;--> statement-breakpoint
790
- CREATE INDEX "downstream_oauth_grants_refresh_previous_idx" ON "downstream_oauth_grants" USING btree ("previous_refresh_token_hash") WHERE "downstream_oauth_grants"."previous_refresh_token_hash" IS NOT NULL;--> statement-breakpoint
791
- CREATE INDEX "downstream_oauth_grants_subject_client_resource_idx" ON "downstream_oauth_grants" USING btree ("tenant_id","subject_id","client_id","resource") WHERE "downstream_oauth_grants"."revoked_at" IS NULL;--> statement-breakpoint
792
- CREATE INDEX "downstream_oauth_grants_expiry_idx" ON "downstream_oauth_grants" USING btree ("expires_at");--> statement-breakpoint
793
- CREATE INDEX "downstream_oauth_pending_authorization_expiry_idx" ON "downstream_oauth_pending_authorization_transactions" USING btree ("expires_at");--> statement-breakpoint
794
- CREATE INDEX "upstream_oauth_state_consumptions_expiry_idx" ON "upstream_oauth_state_consumptions" USING btree ("expires_at");--> statement-breakpoint
795
- CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING btree ("expires_at");
796
- `},{tag:"0001_self_heal_pending_authorization",sql:aP},{tag:"0002_upstream_connection_id_text",sql:iP},{tag:"0003_drop_tenant_id_columns",sql:sP}];var ma="_runtime_applied_migrations",cP=`
797
- CREATE TABLE IF NOT EXISTS ${ma} (
798
- tag text PRIMARY KEY NOT NULL,
799
- applied_at timestamp with time zone NOT NULL DEFAULT now()
800
- )
801
- `,pa;async function uP(e){if(pa)return pa;pa=(async()=>{await e.query(cP),await e.query(`INSERT INTO ${ma} (tag)
802
- SELECT '0000_messy_makkari'
803
- WHERE to_regclass('public.audit_events') IS NOT NULL
804
- AND NOT EXISTS (
805
- SELECT 1 FROM ${ma}
806
- WHERE tag = '0000_messy_makkari'
807
- )
808
- ON CONFLICT (tag) DO NOTHING`);let t=await e.query(`SELECT tag FROM ${ma}`),r=new Set(t.map(n=>n.tag));for(let n of S_){if(r.has(n.tag))continue;let a=n.sql.split(/-->\s*statement-breakpoint/g).map(i=>i.trim()).filter(i=>i.length>0);for(let i of a)await e.query(i);await e.query(`INSERT INTO ${ma} (tag) VALUES ($1)`,[n.tag])}})();try{await pa}catch(t){throw pa=void 0,t}}o(uP,"ensureGatewayMigrationsApplied");function v_(e){let t=o(()=>uP(e),"ensureReady");return{query:o((n,a)=>(async()=>(await t(),e.query(n,a)))(),"query"),async transaction(n){return await t(),e.transaction(n)}}}o(v_,"createMigrationGatedDatabase");ae();ae();var dP=["user","shared"],tr=c.enum(dP);function kr(e){return{mode:"user",subjectId:e}}o(kr,"buildUserUpstreamConnectionOwner");function Ss(){return{mode:"shared"}}o(Ss,"buildSharedUpstreamConnectionOwner");ae();ae();function vs(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(vs,"parseSafeRelativeReturnTo");var R_=c.object({ownerMode:tr,initiatedBySubjectId:ie,ownerSubjectId:ie.optional(),upstreamServerId:$e,authProfileId:De,virtualServerId:Se,returnTo:c.string().min(1).transform(e=>vs(e)).optional()});function b_(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:c.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}o(b_,"validateUpstreamOwnerState");var Fn=R_.superRefine(b_),C_=R_.omit({returnTo:!0}).superRefine(b_);function ha(e){return Fn.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,returnTo:e.returnTo})}o(ha,"buildUpstreamOwnerState");function Vn(e){if(e.ownerMode==="shared")return Ss();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return kr(e.ownerSubjectId)}o(Vn,"resolveUpstreamConnectionOwnerFromState");var lP=["active","not_connected","reconsent_required"],pP=["basic_auth_app_password","bearer_token"],I_=c.string().trim().min(1).brand(),Kn=c.uuid().brand(),fa=c.uuid().brand(),Zn=c.enum(lP),mP=c.enum(pP),T_=c.object({encryptedClientInformation:c.string().optional(),encryptedDiscoveryState:c.string().optional(),connectedBySubjectId:ie.optional()}),El=T_.extend({encryptedStaticSecret:c.string().optional(),staticSecretKind:mP.optional(),staticSecretLabel:c.string().min(1).optional(),staticSecretUsername:c.string().min(1).optional()}).strict(),hP=c.object({id:I_,subjectId:ie.optional(),ownerMode:tr,upstreamServerId:$e,authProfileId:De,status:Zn,encryptedAccessToken:c.string().min(1).optional(),encryptedRefreshToken:c.string().min(1).optional(),scopes:c.array(c.string()),expiresAt:Q.optional(),metadata:El.optional(),createdAt:Q,updatedAt:Q});function xl(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:c.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(xl,"validateUpstreamConnectionOwnerShape");var rr=hP.superRefine(xl);function en(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(en,"readUpstreamConnectionLookupKey");var ga=Fn.extend({id:Kn,callbackPath:c.string().min(1),expiresAt:Q,codeVerifier:c.string().optional(),redirectUri:c.url(),returnOrigin:c.url().optional()}).extend(T_.shape);function A_(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(A_,"readUpstreamConnectionStatus");function Rs(){return I_.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(Rs,"createUpstreamConnectionId");function k_(){return Kn.parse(crypto.randomUUID())}o(k_,"createOAuthStateId");function E_(){return fa.parse(crypto.randomUUID())}o(E_,"createBrowserConnectTicketId");var x_=c.unknown().transform(e=>Ar(e,"upstream connection scopes")).pipe(c.array(c.string())),P_=c.unknown().transform(e=>{if(e!=null)return Ar(e,"upstream connection metadata")}).transform(e=>{if(!e||typeof e!="object"||Array.isArray(e))return;let t=El.safeParse(e);if(t.success)return Object.values(t.data).some(r=>r!==void 0)?t.data:void 0}),fP=c.object({id:c.string().min(1),owner_mode:tr,user_id:ie.nullable(),upstream_server_id:$e,auth_profile_id:De,status:Zn,encrypted_access_token:c.string().nullable(),encrypted_refresh_token:c.string().nullable(),scopes:x_,expires_at:he.nullable(),metadata:P_,created_at:he,updated_at:he}).transform(e=>rr.parse({id:e.id,ownerMode:e.owner_mode,subjectId:e.user_id??void 0,upstreamServerId:e.upstream_server_id,authProfileId:e.auth_profile_id,status:e.status,encryptedAccessToken:e.encrypted_access_token??void 0,encryptedRefreshToken:e.encrypted_refresh_token??void 0,scopes:e.scopes,expiresAt:e.expires_at?z(e.expires_at):void 0,metadata:e.metadata,createdAt:z(e.created_at),updatedAt:z(e.updated_at)})),gP=c.object({requested_ordinal:c.number(),id:c.string().min(1).nullable(),owner_mode:tr.nullable(),user_id:ie.nullable(),upstream_server_id:$e.nullable(),auth_profile_id:De.nullable(),status:Zn.nullable(),encrypted_access_token:c.string().nullable(),encrypted_refresh_token:c.string().nullable(),scopes:x_.nullable(),expires_at:he.nullable(),metadata:P_,created_at:he.nullable(),updated_at:he.nullable()}).transform(e=>{if(e.id!==null)return rr.parse({id:e.id,ownerMode:e.owner_mode,subjectId:e.user_id??void 0,upstreamServerId:e.upstream_server_id,authProfileId:e.auth_profile_id,status:e.status,encryptedAccessToken:e.encrypted_access_token??void 0,encryptedRefreshToken:e.encrypted_refresh_token??void 0,scopes:e.scopes??[],expiresAt:e.expires_at?z(e.expires_at):void 0,metadata:e.metadata,createdAt:z(e.created_at),updatedAt:z(e.updated_at)})});function _P(e){let t=[],r=e.map((n,a)=>{let i=t.length+1;return t.push(a,n.owner.mode,n.owner.mode==="user"?n.owner.subjectId:null,n.upstreamServerId,n.authProfileId),`($${i}::integer, $${i+1}, $${i+2}, $${i+3}, $${i+4})`});return{params:t,sql:`WITH requested(
809
- requested_ordinal,
810
- owner_mode,
811
- user_id,
812
- upstream_server_id,
813
- auth_profile_id
814
- ) AS (
815
- VALUES ${r.join(", ")}
816
- )
817
- SELECT
818
- requested.requested_ordinal,
819
- upstream_connections.id,
820
- upstream_connections.owner_mode,
821
- upstream_connections.user_id,
822
- upstream_connections.upstream_server_id,
823
- upstream_connections.auth_profile_id,
824
- upstream_connections.status,
825
- upstream_connections.encrypted_access_token,
826
- upstream_connections.encrypted_refresh_token,
827
- upstream_connections.scopes,
828
- upstream_connections.expires_at,
829
- upstream_connections.metadata,
830
- upstream_connections.created_at,
831
- upstream_connections.updated_at
832
- FROM requested
833
- LEFT JOIN upstream_connections
834
- ON upstream_connections.owner_mode = requested.owner_mode
835
- AND upstream_connections.user_id IS NOT DISTINCT FROM requested.user_id
836
- AND upstream_connections.upstream_server_id = requested.upstream_server_id
837
- AND upstream_connections.auth_profile_id = requested.auth_profile_id
838
- ORDER BY requested.requested_ordinal`}}o(_P,"buildBatchGetQuery");function yP(e){if(!e)return null;let t={};for(let[r,n]of Object.entries(e))typeof n=="string"&&(t[r]=n);return Object.keys(t).length>0?JSON.stringify(t):null}o(yP,"metadataToDatabaseValue");function wP(e){if(!e)throw g("internal_server_error","Failed to persist upstream connection");return e}o(wP,"requirePersistedUpstreamConnection");var bs=class{constructor(t){this.db=t}static{o(this,"PostgresUpstreamConnectionRepository")}async batchGet(t){if(t.length===0)return[];let r=_P(t);return c.array(gP).parse(await this.db.query(r.sql,r.params))}async upsert(t){let r=new Date,n=c.array(fP).parse(await this.db.query(`INSERT INTO upstream_connections (
839
- id,
840
- owner_mode,
841
- user_id,
842
- upstream_server_id,
843
- auth_profile_id,
844
- status,
845
- encrypted_access_token,
846
- encrypted_refresh_token,
847
- scopes,
848
- expires_at,
849
- metadata,
850
- created_at,
851
- updated_at
852
- ) VALUES (
853
- $1,
854
- $2,
855
- $3,
856
- $4,
857
- $5,
858
- $6,
859
- $7,
860
- $8,
861
- $9::jsonb,
862
- $10,
863
- $11::jsonb,
864
- $12,
865
- $12
866
- )
867
- ON CONFLICT ON CONSTRAINT upstream_connections_owner_key
868
- DO UPDATE SET
869
- status = EXCLUDED.status,
870
- encrypted_access_token = EXCLUDED.encrypted_access_token,
871
- encrypted_refresh_token = EXCLUDED.encrypted_refresh_token,
872
- scopes = EXCLUDED.scopes,
873
- expires_at = EXCLUDED.expires_at,
874
- metadata = EXCLUDED.metadata,
875
- updated_at = EXCLUDED.updated_at
876
- RETURNING
877
- id,
878
- owner_mode,
879
- user_id,
880
- upstream_server_id,
881
- auth_profile_id,
882
- status,
883
- encrypted_access_token,
884
- encrypted_refresh_token,
885
- scopes,
886
- expires_at,
887
- metadata,
888
- created_at,
889
- updated_at`,[t.id,t.ownerMode,t.subjectId??null,t.upstreamServerId,t.authProfileId,t.status,t.encryptedAccessToken??null,t.encryptedRefreshToken??null,JSON.stringify(t.scopes),t.expiresAt?new Date(t.expiresAt):null,yP(t.metadata),r]));return wP(n[0])}};ae();var SP=60*60*24*1e3,vP=c.object({kind:c.enum(["available","consumed","missing"]),record:c.unknown().nullable()}),RP=c.object({inserted:c.preprocess(e=>{if(typeof e!="string")return e;switch(e.toLowerCase()){case"true":case"t":case"1":return!0;case"false":case"f":case"0":return!1;default:return e}},c.boolean())});function O_(e,t){let r=e[0];if(!r)throw g("internal_server_error",`Postgres ${t} query returned no result row`);return r}o(O_,"requireSingleRow");function bP(e){return ga.parse(Ar(e,"upstream OAuth state record"))}o(bP,"parseStoredOAuthStateRecord");var Cs=class{constructor(t){this.db=t}static{o(this,"PostgresOAuthStateStore")}async save(t){let r=new Date;await this.db.query(`INSERT INTO upstream_oauth_states (
890
- id,
891
- record,
892
- expires_at,
893
- created_at,
894
- updated_at
895
- ) VALUES ($1, $2::jsonb, $3, $4, $4)
896
- ON CONFLICT (id) DO UPDATE
897
- SET record = EXCLUDED.record,
898
- expires_at = EXCLUDED.expires_at,
899
- updated_at = EXCLUDED.updated_at`,[t.id,JSON.stringify(t),new Date(t.expiresAt),r])}async consumeForCallback(t){let r=new Date,n=new Date(r.getTime()+SP),a=O_(c.array(vP).parse(await this.db.query(`WITH expired_state_cleanup AS (
900
- DELETE FROM upstream_oauth_states
901
- WHERE id = $1
902
- AND expires_at <= $2
903
- RETURNING id
904
- ),
905
- expired_consumption_cleanup AS (
906
- DELETE FROM upstream_oauth_state_consumptions
907
- WHERE id = $1
908
- AND expires_at <= $2
909
- RETURNING id
910
- ),
911
- candidate AS (
912
- SELECT id
913
- FROM upstream_oauth_states
914
- WHERE id = $1
915
- AND expires_at > $2
916
- AND (SELECT count(*) FROM expired_state_cleanup) >= 0
917
- ),
918
- inserted_consumption AS (
919
- INSERT INTO upstream_oauth_state_consumptions (
920
- id,
921
- consumed_at,
922
- expires_at
923
- )
924
- SELECT $1, $2, $3
925
- WHERE EXISTS (SELECT 1 FROM candidate)
926
- AND (SELECT count(*) FROM expired_consumption_cleanup) >= 0
927
- ON CONFLICT (id) DO NOTHING
928
- RETURNING id
929
- ),
930
- deleted_state AS (
931
- DELETE FROM upstream_oauth_states
932
- WHERE id = $1
933
- AND EXISTS (SELECT 1 FROM inserted_consumption)
934
- RETURNING record
935
- ),
936
- existing_consumption AS (
937
- SELECT id
938
- FROM upstream_oauth_state_consumptions
939
- WHERE id = $1
940
- AND expires_at > $2
941
- AND (SELECT count(*) FROM expired_consumption_cleanup) >= 0
942
- )
943
- SELECT
944
- CASE
945
- WHEN EXISTS (SELECT 1 FROM deleted_state) THEN 'available'
946
- WHEN EXISTS (SELECT 1 FROM existing_consumption) THEN 'consumed'
947
- WHEN EXISTS (SELECT 1 FROM candidate) THEN 'consumed'
948
- ELSE 'missing'
949
- END AS kind,
950
- (SELECT record FROM deleted_state LIMIT 1) AS record`,[t,r,n])),"OAuth state consume");if(a.kind==="available"){if(a.record===null)throw g("internal_server_error","Consumed OAuth state row did not include a record");return{kind:"available",record:bP(a.record)}}return{kind:a.kind}}},Is=class{constructor(t){this.db=t}static{o(this,"PostgresBrowserConnectTicketStore")}async consume(t,r){let n=new Date;return O_(c.array(RP).parse(await this.db.query(`WITH expired_consumption_cleanup AS (
951
- DELETE FROM browser_connect_ticket_consumptions
952
- WHERE id = $1
953
- AND expires_at <= $2
954
- RETURNING id
955
- ),
956
- inserted_consumption AS (
957
- INSERT INTO browser_connect_ticket_consumptions (
958
- id,
959
- consumed_at,
960
- expires_at
961
- )
962
- SELECT $1, $2, $3
963
- WHERE $3 > $2
964
- AND (SELECT count(*) FROM expired_consumption_cleanup) >= 0
965
- ON CONFLICT (id) DO NOTHING
966
- RETURNING id
967
- )
968
- SELECT EXISTS (SELECT 1 FROM inserted_consumption) AS inserted`,[t,n,r])),"browser connect ticket consume").inserted?{kind:"available"}:{kind:"consumed"}}};var CP={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},D=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=CP[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};ae();var Ol=c.discriminatedUnion("mode",[c.object({mode:c.literal("user"),subjectId:ie}).strict(),c.object({mode:c.literal("shared")}).strict()]),N_=c.object({owner:Ol,upstreamServerId:$e,authProfileId:De}).strict(),z_=c.object({items:c.array(N_).min(1).max(100)}).strict(),Ul=c.object({items:c.array(c.object({key:c.object({ownerMode:tr,subjectId:ie.optional(),upstreamServerId:$e,authProfileId:De}).strict(),connection:rr.strict().optional()}).strict())}).strict(),$_=rr.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(xl),D_=rr.strict(),M_=c.object({owner:Ol,upstreamServerId:$e,authProfileId:De}).strict(),q_=c.object({owner:Ol,upstreamServerId:$e,authProfileId:De,connection:rr.strict().optional(),connectionStatus:c.object({connected:c.boolean(),status:Zn,updatedAt:rr.shape.updatedAt.optional()}).strict()}).strict(),IP=c.enum(["none","client_secret_basic","client_secret_post"]),tn=c.object({clientId:ye,clientName:c.string().min(1),tokenEndpointAuthMethod:IP}).strict(),Nl=c.discriminatedUnion("method",[c.object({method:c.literal("none"),clientId:ye}).strict(),c.object({method:c.enum(["client_secret_basic","client_secret_post"]),clientId:ye,clientSecretHashInput:c.string().min(1)}).strict()]),zl=c.object({id:Je,currentStateHash:c.string().min(1),clientId:ye,redirectUri:c.string().min(1),resource:c.string().min(1),virtualServerId:Se,clientState:c.string().optional(),scope:c.string(),codeChallenge:c.string().min(1),codeChallengeMethod:c.literal("S256"),createdAt:Q,expiresAt:Q,consumedAt:Q.optional()}).strict(),U_=zl.omit({id:!0,consumedAt:!0}).extend({transactionId:Je,client:tn.optional()}).strict(),$l=c.object({subjectId:ie,roles:c.array(c.string()).optional()}).strict(),TP=zl.extend({phase:c.literal("awaiting_login")}).strict(),Pl=zl.extend({phase:c.literal("awaiting_setup"),principal:$l}).strict(),AP=c.discriminatedUnion("phase",[TP,Pl]),Dl=c.object({transaction:AP,client:tn}).strict(),L_=da.omit({revokedAt:!0}).strict(),j_=c.discriminatedUnion("kind",[c.object({kind:c.literal("registered"),client:tn}).strict(),c.object({kind:c.literal("already_exists")}).strict()]),H_=c.object({clientId:ye}).strict(),G_=c.discriminatedUnion("kind",[c.object({kind:c.literal("found"),client:da.strict()}).strict(),c.object({kind:c.literal("missing")}).strict()]),B_=c.discriminatedUnion("phase",[U_.extend({phase:c.literal("awaiting_login")}).strict(),U_.extend({phase:c.literal("awaiting_setup"),principal:$l}).strict()]),F_=c.discriminatedUnion("kind",[Dl.extend({kind:c.literal("started")}).strict(),c.object({kind:c.literal("invalid_client")}).strict(),c.object({kind:c.literal("redirect_uri_mismatch")}).strict(),c.object({kind:c.literal("already_exists")}).strict()]),V_=c.object({transactionId:Je,currentStateHash:c.string().min(1),now:Q}).strict(),K_=c.discriminatedUnion("kind",[Dl.extend({kind:c.literal("available")}).strict(),c.object({kind:c.literal("stale_hash")}).strict(),c.object({kind:c.literal("consumed")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("missing")}).strict()]),Z_=c.object({transactionId:Je,expectedPhase:c.literal("awaiting_login"),currentStateHash:c.string().min(1),nextStateHash:c.string().min(1),nextPhase:c.literal("awaiting_setup"),principal:$l,now:Q}).strict(),W_=c.discriminatedUnion("kind",[Dl.extend({kind:c.literal("advanced")}).strict(),c.object({kind:c.literal("wrong_phase"),current:c.enum(["awaiting_login","awaiting_setup"])}).strict(),c.object({kind:c.literal("stale_hash")}).strict(),c.object({kind:c.literal("consumed")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("missing")}).strict()]),J_=c.discriminatedUnion("decision",[c.object({decision:c.literal("approve"),transactionId:Je,currentStateHash:c.string().min(1),currentPrincipal:c.object({subjectId:ie}).strict(),authorizationCodeHash:c.string().min(1),authorizationCodeExpiresAt:Q,grantId:kt,now:Q}).strict(),c.object({decision:c.literal("cancel"),transactionId:Je,currentStateHash:c.string().min(1),currentPrincipal:c.object({subjectId:ie}).strict(),now:Q}).strict()]),Y_=c.discriminatedUnion("kind",[c.object({kind:c.literal("approved"),transaction:Pl,client:tn}).strict(),c.object({kind:c.literal("cancelled"),transaction:Pl,client:tn}).strict(),c.object({kind:c.literal("principal_mismatch")}).strict(),c.object({kind:c.literal("stale_hash")}).strict(),c.object({kind:c.literal("consumed_already")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("missing")}).strict()]),X_=c.object({clientAuth:Nl,codeHash:c.string().min(1),redirectUri:c.string().min(1),resource:c.string().min(1).optional(),codeChallenge:c.string().min(1),currentRefreshTokenHash:c.string().min(1),accessTokenHash:c.string().min(1),grantExpiresAt:Q,accessTokenExpiresAt:Q,now:Q}).strict(),Q_=c.discriminatedUnion("kind",[c.object({kind:c.literal("exchanged"),client:tn,grant:la.strict()}).strict(),c.object({kind:c.literal("invalid_client")}).strict(),c.object({kind:c.literal("consumed")}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("resource_mismatch")}).strict(),c.object({kind:c.literal("binding_mismatch")}).strict()]),ey=c.object({clientAuth:Nl,currentRefreshTokenHash:c.string().min(1),nextRefreshTokenHash:c.string().min(1),accessTokenHash:c.string().min(1),resource:c.string().min(1).optional(),accessTokenExpiresAt:Q,now:Q}).strict(),ty=c.discriminatedUnion("kind",[c.object({kind:c.literal("rotated"),client:tn,grant:la.strict(),accessToken:Gn.strict(),matched:c.literal("current")}).strict(),c.object({kind:c.literal("invalid_client")}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("resource_mismatch")}).strict(),c.object({kind:c.literal("revoked")}).strict()]),ry=c.object({clientAuth:Nl,tokenHash:c.string().min(1),now:Q}).strict(),ny=c.discriminatedUnion("kind",[c.object({kind:c.literal("revoked_access_token")}).strict(),c.object({kind:c.literal("revoked_grant")}).strict(),c.object({kind:c.literal("client_mismatch")}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("invalid_client")}).strict()]),oy=c.object({tokenHash:c.string().min(1),now:Q}).strict(),ay=c.discriminatedUnion("kind",[c.object({kind:c.literal("valid"),record:Gn.strict()}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("revoked")}).strict()]),iy=c.object({accessTokenHash:c.string().min(1),resource:c.string().min(1),virtualServerId:Se,upstreamConnectionKeys:c.array(N_).max(100),now:Q}).strict(),sy=c.discriminatedUnion("kind",[c.object({kind:c.literal("authorized"),principal:c.object({subjectId:ie,roles:c.array(c.string())}).strict(),accessToken:Gn.strict(),upstreamConnections:Ul.shape.items}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("revoked")}).strict(),c.object({kind:c.literal("resource_mismatch")}).strict(),c.object({kind:c.literal("principal_mismatch")}).strict()]),cy=c.object({record:ga}).strict(),uy=c.object({kind:c.literal("saved")}).strict(),dy=c.object({id:Kn,now:Q}).strict(),ly=c.discriminatedUnion("kind",[c.object({kind:c.literal("available"),record:ga}).strict(),c.object({kind:c.literal("consumed")}).strict(),c.object({kind:c.literal("missing")}).strict()]),py=c.object({id:fa,expiresAt:Q,now:Q}).strict(),my=c.discriminatedUnion("kind",[c.object({kind:c.literal("available")}).strict(),c.object({kind:c.literal("consumed")}).strict()]);var hy=100;function fy(e){return e!==null&&typeof e=="object"}o(fy,"isProblemDetailsShape");var kP="/zups/v2/mcp/storage";function qe(e){return`${kP}/${e}`}o(qe,"buildStoragePath");function EP(){return qe("upstream-connections/batch-get")}o(EP,"buildBatchGetUpstreamConnectionsPath");function xP(){return qe("upstream-connections/upsert")}o(xP,"buildUpsertUpstreamConnectionPath");function PP(){return qe("authorization/read-setup")}o(PP,"buildReadAuthorizationSetupPath");function OP(){return qe("oauth/register-client")}o(OP,"buildRegisterClientPath");function UP(){return qe("oauth/read-client")}o(UP,"buildReadClientPath");function NP(){return qe("authorization/start")}o(NP,"buildStartAuthorizationPath");function zP(){return qe("authorization/read-pending")}o(zP,"buildReadPendingAuthorizationPath");function $P(){return qe("authorization/advance-pending")}o($P,"buildAdvancePendingAuthorizationPath");function DP(){return qe("authorization/decide-setup")}o(DP,"buildDecideAuthorizationSetupPath");function MP(){return qe("token/exchange-authorization-code")}o(MP,"buildExchangeAuthorizationCodePath");function qP(){return qe("token/refresh")}o(qP,"buildRefreshTokenPath");function LP(){return qe("token/revoke")}o(LP,"buildRevokeOAuthTokenPath");function jP(){return qe("token/validate-access-token")}o(jP,"buildValidateAccessTokenPath");function HP(){return qe("mcp/authorize-and-load-connections")}o(HP,"buildAuthorizeAndLoadConnectionsPath");function GP(){return qe("upstream-oauth-state/save")}o(GP,"buildSaveUpstreamOAuthStatePath");function BP(){return qe("upstream-oauth-state/consume")}o(BP,"buildConsumeUpstreamOAuthStatePath");function FP(){return qe("browser-connect-ticket/consume")}o(FP,"buildConsumeBrowserConnectTicketPath");function VP(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(VP,"responseKeyMatchesLookup");function KP(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(KP,"authorizationSetupMatchesLookup");function yy(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(yy,"connectionMatchesLookup");function ZP(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&ql(e.scopes,t.scopes)&&Ml(e.expiresAt,t.expiresAt)&&JP(e.metadata,t.metadata)}o(ZP,"connectionMatchesUpsertRecord");function Ml(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(Ml,"optionalTimestampInstantsMatch");function WP(e,t){return Date.parse(e)<=Date.parse(t)}o(WP,"timestampInstantIsAtOrBefore");function ql(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(ql,"stringArraysMatch");function JP(e,t){let r=gy(e),n=gy(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(JP,"metadataMatches");function gy(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(gy,"definedMetadataEntries");function Ce(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(Ce,"throwInvalidStorageResponse");async function YP(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){Ce("Gateway Service storage response did not match the runtime storage contract.",r)}}o(YP,"parseRuntimeHttpStorageResponse");function wy(e,t){e.length!==t.length&&Ce("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];VP(n.key,a)||Ce("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!yy(n.connection,a)&&Ce("Gateway Service storage response connection did not match the response key.")}}o(wy,"validateUpstreamConnectionItemsMatchLookups");function XP(e,t){KP(e,t)||Ce("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!yy(e.connection,t)&&Ce("Gateway Service storage response authorization setup connection did not match the request.");let r=e.connection?.status==="active",n=e.connection?.status??"not_connected",a=e.connection?.updatedAt;(e.connectionStatus.connected!==r||e.connectionStatus.status!==n||!Ml(e.connectionStatus.updatedAt,a))&&Ce("Gateway Service storage response authorization setup status did not match the connection.")}o(XP,"validateAuthorizationSetupResponseMatchesLookup");function QP(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&Ce("Gateway Service storage response registered client did not match the request.")}o(QP,"validateRegisterClientResponseMatchesRequest");function e0(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&Ce("Gateway Service storage response client did not match the request.")}o(e0,"validateReadClientResponseMatchesRequest");function t0(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.virtualServerId!==t.virtualServerId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&Ce("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&Ce("Gateway Service storage response started authorization principal did not match the request."))}o(t0,"validateStartAuthorizationResponseMatchesRequest");function _y(e,t){e.kind!=="available"&&e.kind!=="advanced"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&Ce("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&Ce("Gateway Service storage response advanced authorization did not match the request."))}o(_y,"validatePendingAuthorizationResponseMatchesRequest");function r0(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&Ce("Gateway Service storage response authorization setup transaction did not match the request.")}o(r0,"validateAuthorizationSetupDecisionResponseMatchesRequest");function n0(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!Ml(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&Ce("Gateway Service storage response authorization-code exchange did not match the request.")}o(n0,"validateExchangeAuthorizationCodeResponseMatchesRequest");function o0(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&Ce("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!WP(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!s0(e.accessToken,e.grant))&&Ce("Gateway Service storage response token refresh access token did not match the request."))}o(o0,"validateRefreshTokenResponseMatchesRequest");function a0(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&Ce("Gateway Service storage response access token did not match the request.")}o(a0,"validateAccessTokenValidationResponseMatchesRequest");function i0(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!ql(e.principal.roles,e.accessToken.roles))&&Ce("Gateway Service storage response MCP authorization did not match the request."),wy(e.upstreamConnections,t.upstreamConnectionKeys))}o(i0,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function s0(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&ql(e.roles,t.roles)}o(s0,"accessTokenMatchesGrant");async function c0(e){try{return await e.clone().json()}catch{return}}o(c0,"readProblemDetails");async function u0(e){let t=await c0(e),r=fy(t)&&typeof t.status=="number"?t.status:e.status,n=fy(t)&&na(t.code)?t.code:Zd(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(u0,"throwRuntimeHttpStorageError");var Ts=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??om.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}async#e(t){let r=t.requestSchema.parse(t.input),n=new URL(t.path,this.#t),a=new Headers({"Content-Type":"application/json"});am(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await u0(i),{request:r,response:await YP(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let u=en(s),d=n.get(u);if(d!==void 0)return d;let p=r.length;return r.push(s),n.set(u,p),p}),i=[];for(let s=0;s<r.length;s+=hy){let u=r.slice(s,s+hy);i.push(...await this.#n(u))}return a.map(s=>i[s])}async upsertUpstreamConnection(t){let{request:r,response:n}=await this.#e({input:t,path:xP(),requestSchema:$_,responseSchema:D_});return ZP(n,r)||Ce("Gateway Service storage response connection did not match the request."),n}async readAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:PP(),requestSchema:M_,responseSchema:q_});return XP(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:OP(),requestSchema:L_,responseSchema:j_});return QP(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:UP(),requestSchema:H_,responseSchema:G_});return e0(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:NP(),requestSchema:B_,responseSchema:F_});return t0(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:zP(),requestSchema:V_,responseSchema:K_});return _y(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:$P(),requestSchema:Z_,responseSchema:W_});return _y(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:DP(),requestSchema:J_,responseSchema:Y_});return r0(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:GP(),requestSchema:cy,responseSchema:uy});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:BP(),requestSchema:dy,responseSchema:ly});return n.kind==="available"&&n.record.id!==r.id&&Ce("Gateway Service storage response upstream OAuth state did not match the request."),n}async consumeBrowserConnectTicket(t){let{response:r}=await this.#e({input:t,path:FP(),requestSchema:py,responseSchema:my});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:MP(),requestSchema:X_,responseSchema:Q_});return n0(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:qP(),requestSchema:ey,responseSchema:ty});return o0(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:LP(),requestSchema:ry,responseSchema:ny});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:jP(),requestSchema:oy,responseSchema:ay});return a0(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:HP(),requestSchema:iy,responseSchema:sy});return i0(n,r),n}async#n(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:EP(),requestSchema:z_,responseSchema:Ul});return wy(n.items,t),n.items.map(a=>a.connection)}};var Ll=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpUpstreamConnectionRepository")}batchGet(t){return this.client.batchGetUpstreamConnections(t)}upsert(t){return this.client.upsertUpstreamConnection(t)}},jl=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpDownstreamOAuthRepository")}#t=new Map;#r=new Map;async getDcrClient(t){let r=this.#t.get(t);if(r&&r.redirectUris.length>0)return r;let n=await this.client.readClient({clientId:t});if(n.kind!=="missing")return this.#t.set(t,n.client),n.client}async saveDcrClient(t){if((await this.client.registerClient(t)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");this.#t.set(t.clientId,t)}async savePendingAuthorizationTransaction(t,r){let{id:n,...a}=t,i=await this.client.startAuthorization({...a,transactionId:n,...r?.client===void 0?{}:{client:r.client}});switch(i.kind){case"started":return this.#e(i.client),{kind:"saved"};case"already_exists":return{kind:"already_exists"};case"invalid_client":throw new D("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new D("invalid_request","redirect_uri is not registered for the client.")}}async advancePendingAuthorizationTransaction(t){let r=await this.client.advancePendingAuthorization({transactionId:t.id,expectedPhase:t.expectedPhase,currentStateHash:t.currentStateHash,nextStateHash:t.nextStateHash,nextPhase:t.nextPhase,principal:t.principal,now:z(t.now)});return r.kind==="advanced"?(this.#e(r.client),{kind:"advanced",record:r.transaction}):r}async getPendingAuthorizationTransaction(t){let r=await this.client.readPendingAuthorization({transactionId:t.id,currentStateHash:t.currentStateHash,now:z(t.now)});return r.kind==="available"?(this.#e(r.client),{kind:"available",record:r.transaction}):r}async consumePendingAuthorizationTransaction(t){let r=await this.getPendingAuthorizationTransaction(t);return r.kind!=="available"?r.kind==="consumed"?{kind:"consumed_already"}:r:r.record.phase!=="awaiting_setup"?{kind:"missing"}:(this.#r.set(r.record.id,{currentStateHash:t.currentStateHash,now:t.now,transaction:r.record}),{kind:"consumed",record:r.record})}async issueAuthorizationCode(t){let r=this.#r.get(t.id);if(!r)throw g("internal_server_error","Authorization code issuance requires a pending setup decision.");let n=await this.decideAuthorizationSetup({decision:"approve",transactionId:t.id,currentStateHash:r.currentStateHash,currentPrincipal:{subjectId:r.transaction.principal.subjectId},authorizationCodeHash:t.codeHash,authorizationCodeExpiresAt:t.expiresAt,grantId:t.grantId,now:z(r.now)});if(this.#r.delete(t.id),n.kind!=="approved")throw g("oauth_state_invalid","Authorization setup state is invalid, expired, or already used.")}async exchangeAuthorizationCode(t){let r=await this.exchangeAuthorizationCodeWithClientAuth({clientAuth:{method:"none",clientId:t.clientId},codeHash:t.codeHash,redirectUri:t.redirectUri,...t.resource===void 0?{}:{resource:t.resource},codeChallenge:t.codeChallenge,currentRefreshTokenHash:t.currentRefreshTokenHash,accessTokenHash:t.accessTokenHash,grantExpiresAt:t.grantExpiresAt,accessTokenExpiresAt:t.accessTokenExpiresAt,now:z(t.now)});return r.kind==="invalid_client"?{kind:"missing"}:r.kind==="exchanged"?{kind:"exchanged",grant:r.grant}:r}async saveAccessToken(t){throw g("internal_server_error","Runtime HTTP access-token save is covered by token exchange/refresh operations.")}async validateAccessToken(t){return this.client.validateAccessToken({tokenHash:t.tokenHash,now:z(t.now)})}async rotateRefreshToken(t){throw g("internal_server_error","Runtime HTTP refresh-token rotation is covered by the token refresh operation.")}async revokeOAuthToken(t){let r=await this.revokeOAuthTokenWithClientAuth({clientAuth:{method:"none",clientId:t.clientId},tokenHash:t.tokenHash,now:z(t.now)});return r.kind==="invalid_client"?{kind:"missing"}:r}async revokeGrant(t){throw g("internal_server_error","Runtime HTTP grant revocation is not exposed as a standalone storage operation.")}decideAuthorizationSetup(t){return this.client.decideAuthorizationSetup(t)}exchangeAuthorizationCodeWithClientAuth(t){return this.client.exchangeAuthorizationCode(t)}refreshTokenWithClientAuth(t){return this.client.refreshToken(t)}revokeOAuthTokenWithClientAuth(t){return this.client.revokeOAuthToken(t)}authorizeAndLoadConnections(t){return this.client.authorizeAndLoadConnections(t)}#e(t){this.#t.has(t.clientId)||this.#t.set(t.clientId,{clientId:t.clientId,clientName:t.clientName,redirectUris:[],tokenEndpointAuthMethod:t.tokenEndpointAuthMethod,clientExpiresAt:z(new Date(864e10)),createdAt:z(new Date(0))})}},Hl=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpOAuthStateStore")}async save(t){await this.client.saveUpstreamOAuthState({record:t})}consumeForCallback(t){return this.client.consumeUpstreamOAuthState({id:t,now:z(new Date)})}},Gl=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpBrowserConnectTicketStore")}consume(t,r){return this.client.consumeBrowserConnectTicket({id:t,expiresAt:z(r),now:z(new Date)})}};function Sy(e={}){let t=new Ts(e);return{upstreamConnectionRepository:new Ll(t),downstreamOAuthRepository:new jl(t),oauthStateStore:new Hl(t),browserConnectTicketStore:new Gl(t)}}o(Sy,"createRuntimeHttpStorageBackend");var d0="__zuploMcpGatewayStorageBackend",Bl;function l0(e){return{upstreamConnectionRepository:new bs(e),downstreamOAuthRepository:new ys(e),oauthStateStore:new Cs(e),browserConnectTicketStore:new Is(e)}}o(l0,"createPostgresStorageBackend");function p0(e){let t=w_(e),r=v_(t);return l0(r)}o(p0,"buildPostgresStorageBackend");function m0(){let e=_s().TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING;return e?p0(e):Sy()}o(m0,"buildProductionStorageBackend");function V(){let e=globalThis[d0];return e||(Bl||(Bl=m0()),Bl)}o(V,"getStorage");function Fl(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Fl,"readBearerToken");function h0(e,t,r){return _t(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(h0,"gatewayAuthenticationRequiredResponse");async function f0(e,t,r){let n=await V().downstreamOAuthRepository.validateAccessToken({tokenHash:await ee(e),now:new Date});if(n.kind!=="valid")throw t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed"),g("authentication_required","Gateway access token is expired, revoked, or invalid.");return n.record}o(f0,"validateGatewayAccessToken");function g0(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.virtualServerId!==e.virtualServerId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedVirtualServerId:e.virtualServerId,tokenVirtualServerId:e.accessToken.virtualServerId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(g0,"assertAccessTokenResource");function _0(e,t,r){return _t(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":gs({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ve} scope required by this MCP resource.`,scope:ve})}})}o(_0,"insufficientScopeResponse");function y0(e){return{subjectId:e.subjectId,roles:e.roles}}o(y0,"principalFromAccessToken");function w0(e){let t=_e(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),_t(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":gs({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(w0,"gatewayTokenRejectedResponse");async function Vl(e,t){let r=jn(t),n=Qr(r.virtualServerId,e.url),a=Fl(e),i=gs({virtualServerId:r.virtualServerId,requestUrl:e.url});if(!a)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",virtualServerId:r.virtualServerId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),h0(e,t,i);try{let s=await f0(a,t,r.virtualServerId);if(g0({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ve)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ve,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),_0(e,t,r.virtualServerId);let u=y0(s);return f_(t,u),Kd(t,u),e}catch(s){return w0({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Vl,"gatewayTokenInbound");var S0=2,vy=4,v0=24,R0=16,Ry=512,b0=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,C0=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,I0=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,T0=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,A0=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,k0=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function by(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(by,"readRoute");function E0(e){let t=by(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(E0,"readRoutePath");function x0(e){let t=by(e)?.raw;if(typeof t!="function")return;let r=t();if(!r||typeof r!="object")return;let n=r.operationId;return typeof n=="string"&&n.length>0?n:void 0}o(x0,"readRouteOperationId");function P0(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(P0,"deriveStatusClass");function O0(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="shared"?"shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(O0,"deriveOriginAttributionMode");function U0(e){if(!e)return;let t=e.toLowerCase();return t.includes("desktop")||t.includes("claude")||t.includes("chatgpt")?"desktop":t.includes("vscode")||t.includes("cursor")||t.includes("zed")||t.includes("jetbrains")||t.includes("ide")?"ide":t.includes("extension")?"extension":t.includes("agent")||t.includes("bot")||t.includes("worker")||t.includes("service")?"service":"unknown"}o(U0,"deriveClientKind");function N0(e,t){return t==="success"?"none":e===J.MCP_GATEWAY_REQUEST_RECEIVED||e===J.MCP_GATEWAY_REQUEST_REJECTED||e===J.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===J.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===J.MCP_GATEWAY_POLICY_DECISION?"policy":e===J.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===J.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===J.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o(N0,"deriveFailureStage");function z0(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===J.MCP_GATEWAY_POLICY_DECISION||e===J.MCP_GATEWAY_GUARDRAIL_DECISION||e===J.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===J.MCP_GATEWAY_CAPABILITY_FAILED||e===J.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===J.MCP_GATEWAY_REQUEST_REJECTED||e===J.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(z0,"deriveFailureOrigin");function $0(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===J.MCP_GATEWAY_POLICY_DECISION?"policy":e===J.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===J.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===J.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===J.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o($0,"deriveReasonClass");function D0(e){return e.length<=Ry?e:`${e.slice(0,Ry)}...`}o(D0,"truncateAnalyticsString");function M0(e){return D0(e.replace(C0,"$1[REDACTED]$3").replace(T0,"$1$2[REDACTED]").replace(I0,"$1$2[REDACTED]").replace(A0,"Bearer [REDACTED]").replace(k0,"Basic [REDACTED]"))}o(M0,"redactAnalyticsString");function Cy(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return M0(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=vy?"[DEPTH_LIMIT]":e.slice(0,R0).map(r=>Cy(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=vy?"[DEPTH_LIMIT]":Iy(e,t+1)}}o(Cy,"sanitizeAnalyticsValue");function Iy(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,v0)){if(b0.test(n)){r[n]="[REDACTED]";continue}let i=Cy(a,t);i!==void 0&&(r[n]=i)}return Object.keys(r).length===0?void 0:r}o(Iy,"sanitizeMcpGatewayAnalyticsAttributes");function M(e){return e===void 0?null:e}o(M,"nullable");function q0(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(q0,"readEnvironment");function L0(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(L0,"readRequestId");function j0(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(j0,"attributesToJsonString");function H0(e,t){let r=Cl(e),n=aa(e),a=Iy(t.attributes),i=L0(e),s=t.ownerMode??t.routeBinding?.ownerMode??null,u=t.upstreamAuthMode??t.routeBinding?.authMode??null,d=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId??null,p=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId??null,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName??null,m=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId??null,f=t.clientKind??U0(t.clientName)??null,_=O0(s??void 0,u??void 0)??null,w=P0(t.httpStatusCode)??null,y=t.reasonClass??$0(t.eventType,t.outcome),S=t.failureOrigin??z0(t.eventType,t.outcome),v=t.failureStage??N0(t.eventType,t.outcome);return{schemaVersion:S0,outcome:t.outcome,subjectId:M(r?.subjectId),environment:q0(e),traceId:t.traceId??i,spanId:M(t.spanId),parentEventId:M(t.parentEventId),mcpSessionId:M(t.mcpSessionId),routeSurface:M(t.routeSurface),routePath:E0(e)??null,operationId:x0(e)??null,virtualServerName:d,virtualServerTitle:M(t.virtualServerTitle),upstreamServerName:p,upstreamServerTitle:l,upstreamBindingId:M(t.upstreamBindingId),clientName:M(t.clientName),clientTitle:M(t.clientTitle),clientVersion:M(t.clientVersion),clientKind:f,authProfileId:m,upstreamAuthMode:u,ownerMode:s,authMethod:M(t.authMethod),originAttributionMode:_,httpMethod:M(t.httpMethod),httpStatusCode:M(t.httpStatusCode),statusClass:w,mcpMethod:M(t.mcpMethod),mcpProtocolVersion:M(t.mcpProtocolVersion),mcpStatus:M(t.mcpStatus),mcpErrorType:M(t.mcpErrorType),applicationError:M(t.applicationError),applicationErrorCode:M(t.applicationErrorCode),toolResultIsError:M(t.toolResultIsError),capabilityType:M(t.capabilityType),capabilityName:M(t.capabilityName),capabilityTitle:M(t.capabilityTitle),upstreamCapabilityName:M(t.upstreamCapabilityName),upstreamCapabilityTitle:M(t.upstreamCapabilityTitle),capabilitySchemaHash:M(t.capabilitySchemaHash),policyId:M(t.policyId),policyAction:M(t.policyAction),guardrailType:M(t.guardrailType),guardrailDirection:M(t.guardrailDirection),guardrailFindingCount:M(t.guardrailFindingCount),redactionCount:M(t.redactionCount),requestMutated:M(t.requestMutated),responseMutated:M(t.responseMutated),latencyMs:M(t.latencyMs),gatewayLatencyMs:M(t.gatewayLatencyMs),upstreamLatencyMs:M(t.upstreamLatencyMs),authLatencyMs:M(t.authLatencyMs),policyLatencyMs:M(t.policyLatencyMs),requestBytes:M(t.requestBytes),responseBytes:M(t.responseBytes),estimatedInputTokens:M(t.estimatedInputTokens),estimatedOutputTokens:M(t.estimatedOutputTokens),estimatedContextTokens:M(t.estimatedContextTokens),contextPressureBucket:M(t.contextPressureBucket),responseMimeTypes:M(t.responseMimeTypes),base64Suspected:M(t.base64Suspected),truncated:M(t.truncated),isLargePayloadRequest:M(t.isLargePayloadRequest),isLargePayloadResponse:M(t.isLargePayloadResponse),payloadCaptureMode:M(t.payloadCaptureMode),reasonCode:M(t.reasonCode),reasonClass:y,errorType:t.errorType??t.reasonCode??null,failureOrigin:S,failureStage:v,customMetadataJson:M(t.customMetadataJson),attributesJson:j0(a)}}o(H0,"buildMcpGatewayAnalyticsMetadata");function ot(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,H0(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(ot,"emitMcpGatewayAnalyticsEvent");function at(e){let t=yt().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(at,"getUpstreamServerConfig");function G0(e){let t=yt().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(G0,"resolveUpstreamAuthProfileId");function Er(e){G0(e);let t=yt().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(Er,"getUpstreamAuthConfig");function rn(e,t){let r=Er({upstreamServerId:e,authProfileId:t});if(!Og(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(rn,"requireUpstreamOAuthConfig");var B0={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},user_oauth:{authMode:"user_oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},static_secret:{authMode:"static_secret",ownerMode:"none",connectSupport:"none",connectUnsupportedDetail:"Static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"configured_static_secret"},"shared-secret":{authMode:"shared-secret",ownerMode:"shared",connectSupport:"none",connectUnsupportedDetail:"Shared static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"shared_secret_connection"},"user-secret":{authMode:"user-secret",ownerMode:"user",connectSupport:"user_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_secret_connection"}};function Mt(e){return B0[e]}o(Mt,"describeUpstreamAuthMode");function As(e){return Mt(e).ownerMode}o(As,"resolveOwnerModeForUpstreamAuthMode");ae();import{errors as Oy,jwtVerify as Uy,SignJWT as Ny}from"jose";import{base64url as F0}from"jose";var V0=new TextEncoder,Kl=32;function Ty(e,t={}){let r=[K0(e),V0.encode(e)],n;for(let a of r)if(a){if(a.byteLength>=Kl){n=a;break}(n===void 0||a.byteLength>n.byteLength)&&(n=a)}if(n===void 0||n.byteLength<Kl){let a=t.name??"secret key material",i=n?.byteLength??0;throw new Error(`${a} must decode to at least ${Kl} bytes (got ${i}). Generate a high-entropy value with for example: openssl rand -base64 32 | tr '+/' '-_' | tr -d '='.`)}return n}o(Ty,"decodeConfiguredSecretKeyMaterial");function K0(e){try{return F0.decode(e)}catch{return}}o(K0,"tryDecodeBase64Url");var Ay=new Map,ky=new Map;function Z0(e){let t=Ay.get(e);return t||(t=Ty(_s()[e],{name:e}),Ay.set(e,t)),t}o(Z0,"getMasterKeyMaterial");async function qt(e){let t=ky.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Z0(e.envVar));return ky.set(e.purpose,r),r}o(qt,"readCachedDerivedKey");var W0="SHA-256";var J0="zuplo-mcp-gateway:",Y0=new TextEncoder,Ey=new WeakMap;async function xr(e,t){let r=Ey.get(e);r||(r=new Map,Ey.set(e,r));let n=r.get(t);if(n)return n;let a=await X0(e,t);return r.set(t,a),a}o(xr,"deriveGatewaySigningKey");async function X0(e,t){let r=xy(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Y0.encode(`${J0}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:W0,salt:new Uint8Array,info:xy(a)},n,32*8);return new Uint8Array(i)}o(X0,"hkdfExpand");function xy(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(xy,"copyToArrayBuffer");var ks="HS256",zy=15*60,Q0=15*60,Es="zuplo-mcp-gateway",xs="zuplo-mcp-gateway",eO=C_.extend({id:Kn}),tO=eO.extend({exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),$y=Fn.extend({id:fa,purpose:c.literal("browser_connect")}),rO=Fn.extend({purpose:c.literal("browser_connect")}),nO=$y.extend({exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),Dy=zy*1e3;async function My(){return qt({purpose:"oauth-state",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>xr(e,"oauth-state"),"derive")})}o(My,"getOAuthStateKey");async function qy(){return qt({purpose:"browser-connect",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>xr(e,"browser-connect"),"derive")})}o(qy,"getBrowserConnectKey");async function Ly(e){let t=Math.floor(Date.now()/1e3)+zy;return new Ny(e).setProtectedHeader({alg:ks,typ:"JWT"}).setIssuer(Es).setAudience(xs).setIssuedAt().setExpirationTime(t).sign(await My())}o(Ly,"signOAuthState");async function Ps(e){try{let{payload:t}=await Uy(e,await My(),{algorithms:[ks],issuer:Es,audience:xs});return tO.parse(t)}catch(t){throw t instanceof Oy.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(Ps,"verifyOAuthState");async function jy(e){let t=Math.floor(Date.now()/1e3)+Q0,r=rO.parse(e),n=$y.parse({...r,id:E_()});return new Ny(n).setProtectedHeader({alg:ks,typ:"JWT"}).setIssuer(Es).setAudience(xs).setIssuedAt().setExpirationTime(t).sign(await qy())}o(jy,"signBrowserConnectTicket");async function Os(e){try{let{payload:t}=await Uy(e,await qy(),{algorithms:[ks],issuer:Es,audience:xs});return nO.parse(t)}catch(t){throw t instanceof Oy.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(Os,"verifyBrowserConnectTicket");async function Us(e){if((await V().browserConnectTicketStore.consume(e.id,new Date(e.exp*1e3))).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(Us,"consumeBrowserConnectTicket");function oO(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(oO,"buildConnectRequiredMessage");async function Hy(e){let t=de(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("virtualServerId",e.virtualServerId),r.searchParams.set("browserTicket",await jy({...ha(e),purpose:"browser_connect"})),r.toString()}o(Hy,"buildGatewayBrowserTicketUrl");function aO(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(aO,"buildGatewayConnectPath");async function Zl(e){return Hy({...e,path:aO(e.upstreamServerId),redirect:!0})}o(Zl,"buildGatewayConnectUrl");async function Gy(e){return Hy({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(Gy,"buildGatewayAppPasswordCaptureUrl");async function Wn(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Zl(t),message:oO(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Wn,"buildRedirectConnectRequiredResponse");function By(e){return Fy({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(By,"buildAdminConnectRequiredResponse");function Fy(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(Fy,"buildAdminSetupRequiredResponse");function Vy(e){return Fy({...e,message:e.requiresReconsent?`An administrator must replace the ${e.upstreamDisplayName} static credential before this tool can be used.`:`An administrator must configure the ${e.upstreamDisplayName} static credential before this tool can be used.`})}o(Vy,"buildAdminStaticSecretRequiredResponse");ae();import{base64url as Pr}from"jose";var iO="SHA-256",Yn="AES-GCM",sO=12,Jl="zuplo-secret",Yl=1,Ky="env:TOKEN_ENCRYPTION_KEY",cO=c.object({version:c.literal(Yl),keyId:c.literal(Ky),algorithm:c.literal(Yn),iv:c.string().min(1),ciphertext:c.string().min(1)}).strict();function Jn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Jn,"copyToArrayBuffer");async function Wl(){return qt({purpose:"token-encryption",envVar:"TOKEN_ENCRYPTION_KEY",derive:o(async e=>{let t=await crypto.subtle.digest(iO,Jn(e));return crypto.subtle.importKey("raw",t,{name:Yn},!1,["encrypt","decrypt"])},"derive")})}o(Wl,"getEncryptionKey");function Zy(e){return Jn(new TextEncoder().encode(`${Jl}:v${e.version}:${e.keyId}`))}o(Zy,"getAssociatedData");function uO(e){return`${Jl}:v${e.version}:${Pr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(uO,"encodeEnvelope");function dO(e){let t=`${Jl}:v${Yl}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Pr.decode(r));return cO.parse(JSON.parse(n))}o(dO,"decodeEnvelope");async function nn(e){let t=await Wl(),r=crypto.getRandomValues(new Uint8Array(sO)),n={version:Yl,keyId:Ky},a=await crypto.subtle.encrypt({name:Yn,iv:r,additionalData:Zy(n)},t,new TextEncoder().encode(e));return uO({...n,algorithm:Yn,iv:Pr.encode(r),ciphertext:Pr.encode(new Uint8Array(a))})}o(nn,"encryptSecret");async function nr(e){let t=dO(e);if(t){let s=await Wl(),u=await crypto.subtle.decrypt({name:Yn,iv:Jn(Pr.decode(t.iv)),additionalData:Zy(t)},s,Jn(Pr.decode(t.ciphertext)));return new TextDecoder().decode(u)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await Wl(),i=await crypto.subtle.decrypt({name:Yn,iv:Jn(Pr.decode(r))},a,Jn(Pr.decode(n)));return new TextDecoder().decode(i)}o(nr,"decryptSecret");function lO(e,t){let r=Er({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(lO,"requireTenantStaticSecretConfig");function Wy(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(Wy,"hasUsableTenantStaticSecret");async function pO(e){if(!Wy(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await nr(e.connection.metadata.encryptedStaticSecret)}}o(pO,"resolveTenantStaticSecretCredential");async function Jy(e){let t=at(e.upstreamServerId);lO(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await V().upstreamConnectionRepository.batchGet([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Wy(r))return{kind:"authorized",credential:await pO({connection:r})};let n={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:Vy(n)}}o(Jy,"resolveTenantStaticSecretCredentialForRequest");ae();async function Xl(e){return V().upstreamConnectionRepository.upsert({id:Rs(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(Xl,"upsertStaticSecretConnection");var mO=c.string().trim().min(1).max(320),hO=c.string().min(1).max(4096),fO=c.string().trim().min(1).max(4096);function Ql(e,t){let r=Er({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Ql,"requireUserStaticSecretConfig");function gO(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(gO,"encodeBase64Utf8");function _O(e){return`Basic ${gO(`${e.username}:${e.appPassword}`)}`}o(_O,"buildBasicAuthHeader");function Yy(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(Yy,"hasEncryptedUserStaticSecret");async function yO(e){if(!Yy(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await nr(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:_O({username:e.connection.metadata.staticSecretUsername,appPassword:await nr(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(yO,"resolveUserStaticSecretCredential");async function Xy(e){if(Ql(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=mO.parse(e.username),n=hO.parse(e.appPassword);return Xl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await nn(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(Xy,"saveUserStaticSecretCredential");async function Ns(e){let t=Ql(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=fO.parse(e.token);return Xl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await nn(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Ns,"saveUserStaticBearerTokenCredential");function ep(e,t){return Ql(e,t)}o(ep,"readUserStaticSecretCaptureConfig");async function Qy(e){let t=at(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await V().upstreamConnectionRepository.batchGet([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Yy(r))return{kind:"authorized",credential:await yO({connection:r})};let n={requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:await Wn(n)}}o(Qy,"resolveUserStaticSecretCredentialForRequest");function ew(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return Gy({requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}})}o(ew,"buildUserStaticSecretConnectUrl");var tp;tp=globalThis.crypto;async function wO(e){return(await tp).getRandomValues(new Uint8Array(e))}o(wO,"getRandomValues");async function SO(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await wO(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(SO,"random");async function vO(e){return await SO(e)}o(vO,"generateVerifier");async function RO(e){let t=await(await tp).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(RO,"generateChallenge");async function rp(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await vO(e),r=await RO(t);return{code_verifier:t,code_challenge:r}}o(rp,"pkceChallenge");ae();var Le=um().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:mm.custom,message:"URL must be parseable",fatal:!0}),sm}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),zs=Ae({resource:h().url(),authorization_servers:C(Le).optional(),jwks_uri:h().url().optional(),scopes_supported:C(h()).optional(),bearer_methods_supported:C(h()).optional(),resource_signing_alg_values_supported:C(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:C(h()).optional(),dpop_signing_alg_values_supported:C(h()).optional(),dpop_bound_access_tokens_required:ce().optional()}),_a=Ae({issuer:h(),authorization_endpoint:Le,token_endpoint:Le,registration_endpoint:Le.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),service_documentation:Le.optional(),revocation_endpoint:Le.optional(),revocation_endpoint_auth_methods_supported:C(h()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(h()).optional(),introspection_endpoint:h().optional(),introspection_endpoint_auth_methods_supported:C(h()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(h()).optional(),code_challenge_methods_supported:C(h()).optional(),client_id_metadata_document_supported:ce().optional()}),bO=Ae({issuer:h(),authorization_endpoint:Le,token_endpoint:Le,userinfo_endpoint:Le.optional(),jwks_uri:Le,registration_endpoint:Le.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),acr_values_supported:C(h()).optional(),subject_types_supported:C(h()),id_token_signing_alg_values_supported:C(h()),id_token_encryption_alg_values_supported:C(h()).optional(),id_token_encryption_enc_values_supported:C(h()).optional(),userinfo_signing_alg_values_supported:C(h()).optional(),userinfo_encryption_alg_values_supported:C(h()).optional(),userinfo_encryption_enc_values_supported:C(h()).optional(),request_object_signing_alg_values_supported:C(h()).optional(),request_object_encryption_alg_values_supported:C(h()).optional(),request_object_encryption_enc_values_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),display_values_supported:C(h()).optional(),claim_types_supported:C(h()).optional(),claims_supported:C(h()).optional(),service_documentation:h().optional(),claims_locales_supported:C(h()).optional(),ui_locales_supported:C(h()).optional(),claims_parameter_supported:ce().optional(),request_parameter_supported:ce().optional(),request_uri_parameter_supported:ce().optional(),require_request_uri_registration:ce().optional(),op_policy_uri:Le.optional(),op_tos_uri:Le.optional(),client_id_metadata_document_supported:ce().optional()}),$s=I({...bO.shape,..._a.pick({code_challenge_methods_supported:!0}).shape}),ya=I({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:hm.number().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),rw=I({error:h(),error_description:h().optional(),error_uri:h().optional()}),tw=Le.optional().or(O("").transform(()=>{})),CO=I({redirect_uris:C(Le),token_endpoint_auth_method:h().optional(),grant_types:C(h()).optional(),response_types:C(h()).optional(),client_name:h().optional(),client_uri:Le.optional(),logo_uri:tw,scope:h().optional(),contacts:C(h()).optional(),tos_uri:tw,policy_uri:h().optional(),jwks_uri:Le.optional(),jwks:lm().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),np=I({client_id:h(),client_secret:h().optional(),client_id_issued_at:re().optional(),client_secret_expires_at:re().optional()}).strip(),wa=CO.merge(np),nK=I({error:h(),error_description:h().optional()}).strip(),oK=I({token:h(),token_type_hint:h().optional()}).strip();function nw(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(nw,"resourceUrlFromServerUrl");function ow({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return a.startsWith(i)}o(ow,"checkResourceAllowed");var Ie=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Sa=class extends Ie{static{o(this,"InvalidRequestError")}};Sa.errorCode="invalid_request";var on=class extends Ie{static{o(this,"InvalidClientError")}};on.errorCode="invalid_client";var an=class extends Ie{static{o(this,"InvalidGrantError")}};an.errorCode="invalid_grant";var sn=class extends Ie{static{o(this,"UnauthorizedClientError")}};sn.errorCode="unauthorized_client";var va=class extends Ie{static{o(this,"UnsupportedGrantTypeError")}};va.errorCode="unsupported_grant_type";var Ra=class extends Ie{static{o(this,"InvalidScopeError")}};Ra.errorCode="invalid_scope";var ba=class extends Ie{static{o(this,"AccessDeniedError")}};ba.errorCode="access_denied";var or=class extends Ie{static{o(this,"ServerError")}};or.errorCode="server_error";var Ca=class extends Ie{static{o(this,"TemporarilyUnavailableError")}};Ca.errorCode="temporarily_unavailable";var Ia=class extends Ie{static{o(this,"UnsupportedResponseTypeError")}};Ia.errorCode="unsupported_response_type";var Ta=class extends Ie{static{o(this,"UnsupportedTokenTypeError")}};Ta.errorCode="unsupported_token_type";var Aa=class extends Ie{static{o(this,"InvalidTokenError")}};Aa.errorCode="invalid_token";var ka=class extends Ie{static{o(this,"MethodNotAllowedError")}};ka.errorCode="method_not_allowed";var Ea=class extends Ie{static{o(this,"TooManyRequestsError")}};Ea.errorCode="too_many_requests";var cn=class extends Ie{static{o(this,"InvalidClientMetadataError")}};cn.errorCode="invalid_client_metadata";var xa=class extends Ie{static{o(this,"InsufficientScopeError")}};xa.errorCode="insufficient_scope";var Pa=class extends Ie{static{o(this,"InvalidTargetError")}};Pa.errorCode="invalid_target";var aw={[Sa.errorCode]:Sa,[on.errorCode]:on,[an.errorCode]:an,[sn.errorCode]:sn,[va.errorCode]:va,[Ra.errorCode]:Ra,[ba.errorCode]:ba,[or.errorCode]:or,[Ca.errorCode]:Ca,[Ia.errorCode]:Ia,[Ta.errorCode]:Ta,[Aa.errorCode]:Aa,[ka.errorCode]:ka,[Ea.errorCode]:Ea,[cn.errorCode]:cn,[xa.errorCode]:xa,[Pa.errorCode]:Pa};var ar=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function IO(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(IO,"isClientAuthMethod");var op="code",ap="S256";function TO(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&IO(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(TO,"selectClientAuthMethod");function AO(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":kO(a,i,r);return;case"client_secret_post":EO(a,i,n);return;case"none":xO(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(AO,"applyClientAuthentication");function kO(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(kO,"applyBasicAuth");function EO(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(EO,"applyPostAuth");function xO(e,t){t.set("client_id",e)}o(xO,"applyPublicAuth");async function sw(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=rw.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,u=aw[a]||or;return new u(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new or(a)}}o(sw,"parseErrorResponse");async function Or(e,t){try{return await ip(e,t)}catch(r){if(r instanceof on||r instanceof sn)return await e.invalidateCredentials?.("all"),await ip(e,t);if(r instanceof an)return await e.invalidateCredentials?.("tokens"),await ip(e,t);throw r}}o(Or,"auth");async function ip(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),u,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,u=s.resourceMetadata,p=s.authorizationServerMetadata??await uw(d,{fetchFn:i}),!u)try{u=await cw(t,{resourceMetadataUrl:l},i)}catch{}(p!==s.authorizationServerMetadata||u!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:u,authorizationServerMetadata:p})}else{let b=await $O(t,{resourceMetadataUrl:l,fetchFn:i});d=b.authorizationServerUrl,p=b.authorizationServerMetadata,u=b.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:u,authorizationServerMetadata:p})}let m=await PO(t,e,u),f=n||u?.scopes_supported?.join(" ")||e.clientMetadata.scope,_=await Promise.resolve(e.clientInformation());if(!_){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=p?.client_id_metadata_document_supported===!0,q=e.clientMetadataUrl;if(q&&!cp(q))throw new cn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${q}`);if(b&&q)_={client_id:q},await e.saveClientInformation?.(_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let je=await jO(d,{metadata:p,clientMetadata:e.clientMetadata,scope:f,fetchFn:i});await e.saveClientInformation(je),_=je}}let w=!e.redirectUrl;if(r!==void 0||w){let b=await LO(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}let y=await e.tokens();if(y?.refresh_token)try{let b=await qO(d,{metadata:p,clientInformation:_,refreshToken:y.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Ie)||b instanceof or))throw b}let S=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:R}=await DO(d,{metadata:p,clientInformation:_,state:S,redirectUrl:e.redirectUrl,scope:f,resource:m});return await e.saveCodeVerifier(R),await e.redirectToAuthorization(v),"REDIRECT"}o(ip,"authInternal");function cp(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(cp,"isHttpsUrl");async function PO(e,t,r){let n=nw(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ow({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(PO,"selectResourceURL");function up(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=sp(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=sp(e,"scope")||void 0,u=sp(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:u}}o(up,"extractWWWAuthenticateParams");function sp(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(sp,"extractFieldFromWwwAuth");async function cw(e,t,r=fetch){let n=await NO(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return zs.parse(await n.json())}o(cw,"discoverOAuthProtectedResourceMetadata");async function dp(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?dp(e,void 0,r):void 0;throw n}}o(dp,"fetchWithCorsRetry");function OO(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(OO,"buildWellKnownPath");async function iw(e,t,r=fetch){return await dp(e,{"MCP-Protocol-Version":t},r)}o(iw,"tryMetadataDiscovery");function UO(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(UO,"shouldAttemptFallback");async function NO(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??mr,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=OO(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let u=await iw(s,i,r);if(!n?.metadataUrl&&UO(u,a.pathname)){let d=new URL(`/.well-known/${t}`,a);u=await iw(d,i,r)}return u}o(NO,"discoverMetadataWithFallback");function zO(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),n.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(zO,"buildDiscoveryUrls");async function uw(e,{fetchFn:t=fetch,protocolVersion:r=mr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=zO(e);for(let{url:i,type:s}of a){let u=await dp(i,n,t);if(u){if(!u.ok){if(await u.body?.cancel(),u.status>=400&&u.status<500)continue;throw new Error(`HTTP ${u.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?_a.parse(await u.json()):$s.parse(await u.json())}}}o(uw,"discoverAuthorizationServerMetadata");async function $O(e,t){let r,n;try{r=await cw(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));let a=await uw(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o($O,"discoverOAuthServerInfo");async function DO(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(op))throw new Error(`Incompatible auth server: does not support response type ${op}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ap))throw new Error(`Incompatible auth server: does not support code challenge method ${ap}`)}else u=new URL("/authorize",e);let d=await rp(),p=d.code_verifier,l=d.code_challenge;return u.searchParams.set("response_type",op),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",l),u.searchParams.set("code_challenge_method",ap),u.searchParams.set("redirect_uri",String(n)),i&&u.searchParams.set("state",i),a&&u.searchParams.set("scope",a),a?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:p}}o(DO,"startAuthorization");function MO(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(MO,"prepareAuthorizationCodeRequest");async function dw(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:s}){let u=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(d,r,u,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],m=TO(n,l);AO(m,n,d,r)}let p=await(s??fetch)(u,{method:"POST",headers:d,body:r});if(!p.ok)throw await sw(p);return ya.parse(await p.json())}o(dw,"executeTokenRequest");async function qO(e,{metadata:t,clientInformation:r,refreshToken:n,resource:a,addClientAuthentication:i,fetchFn:s}){let u=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await dw(e,{metadata:t,tokenRequestParams:u,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(qO,"refreshAuthorization");async function LO(e,t,{metadata:r,resource:n,authorizationCode:a,fetchFn:i}={}){let s=e.clientMetadata.scope,u;if(e.prepareTokenRequest&&(u=await e.prepareTokenRequest(s)),!u){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();u=MO(a,p,e.redirectUrl)}let d=await e.clientInformation();return dw(t,{metadata:r,tokenRequestParams:u,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(LO,"fetchToken");async function jO(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await sw(s);return wa.parse(await s.json())}o(jO,"registerClient");function HO(){let e=go.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}o(HO,"isTestOnlyAllowHttpLoopbackIdpEnabled");var GO=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),BO=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function lw(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}o(lw,"parseIpv4Octets");function FO([e,t],r){let n=r.firstMax??r.first;return e<r.first||e>n?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}o(FO,"ipv4RangeMatches");function pw(e){let t=lw(e);return t!==void 0&&BO.some(r=>FO(t,r))}o(pw,"isPrivateIpv4");function lp(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}o(lp,"parseIpv6Word");function VO(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(VO,"formatIpv4FromWords");function KO(e){let t=e.slice(7),r=lw(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=lp(n),u=lp(a);return i===void 0&&s!==void 0&&u!==void 0?VO(s,u):void 0}o(KO,"parseIpv6MappedIpv4");function ZO(e){return lp(e.split(":").find(Boolean))}o(ZO,"readFirstIpv6Hextet");function WO(e){let t=wt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=KO(t);return n===void 0||pw(n)}let r=ZO(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(WO,"isPrivateIpv6");function pp(e){let t=wt(e);return GO.has(t)||t.endsWith(".internal")||pw(t)||WO(t)}o(pp,"isBlockedOutboundHostname");function mw(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);let r=Ve(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=wt(t.hostname);if(!r&&pp(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(mw,"validateConfiguredOutboundUrl");function hw(e){let t=new URL(e),r=Ve(t),n=r&&HO();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");let a=wt(t.hostname);if(!r&&pp(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(hw,"validateIdentityProviderUrl");function Ds(e){let t=new URL(e);if(t.protocol!=="https:"||t.pathname==="/"||t.username||t.password||t.search||t.hash)throw g("invalid_request","CIMD client_id must be an HTTPS URL with a path and no credentials, query, or fragment.");if(pp(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(Ds,"validateCimdClientMetadataUrl");function fw(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(fw,"mergeAbortSignals");async function JO(e){try{await e.cancel()}catch{}}o(JO,"cancelReader");async function Ms(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],a=0,i=await r.read();for(;!i.done;){let d=i.value;if(a+=d.byteLength,a>t.maxBytes)throw await JO(r),t.createLimitError();n.push(d),i=await r.read()}let s=new Uint8Array(a),u=0;for(let d of n)s.set(d,u),u+=d.byteLength;return s}o(Ms,"readBoundedByteStream");var YO=2,XO=1024*1024,QO=1e4,eU=new Set([301,302,303,307,308]),tU=["authorization","proxy-authorization","cookie","cookie2"];function mp(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(mp,"readRequestUrl");function Xn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Xn,"readRequestMethod");function rU(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(rU,"assertContentLengthWithinLimit");async function nU(e,t,r){return rU(e,t,r),Ms(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(nU,"readBoundedResponseBody");function oU(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(oU,"responseFromBufferedBody");function aU(e,t){if(!eU.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(aU,"resolveRedirectUrl");function gw(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(gw,"validateOutboundUrl");function iU(e,t){throw _e(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(iU,"normalizeFetchError");function Oa(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&ze(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Oa,"logOutboundFailure");async function sU(e,t,r,n,a,i,s){let u=Xn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Oa(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:u,host:gt(i),error:d,extra:{abortReason:s()}}),iU(d,a)}}o(sU,"fetchWithNormalizedError");function cU(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(cU,"assertRedirectAllowed");function uU(e,t){let r=new Headers(e);for(let n of tU)r.delete(n);for(let n of t)r.delete(n);return r}o(uU,"stripCrossOriginHeaders");function dU(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=uU(e.headers,a)),i}o(dU,"buildRedirectInit");function lU(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(lU,"buildInitialRequestInit");function pU(e){let t=Xn(e.currentInput,e.currentInit);cU({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=gw(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),a=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:dU(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(pU,"followRedirect");async function hp(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??YO,i=r.maxResponseBytes??XO,s=r.timeoutMs??QO,u=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=fw(l,t.signal),f=!1,_=setTimeout(()=>{f=!0,l.abort()},s),w=e,y=lU(e,t,l.signal),S;try{S=gw(mp(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(R){throw Oa(p,{event:"outbound_url_blocked",problemCode:n,method:Xn(e,t),host:gt(mp(e)),error:R}),clearTimeout(_),m?.(),R}let v=0;try{for(;;){let R=await sU(p,u,w,y,n,S,()=>f?`timeout_after_${s}ms`:void 0),b=aU(R,S);if(b!==void 0)try{let q=pU({currentInput:w,currentInit:y,currentUrl:S,redirectUrl:b,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});w=q.currentInput,y=q.currentInit,S=q.currentUrl,v=q.redirects;continue}catch(q){throw Oa(p,{event:"outbound_redirect_blocked",problemCode:n,method:Xn(w,y),host:gt(S),error:q,extra:{redirects:v,maxRedirects:a,redirectTargetHost:gt(b)}}),q}try{return oU(R,await nU(R,i,n))}catch(q){throw Oa(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Xn(w,y),host:gt(S),error:q,extra:{maxResponseBytes:i,status:R.status}}),q}}}finally{clearTimeout(_),m?.()}}o(hp,"runSafeOutboundExchange");async function fp(e,t,r){let n=await hp(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Oa(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Xn(e,t),host:gt(mp(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(fp,"runSafeOutboundJsonExchange");function qs(e,t={},r={}){return hp(e,t,{...r,validateUrl:mw})}o(qs,"fetchConfiguredOutbound");function _w(e,t={},r={}){return fp(e,t,{...r,validateUrl:hw})}o(_w,"fetchIdentityProviderJson");function yw(e,t={},r={}){return fp(e,t,{...r,validateUrl:Ds})}o(yw,"fetchCimdClientMetadataJson");ae();function gp(e){return`Zuplo MCP Gateway - ${e}`}o(gp,"buildGatewayOAuthClientName");function ww(e,t){let r=new URL(e,de(t));return Ve(r)&&wt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(ww,"buildGatewayOAuthRedirectUri");function _p(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(_p,"buildOAuthClientMetadataDocumentUrl");function Sw(e){return de(e)}o(Sw,"requireOAuthClientMetadataOrigin");function vw(e,t,r){let n=at(t),a=rn(t,r);return{client_id:_p({origin:e,upstreamServerId:t,authProfileId:r}),client_name:gp(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(vw,"buildOAuthClientMetadataDocument");var mU=c.union([wa,np]),hU=c.object({authorizationServerUrl:c.url(),resourceMetadataUrl:c.url().optional(),resourceMetadata:zs.optional(),authorizationServerMetadata:c.union([_a,$s]).optional()}).passthrough(),fU="Bearer";function gU(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(gU,"splitScopes");function _U(e){return ls.parse(e)}o(_U,"parsePkceCodeVerifier");function yU(e){if(typeof e.expires_in=="number")return z(new Date(Date.now()+e.expires_in*1e3))}o(yU,"readTokenExpiry");async function Rw(e){if(e!==void 0)return nn(JSON.stringify(e))}o(Rw,"encryptJson");async function bw(e,t){if(!e)return;let r=await nr(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(bw,"decryptJson");function wU(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}o(wU,"toOAuthDiscoveryState");function SU(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(SU,"clientInformationAllowsRedirectUri");function vU(e,t,r){let n=at(e),a=rn(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:gp(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(vU,"buildOAuthClientMetadata");function RU(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return wa.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(RU,"buildManualOAuthClientInformation");function bU(e,t,r){let n=_p({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return cp(n)?n:void 0}o(bU,"buildClientMetadataUrl");function Cw(e){for(let t of e)if(t!==void 0)return t}o(Cw,"firstDefined");function CU(e){let t=rn(e.target.upstreamServerId,e.target.authProfileId),r=vU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:RU({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=bU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(CU,"buildInitialOAuthClientSetup");function IU(e,t){if(t===void 0)return Cw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(IU,"readEncryptedClientInformation");function TU(e){return Cw([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(TU,"readEncryptedDiscoveryState");var un=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=CU({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=IU(t,this.configuredClientInformation),this.encryptedDiscoveryState=TU(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return Ly({id:t.id,...ha({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await Rw(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Rw(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ya.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0;this.cachedTokens=r,this.tokensLoaded=!0;let a={id:this.connection?.id??Rs(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await nn(r.access_token),encryptedRefreshToken:r.refresh_token?await nn(r.refresh_token):void 0,scopes:gU(r.scope??this.clientMetadataValue.scope),expiresAt:yU(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await V().upstreamConnectionRepository.upsert(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:_U(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:k_(),...ha({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:z(new Date(Date.now()+Dy)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await V().oauthStateStore.save(t),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await bw(this.encryptedClientInformation,mU)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!SU(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=wU(await bw(this.encryptedDiscoveryState,hU))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection?.encryptedAccessToken||this.connection.status!=="active")return;let t=ya.parse({access_token:await nr(this.connection.encryptedAccessToken),token_type:fU,refresh_token:this.connection.encryptedRefreshToken?await nr(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await V().upstreamConnectionRepository.upsert(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var AU=1e4,kU=256*1024,EU=2;function xU(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(xU,"hasUsableAccessToken");var PU="does not support dynamic client registration";function OU(e){return e instanceof Error&&e.message.includes(PU)}o(OU,"isDynamicClientRegistrationUnsupported");function UU(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(UU,"readOAuthFetchRequest");function NU(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(NU,"responseLooksJson");function Iw(e){return async(t,r)=>{let n=UU(t),a=await qs(t,r,{maxRedirects:EU,maxResponseBytes:kU,problemCode:"upstream_token_exchange_failed",timeoutMs:AU}),i=await a.clone().text();if(!NU(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(Iw,"createUpstreamOAuthFetch");async function Tw(e,t){try{return await Or(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Iw(t.upstreamServerId)})}catch(r){throw OU(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(Tw,"runUpstreamOAuth");async function zU(e,t){return Or(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Iw(t.upstreamServerId)})}o(zU,"exchangeUpstreamAuthorizationCode");async function Aw(e,t){let r=await Tw(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(Aw,"requireUpstreamAuthorizationRedirect");async function kw(e){if(xU(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Tw(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await LU({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.target.virtualServerId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(kw,"authorizeUpstreamOAuthSession");async function $U(e){let t=await Ps(e.stateToken),r=await V().oauthStateStore.consumeForCallback(t.id),n=DU(r);return MU({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),qU(n),n}o($U,"consumeStoredCallbackState");function DU(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(DU,"readConsumedCallbackState");function MU(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(MU,"assertStoredCallbackStateMatches");function qU(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(qU,"assertStoredCallbackStateFresh");async function LU(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),By(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Wn(t)}o(LU,"buildOAuthConnectRequiredResponse");async function Ew(e){let t=await $U({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Vn(t),[n]=await V().upstreamConnectionRepository.batchGet([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new un(a),s=await zU(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(Ew,"finishUpstreamOAuthCallback");async function xw(e){let t=at(e.upstreamServerId),r=rn(e.upstreamServerId,e.authProfileId),n=ww(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await V().upstreamConnectionRepository.batchGet([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:de(e.request.url)}}}o(xw,"prepareUpstreamOAuthRequest");async function Pw(e){let t=await xw(e),r=new un({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Aw(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Pw,"startUpstreamConnect");async function Ow(e){let t=await xw(e),r=new un({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return kw({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Ow,"authorizeUpstreamRequest");function jU(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(jU,"resolveStaticSecretCredential");async function Uw(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user_oauth":return Ow({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"shared-secret":return Jy({owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"static_secret":{let n=Er({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static_secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:jU(n.secret,t.upstreamServerId)}}case"user-secret":return Qy({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(Uw,"resolveUpstreamCredentialForRoute");async function Nw(e){let t=kr(e.principal.subjectId),r=yt().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user-secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await Ns({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(Nw,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function zw(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,virtualServerId:e.connectRequest.virtualServerId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},n=Mt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await Pw(r);break;case"user_secret_capture":t=await ew(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(zw,"startUpstreamConnectForRequest");async function $w(e){let r=(await Ps(e.callbackRequest.state)).authProfileId,n=Er({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(Mt(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Ew({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:at(e.callbackRequest.upstreamServerId)})}o($w,"finishUpstreamCallbackForRequest");var Ls=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=gr,n){let a=this._client,i={...n,task:n?.task??(a.isToolTask(t.name)?{}:void 0)},s=a.requestStream({method:"tools/call",params:t},r,i),u=a.getToolOutputValidator(t.name);for await(let d of s){if(d.type==="result"&&u){let p=d.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new k(P.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(p.structuredContent)try{let l=u(p.structuredContent);if(!l.valid){yield{type:"error",error:new k(P.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof k){yield{type:"error",error:l};return}yield{type:"error",error:new k(P.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield d}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function js(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let a of Object.keys(n)){let i=n[a];r[a]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[a]=i.default),r[a]!==void 0&&js(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&js(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&js(r,t)}}o(js,"applyElicitationDefaults");function HU(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}o(HU,"getSupportedElicitationModes");var Hs=class extends vn{static{o(this,"Client")}constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Mn,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Vc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Gc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Nc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ls(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ui(this._capabilities,t)}setRequestHandler(t,r){let a=gn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(lr(a)){let u=a;i=u._zod?.def?.value??u.value}else{let u=a;i=u._def?.value??u.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let u=o(async(d,p)=>{let l=Ke(Wc,d);if(!l.success){let R=l.error instanceof Error?l.error.message:String(l.error);throw new k(P.InvalidParams,`Invalid elicitation request: ${R}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:f,supportsUrlMode:_}=HU(this._capabilities.elicitation);if(m.mode==="form"&&!f)throw new k(P.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!_)throw new k(P.InvalidParams,"Client does not support URL-mode elicitation requests");let w=await Promise.resolve(r(d,p));if(m.task){let R=Ke(Zt,w);if(!R.success){let b=R.error instanceof Error?R.error.message:String(R.error);throw new k(P.InvalidParams,`Invalid task creation result: ${b}`)}return R.data}let y=Ke(_r,w);if(!y.success){let R=y.error instanceof Error?y.error.message:String(y.error);throw new k(P.InvalidParams,`Invalid elicitation result: ${R}`)}let S=y.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&S.action==="accept"&&S.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{js(v,S.content)}catch{}return S},"wrappedHandler");return super.setRequestHandler(t,u)}if(s==="sampling/createMessage"){let u=o(async(d,p)=>{let l=Ke(Zc,d);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new k(P.InvalidParams,`Invalid sampling request: ${S}`)}let{params:m}=l.data,f=await Promise.resolve(r(d,p));if(m.task){let S=Ke(Zt,f);if(!S.success){let v=S.error instanceof Error?S.error.message:String(S.error);throw new k(P.InvalidParams,`Invalid task creation result: ${v}`)}return S.data}let w=m.tools||m.toolChoice?To:qr,y=Ke(w,f);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new k(P.InvalidParams,`Invalid sampling result: ${S}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,u)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:mr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Tc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!hr.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Ki(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Zi(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Kt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Jc,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Kt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Hc,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},$c,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ec,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},xc,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Uc,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Kt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Kt,r)}async callTool(t,r=gr,n){if(this.isToolTaskRequired(t.name))throw new k(P.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let a=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!a.structuredContent&&!a.isError)throw new k(P.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(a.structuredContent)try{let s=i(a.structuredContent);if(!s.valid)throw new k(P.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof k?s:new k(P.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return a}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let a=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},Fc,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=xm.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:u}=i.data,{onChanged:d}=n,p=o(async()=>{if(!s){d(null,null);return}try{let m=await a();d(null,m)}catch(m){let f=m instanceof Error?m:new Error(String(m));d(f,null)}},"refresh"),l=o(()=>{if(u){let m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);let f=setTimeout(p,u);this._listChangedDebounceTimers.set(t,f)}else p()},"handler");this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Gs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(Gs,"normalizeHeaders");function Dw(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...Gs(t.headers),...Gs(n.headers)}:t.headers};return e(r,a)}:e}o(Dw,"createFetchWithInit");var Bs=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function yp(e){}o(yp,"noop");function Mw(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=yp,onError:r=yp,onRetry:n=yp,onComment:a}=e,i="",s=!0,u,d="",p="";function l(y){let S=s?y.replace(/^\xEF\xBB\xBF/,""):y,[v,R]=GU(`${i}${S}`);for(let b of v)m(b);i=R,s=!1}o(l,"feed");function m(y){if(y===""){_();return}if(y.startsWith(":")){a&&a(y.slice(y.startsWith(": ")?2:1));return}let S=y.indexOf(":");if(S!==-1){let v=y.slice(0,S),R=y[S+1]===" "?2:1,b=y.slice(S+R);f(v,b,y);return}f(y,"",y)}o(m,"parseLine");function f(y,S,v){switch(y){case"event":p=S;break;case"data":d=`${d}${S}
969
- `;break;case"id":u=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new Bs(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:v}));break;default:r(new Bs(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:S,line:v}));break}}o(f,"processField");function _(){d.length>0&&t({id:u,event:p||void 0,data:d.endsWith(`
970
- `)?d.slice(0,-1):d}),u=void 0,d="",p=""}o(_,"dispatchEvent");function w(y={}){i&&y.consume&&m(i),s=!0,u=void 0,d="",p="",i=""}return o(w,"reset"),{feed:l,reset:w}}o(Mw,"createParser");function GU(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
971
- `,n),s=-1;if(a!==-1&&i!==-1?s=Math.min(a,i):a!==-1?a===e.length-1?s=-1:s=a:i!==-1&&(s=i),s===-1){r=e.slice(n);break}else{let u=e.slice(n,s);t.push(u),n=s+1,e[n-1]==="\r"&&e[n]===`
972
- `&&n++}}return[t,r]}o(GU,"splitLines");var Fs=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=Mw({onEvent:o(s=>{i.enqueue(s)},"onEvent"),onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:r,onComment:n})},transform(i){a.feed(i)}})}};var BU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ur=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Vs=class{static{o(this,"StreamableHTTPClientTransport")}constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Dw(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??BU}async _authThenStart(){if(!this._authProvider)throw new ar("No auth provider");let t;try{t=await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new ar;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=Gs(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let a=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Ur(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),a)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},a)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:a,replayMessageId:i}=r,s,u=!1,d=!1;o(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Fs({onRetry:o(_=>{this._serverRetryMs=_},"onRetry")})).getReader();for(;;){let{value:_,done:w}=await l.read();if(w)break;if(_.id&&(s=_.id,u=!0,a?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let y=Mr.parse(JSON.parse(_.data));St(y)&&(d=!0,i!==void 0&&(y.id=i)),this.onmessage?.(y)}catch(y){this.onerror?.(y)}}(n||u)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||u)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(_){this.onerror?.(new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}},"processStream")()}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 ar("No auth provider");if(await Or(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:xt(t)?t.id:void 0}).catch(f=>this.onerror?.(f));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},u=await(this._fetch??fetch)(this._url,s),d=u.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!u.ok){let f=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ur(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:w}=up(u);if(this._resourceMetadataUrl=_,this._scope=w,await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ar;return this._hasCompletedAuthFlow=!0,this.send(t)}if(u.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:w,error:y}=up(u);if(y==="insufficient_scope"){let S=u.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new Ur(403,"Server returned 403 after trying upscoping");if(w&&(this._scope=w),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=S??void 0,await Or(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar;return this.send(t)}}throw new Ur(u.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,u.status===202){await u.body?.cancel(),bm(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let l=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,m=u.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let f=await u.json(),_=Array.isArray(f)?f.map(w=>Mr.parse(w)):[Mr.parse(f)];for(let w of _)this.onmessage?.(w)}else throw await u.body?.cancel(),new Ur(-1,`Unexpected content type: ${m}`);else await u.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ur(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function Qn(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!Qn(e[a],t[a]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(let s of n)if(!Qn(e[s],t[s]))return!1;return!0}return e===t}o(Qn,"deepCompareStrict");function ct(e){return encodeURI(FU(e))}o(ct,"encodePointer");function FU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(FU,"escapePointer");var VU={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},KU={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ZU={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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},WU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ir(e,t=Object.create(null),r=WU,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:ir(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(ZU[i])continue;let s=`${n}/${ct(i)}`,u=e[i];if(Array.isArray(u)){if(VU[i]){let d=u.length;for(let p=0;p<d;p++)ir(u[p],t,r,`${s}/${p}`)}}else if(KU[i])for(let d in u)ir(u[d],t,r,`${s}/${ct(d)}`);else ir(u,t,r,s)}return t}o(ir,"dereference");var JU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YU=[0,31,28,31,30,31,30,31,31,30,31,30,31],XU=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,QU=/^(?=.{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,eN=/^(?:[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,tN=/^(?:(?:[^\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,rN=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,nN=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,oN=/^(?:\/(?:[^~/]|~0|~1)*)*$/,aN=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,iN=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,sN=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},"EMAIL"),cN=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,uN=/^((([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,dN=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function Lt(e){return e.test.bind(e)}o(Lt,"bind");var wp={date:qw,time:Lw.bind(void 0,!1),"date-time":mN,duration:dN,uri:gN,"uri-reference":Lt(eN),"uri-template":Lt(tN),url:Lt(rN),email:sN,hostname:Lt(QU),ipv4:Lt(cN),ipv6:Lt(uN),regex:yN,uuid:Lt(nN),"json-pointer":Lt(oN),"json-pointer-uri-fragment":Lt(aN),"relative-json-pointer":Lt(iN)};function lN(e){return e%4===0&&(e%100!==0||e%400===0)}o(lN,"isLeapYear");function qw(e){let t=e.match(JU);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&lN(r)?29:YU[n])}o(qw,"date");function Lw(e,t){let r=t.match(XU);if(!r)return!1;let n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||n==23&&a==59&&i==60)&&(!e||s)}o(Lw,"time");var pN=/t|\s/i;function mN(e){let t=e.split(pN);return t.length==2&&qw(t[0])&&Lw(!0,t[1])}o(mN,"date_time");var hN=/\/|:/,fN=/^(?:[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 gN(e){return hN.test(e)&&fN.test(e)}o(gN,"uri");var _N=/[^\\]\\Z/;function yN(e){if(_N.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(yN,"regex");var jw;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(jw||(jw={}));function Hw(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}o(Hw,"ucs2length");function ge(e,t,r="2019-09",n=ir(t),a=!0,i=null,s="#",u="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:_,type:w,const:y,enum:S,required:v,not:R,anyOf:b,allOf:q,oneOf:L,if:je,then:ut,else:fn,format:ur,properties:Gt,patternProperties:zr,additionalProperties:co,unevaluatedProperties:uo,minProperties:lo,maxProperties:dc,propertyNames:Jp,dependentRequired:lc,dependentSchemas:pc,dependencies:mc,prefixItems:hc,items:po,additionalItems:Yp,unevaluatedItems:Xp,contains:Qp,minContains:Bt,maxContains:Ha,minItems:fc,maxItems:gc,uniqueItems:Hv,minimum:$r,maximum:Dr,exclusiveMinimum:mo,exclusiveMaximum:ho,multipleOf:Ga,minLength:Ba,maxLength:Fa,pattern:em,__absolute_ref__:Va,__absolute_recursive_ref__:Gv}=t,E=[];if(_===!0&&i===null&&(i=t),f==="#"){let j=i===null?n[Gv]:i,$=`${u}/$recursiveRef`,F=ge(e,i===null?t:i,r,n,a,j,s,$,d);F.valid||E.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...F.errors)}if(m!==void 0){let $=n[Va||m];if($===void 0){let T=`Unresolved $ref "${m}".`;throw Va&&Va!==m&&(T+=` Absolute URI "${Va}".`),T+=`
43
+ `,t.enqueue(r.encode(i)),!0}catch(i){return this.onerror?.(i),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let a=t.headers.get("content-type");if(!a||!a.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},s;if(r?.parsedBody!==void 0)s=r.parsedBody;else try{s=await t.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let c;try{Array.isArray(s)?c=s.map(v=>$r.parse(v)):c=[$r.parse(s)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let d=c.some(cc);if(d){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(c.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!d){let v=this.validateSession(t);if(v)return v;let b=this.validateProtocolVersion(t);if(b)return b}if(!c.some(It)){for(let v of c)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(v=>cc(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Jp;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let b of c)It(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:i})});let y=new TextEncoder,_,S=new ReadableStream({start:o(v=>{_=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),w={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(w["mcp-session-id"]=this.sessionId);for(let v of c)It(v)&&(this._streamMapping.set(l,{controller:_,encoder:y,cleanup:o(()=>{this._streamMapping.delete(l);try{_.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(_,y,l,h);for(let v of c){let b,R;It(v)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),R=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:b,closeStandaloneSSEStream:R})}return new Response(S,{status:200,headers:w})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!lr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${lr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${lr.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((St(t)||mn(t))&&(n=t.id),n===void 0){if(St(t)||mn(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let c=this._streamMapping.get(this._standaloneSseStreamId);if(c===void 0)return;c.controller&&c.encoder&&this.writeSSEEvent(c.controller,c.encoder,t,s);return}let a=this._requestToStreamMapping.get(n);if(!a)throw new Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let s;this._eventStore&&(s=await this._eventStore.storeEvent(a,t)),this.writeSSEEvent(i.controller,i.encoder,t,s)}if(St(t)||mn(t)){this._requestResponseMap.set(n,t);let s=Array.from(this._requestToStreamMapping.entries()).filter(([d,p])=>p===a).map(([d])=>d);if(s.every(d=>this._requestResponseMap.has(d))){if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let d={"Content-Type":"application/json"};this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId);let p=s.map(l=>this._requestResponseMap.get(l));p.length===1?i.resolveJson(new Response(JSON.stringify(p[0]),{status:200,headers:d})):i.resolveJson(new Response(JSON.stringify(p),{status:200,headers:d}))}else i.cleanup();for(let d of s)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function $n(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!$n(e[a],t[a]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(let s of n)if(!$n(e[s],t[s]))return!1;return!0}return e===t}o($n,"deepCompareStrict");function at(e){return encodeURI(NA(e))}o(at,"encodePointer");function NA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(NA,"escapePointer");var jA={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},DA={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},HA={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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},LA=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Wt(e,t=Object.create(null),r=LA,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:Wt(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(HA[i])continue;let s=`${n}/${at(i)}`,c=e[i];if(Array.isArray(c)){if(jA[i]){let d=c.length;for(let p=0;p<d;p++)Wt(c[p],t,r,`${s}/${p}`)}}else if(DA[i])for(let d in c)Wt(c[d],t,r,`${s}/${at(d)}`);else Wt(c,t,r,s)}return t}o(Wt,"dereference");var BA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,GA=[0,31,28,31,30,31,30,31,31,30,31,30,31],VA=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,FA=/^(?=.{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,ZA=/^(?:[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,KA=/^(?:(?:[^\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,WA=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,JA=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,YA=/^(?:\/(?:[^~/]|~0|~1)*)*$/,QA=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,XA=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,eT=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},"EMAIL"),tT=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,rT=/^((([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,nT=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function Ut(e){return e.test.bind(e)}o(Ut,"bind");var Td={date:eg,time:tg.bind(void 0,!1),"date-time":iT,duration:nT,uri:uT,"uri-reference":Ut(ZA),"uri-template":Ut(KA),url:Ut(WA),email:eT,hostname:Ut(FA),ipv4:Ut(tT),ipv6:Ut(rT),regex:lT,uuid:Ut(JA),"json-pointer":Ut(YA),"json-pointer-uri-fragment":Ut(QA),"relative-json-pointer":Ut(XA)};function oT(e){return e%4===0&&(e%100!==0||e%400===0)}o(oT,"isLeapYear");function eg(e){let t=e.match(BA);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&oT(r)?29:GA[n])}o(eg,"date");function tg(e,t){let r=t.match(VA);if(!r)return!1;let n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||n==23&&a==59&&i==60)&&(!e||s)}o(tg,"time");var aT=/t|\s/i;function iT(e){let t=e.split(aT);return t.length==2&&eg(t[0])&&tg(!0,t[1])}o(iT,"date_time");var sT=/\/|:/,cT=/^(?:[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 uT(e){return sT.test(e)&&cT.test(e)}o(uT,"uri");var dT=/[^\\]\\Z/;function lT(e){if(dT.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(lT,"regex");var rg;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(rg||(rg={}));function ng(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}o(ng,"ucs2length");function fe(e,t,r="2019-09",n=Wt(t),a=!0,i=null,s="#",c="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:y,type:_,const:S,enum:w,required:v,not:b,anyOf:R,allOf:q,oneOf:N,if:qe,then:it,else:dn,format:ir,properties:qt,patternProperties:Er,additionalProperties:no,unevaluatedProperties:oo,minProperties:ao,maxProperties:Zs,propertyNames:kp,dependentRequired:Ks,dependentSchemas:Ws,dependencies:Js,prefixItems:Ys,items:io,additionalItems:Ep,unevaluatedItems:Up,contains:Op,minContains:Nt,maxContains:Ea,minItems:Qs,maxItems:Xs,uniqueItems:vv,minimum:Ur,maximum:Or,exclusiveMinimum:so,exclusiveMaximum:co,multipleOf:Ua,minLength:Oa,maxLength:$a,pattern:$p,__absolute_ref__:za,__absolute_recursive_ref__:bv}=t,T=[];if(y===!0&&i===null&&(i=t),h==="#"){let j=i===null?n[bv]:i,z=`${c}/$recursiveRef`,B=fe(e,i===null?t:i,r,n,a,j,s,z,d);B.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:z,error:"A subschema had errors."},...B.errors)}if(m!==void 0){let z=n[za||m];if(z===void 0){let P=`Unresolved $ref "${m}".`;throw za&&za!==m&&(P+=` Absolute URI "${za}".`),P+=`
973
44
  Known schemas:
974
45
  - ${Object.keys(n).join(`
975
- - `)}`,new Error(T)}let F=`${u}/$ref`,x=ge(e,$,r,n,a,i,s,F,d);if(x.valid||E.push({instanceLocation:s,keyword:"$ref",keywordLocation:F,error:"A subschema had errors."},...x.errors),r==="4"||r==="7")return{valid:E.length===0,errors:E}}if(Array.isArray(w)){let j=w.length,$=!1;for(let F=0;F<j;F++)if(l===w[F]||w[F]==="integer"&&l==="number"&&e%1===0&&e===e){$=!0;break}$||E.push({instanceLocation:s,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${l}" is invalid. Expected "${w.join('", "')}".`})}else w==="integer"?(l!=="number"||e%1||e!==e)&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${l}" is invalid. Expected "${w}".`}):w!==void 0&&l!==w&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${l}" is invalid. Expected "${w}".`});if(y!==void 0&&(l==="object"||l==="array"?Qn(e,y)||E.push({instanceLocation:s,keyword:"const",keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&E.push({instanceLocation:s,keyword:"const",keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),S!==void 0&&(l==="object"||l==="array"?S.some(j=>Qn(e,j))||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(j=>e===j)||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),R!==void 0){let j=`${u}/not`;ge(e,R,r,n,a,i,s,j).valid&&E.push({instanceLocation:s,keyword:"not",keywordLocation:j,error:'Instance matched "not" schema.'})}let Ka=[];if(b!==void 0){let j=`${u}/anyOf`,$=E.length,F=!1;for(let x=0;x<b.length;x++){let T=b[x],G=Object.create(d),H=ge(e,T,r,n,a,_===!0?i:null,s,`${j}/${x}`,G);E.push(...H.errors),F=F||H.valid,H.valid&&Ka.push(G)}F?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:j,error:"Instance does not match any subschemas."})}if(q!==void 0){let j=`${u}/allOf`,$=E.length,F=!0;for(let x=0;x<q.length;x++){let T=q[x],G=Object.create(d),H=ge(e,T,r,n,a,_===!0?i:null,s,`${j}/${x}`,G);E.push(...H.errors),F=F&&H.valid,H.valid&&Ka.push(G)}F?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:j,error:"Instance does not match every subschema."})}if(L!==void 0){let j=`${u}/oneOf`,$=E.length,F=L.filter((x,T)=>{let G=Object.create(d),H=ge(e,x,r,n,a,_===!0?i:null,s,`${j}/${T}`,G);return E.push(...H.errors),H.valid&&Ka.push(G),H.valid}).length;F===1?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:j,error:`Instance does not match exactly one subschema (${F} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...Ka),je!==void 0){let j=`${u}/if`;if(ge(e,je,r,n,a,i,s,j,d).valid){if(ut!==void 0){let F=ge(e,ut,r,n,a,i,s,`${u}/then`,d);F.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "then" schema.'},...F.errors)}}else if(fn!==void 0){let F=ge(e,fn,r,n,a,i,s,`${u}/else`,d);F.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "else" schema.'},...F.errors)}}if(l==="object"){if(v!==void 0)for(let x of v)x in e||E.push({instanceLocation:s,keyword:"required",keywordLocation:`${u}/required`,error:`Instance does not have required property "${x}".`});let j=Object.keys(e);if(lo!==void 0&&j.length<lo&&E.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${u}/minProperties`,error:`Instance does not have at least ${lo} properties.`}),dc!==void 0&&j.length>dc&&E.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${u}/maxProperties`,error:`Instance does not have at least ${dc} properties.`}),Jp!==void 0){let x=`${u}/propertyNames`;for(let T in e){let G=`${s}/${ct(T)}`,H=ge(T,Jp,r,n,a,i,G,x);H.valid||E.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:x,error:`Property name "${T}" does not match schema.`},...H.errors)}}if(lc!==void 0){let x=`${u}/dependantRequired`;for(let T in lc)if(T in e){let G=lc[T];for(let H of G)H in e||E.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:x,error:`Instance has "${T}" but does not have "${H}".`})}}if(pc!==void 0)for(let x in pc){let T=`${u}/dependentSchemas`;if(x in e){let G=ge(e,pc[x],r,n,a,i,s,`${T}/${ct(x)}`,d);G.valid||E.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:T,error:`Instance has "${x}" but does not match dependant schema.`},...G.errors)}}if(mc!==void 0){let x=`${u}/dependencies`;for(let T in mc)if(T in e){let G=mc[T];if(Array.isArray(G))for(let H of G)H in e||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:x,error:`Instance has "${T}" but does not have "${H}".`});else{let H=ge(e,G,r,n,a,i,s,`${x}/${ct(T)}`);H.valid||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:x,error:`Instance has "${T}" but does not match dependant schema.`},...H.errors)}}}let $=Object.create(null),F=!1;if(Gt!==void 0){let x=`${u}/properties`;for(let T in Gt){if(!(T in e))continue;let G=`${s}/${ct(T)}`,H=ge(e[T],Gt[T],r,n,a,i,G,`${x}/${ct(T)}`);if(H.valid)d[T]=$[T]=!0;else if(F=a,E.push({instanceLocation:s,keyword:"properties",keywordLocation:x,error:`Property "${T}" does not match schema.`},...H.errors),F)break}}if(!F&&zr!==void 0){let x=`${u}/patternProperties`;for(let T in zr){let G=new RegExp(T,"u"),H=zr[T];for(let Ye in e){if(!G.test(Ye))continue;let tm=`${s}/${ct(Ye)}`,rm=ge(e[Ye],H,r,n,a,i,tm,`${x}/${ct(T)}`);rm.valid?d[Ye]=$[Ye]=!0:(F=a,E.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:x,error:`Property "${Ye}" matches pattern "${T}" but does not match associated schema.`},...rm.errors))}}}if(!F&&co!==void 0){let x=`${u}/additionalProperties`;for(let T in e){if($[T])continue;let G=`${s}/${ct(T)}`,H=ge(e[T],co,r,n,a,i,G,x);H.valid?d[T]=!0:(F=a,E.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:x,error:`Property "${T}" does not match additional properties schema.`},...H.errors))}}else if(!F&&uo!==void 0){let x=`${u}/unevaluatedProperties`;for(let T in e)if(!d[T]){let G=`${s}/${ct(T)}`,H=ge(e[T],uo,r,n,a,i,G,x);H.valid?d[T]=!0:E.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:x,error:`Property "${T}" does not match unevaluated properties schema.`},...H.errors)}}}else if(l==="array"){gc!==void 0&&e.length>gc&&E.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${u}/maxItems`,error:`Array has too many items (${e.length} > ${gc}).`}),fc!==void 0&&e.length<fc&&E.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${u}/minItems`,error:`Array has too few items (${e.length} < ${fc}).`});let j=e.length,$=0,F=!1;if(hc!==void 0){let x=`${u}/prefixItems`,T=Math.min(hc.length,j);for(;$<T;$++){let G=ge(e[$],hc[$],r,n,a,i,`${s}/${$}`,`${x}/${$}`);if(d[$]=!0,!G.valid&&(F=a,E.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:x,error:"Items did not match schema."},...G.errors),F))break}}if(po!==void 0){let x=`${u}/items`;if(Array.isArray(po)){let T=Math.min(po.length,j);for(;$<T;$++){let G=ge(e[$],po[$],r,n,a,i,`${s}/${$}`,`${x}/${$}`);if(d[$]=!0,!G.valid&&(F=a,E.push({instanceLocation:s,keyword:"items",keywordLocation:x,error:"Items did not match schema."},...G.errors),F))break}}else for(;$<j;$++){let T=ge(e[$],po,r,n,a,i,`${s}/${$}`,x);if(d[$]=!0,!T.valid&&(F=a,E.push({instanceLocation:s,keyword:"items",keywordLocation:x,error:"Items did not match schema."},...T.errors),F))break}if(!F&&Yp!==void 0){let T=`${u}/additionalItems`;for(;$<j;$++){let G=ge(e[$],Yp,r,n,a,i,`${s}/${$}`,T);d[$]=!0,G.valid||(F=a,E.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:T,error:"Items did not match additional items schema."},...G.errors))}}}if(Qp!==void 0)if(j===0&&Bt===void 0)E.push({instanceLocation:s,keyword:"contains",keywordLocation:`${u}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Bt!==void 0&&j<Bt)E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${u}/minContains`,error:`Array has less items (${j}) than minContains (${Bt}).`});else{let x=`${u}/contains`,T=E.length,G=0;for(let H=0;H<j;H++){let Ye=ge(e[H],Qp,r,n,a,i,`${s}/${H}`,x);Ye.valid?(d[H]=!0,G++):E.push(...Ye.errors)}G>=(Bt||0)&&(E.length=T),Bt===void 0&&Ha===void 0&&G===0?E.splice(T,0,{instanceLocation:s,keyword:"contains",keywordLocation:x,error:"Array does not contain item matching schema."}):Bt!==void 0&&G<Bt?E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${u}/minContains`,error:`Array must contain at least ${Bt} items matching schema. Only ${G} items were found.`}):Ha!==void 0&&G>Ha&&E.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${u}/maxContains`,error:`Array may contain at most ${Ha} items matching schema. ${G} items were found.`})}if(!F&&Xp!==void 0){let x=`${u}/unevaluatedItems`;for($;$<j;$++){if(d[$])continue;let T=ge(e[$],Xp,r,n,a,i,`${s}/${$}`,x);d[$]=!0,T.valid||E.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:x,error:"Items did not match unevaluated items schema."},...T.errors)}}if(Hv)for(let x=0;x<j;x++){let T=e[x],G=typeof T=="object"&&T!==null;for(let H=0;H<j;H++){if(x===H)continue;let Ye=e[H];(T===Ye||G&&(typeof Ye=="object"&&Ye!==null)&&Qn(T,Ye))&&(E.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${u}/uniqueItems`,error:`Duplicate items at indexes ${x} and ${H}.`}),x=Number.MAX_SAFE_INTEGER,H=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?($r!==void 0&&(mo===!0&&e<=$r||e<$r)&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${u}/minimum`,error:`${e} is less than ${mo?"or equal to ":""} ${$r}.`}),Dr!==void 0&&(ho===!0&&e>=Dr||e>Dr)&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${u}/maximum`,error:`${e} is greater than ${ho?"or equal to ":""} ${Dr}.`})):($r!==void 0&&e<$r&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${u}/minimum`,error:`${e} is less than ${$r}.`}),Dr!==void 0&&e>Dr&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${u}/maximum`,error:`${e} is greater than ${Dr}.`}),mo!==void 0&&e<=mo&&E.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${u}/exclusiveMinimum`,error:`${e} is less than ${mo}.`}),ho!==void 0&&e>=ho&&E.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${u}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ho}.`})),Ga!==void 0){let j=e%Ga;Math.abs(0-j)>=11920929e-14&&Math.abs(Ga-j)>=11920929e-14&&E.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${u}/multipleOf`,error:`${e} is not a multiple of ${Ga}.`})}}else if(l==="string"){let j=Ba===void 0&&Fa===void 0?0:Hw(e);Ba!==void 0&&j<Ba&&E.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${u}/minLength`,error:`String is too short (${j} < ${Ba}).`}),Fa!==void 0&&j>Fa&&E.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${u}/maxLength`,error:`String is too long (${j} > ${Fa}).`}),em!==void 0&&!new RegExp(em,"u").test(e)&&E.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${u}/pattern`,error:"String does not match pattern."}),ur!==void 0&&wp[ur]&&!wp[ur](e)&&E.push({instanceLocation:s,keyword:"format",keywordLocation:`${u}/format`,error:`String does not match format "${ur}".`})}return{valid:E.length===0,errors:E}}o(ge,"validate");var Ks=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=ir(t)}validate(t){return ge(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),ir(t,this.lookup)}};var Zs=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new Ks(t,this.draft,this.shortcircuit);return n=>{let a=r.validate(n);return a.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:a.errors.map(i=>`${i.instanceLocation}: ${i.error}`).join("; ")}}}};function Gw(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(Gw,"resolveNativeMcpRequestHeaders");var wN={name:"zuplo-mcp-gateway",version:"0.1.0"},SN=new Zs({draft:"7",shortcircuit:!1}),vN=5,RN=500,Vw=3e4,bN=2*1024*1024,CN=2;function Bw(){return performance.now()/1e3}o(Bw,"nowSeconds");function IN(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(IN,"readServerPort");function TN(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:IN(e)}}o(TN,"buildNativeMcpOperationContext");function eo(e){return Xg(e)}o(eo,"withTraceMeta");function Sp(e){if(e>RN)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Sp,"assertImportedCapabilityBudget");function Fw(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(Fw,"buildRequestInit");function AN(e){return(t,r)=>qs(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:CN,maxResponseBytes:bN,problemCode:"upstream_capability_invocation_failed",timeoutMs:Vw})}o(AN,"createNativeMcpFetch");function kN(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},Vw);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(kN,"withNativeMcpRequestTimeout");function EN(e,t=[]){let r=Gw(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:AN(a)};if(!e)return{...i,...Fw(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...Fw(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(EN,"buildNativeMcpTransportOptions");async function to(e,t,r){let{transport:n}=at(e),a=new URL(n.baseUrl),i=new Vs(a,EN(r,n.requestHeaders)),s=new Hs(wN,{capabilities:{},jsonSchemaValidator:SN});return kN((async()=>{let u=Bw();await s.connect(i);let d=i.sessionId,p=TN(a,d);try{return await t(s,p)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&Qg(p,Bw()-u)}})())}o(to,"withNativeMcpClient");async function xN(e,t,r){let n=[],a,i=0;do{if(i>=vN)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(xN,"collectPaginatedSdkItems");async function vp(e){return e.enabled?xN(e.label,e.fetchPage,e.readItems):[]}o(vp,"listNativeMcpCapabilityItems");async function Kw(e){return to(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Yr({methodName:"tools/list",...r},()=>vp({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(eo(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Sp(a.length),{tools:a}},e.credential)}o(Kw,"listNativeMcpTools");async function Zw(e){return to(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Yr({methodName:"prompts/list",...r},()=>vp({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(eo(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Sp(a.length),{prompts:a}},e.credential)}o(Zw,"listNativeMcpPrompts");async function Ww(e){return to(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Yr({methodName:"resources/list",...r},()=>vp({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(eo(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Sp(a.length),{resources:a}},e.credential)}o(Ww,"listNativeMcpResources");async function Jw(e){return to(e.upstreamServerId,(t,r)=>Yr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(eo(e.params))),e.credential)}o(Jw,"callNativeMcpTool");async function Yw(e){return to(e.upstreamServerId,(t,r)=>Yr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(eo(e.params))),e.credential)}o(Yw,"getNativeMcpPrompt");async function Xw(e){return to(e.upstreamServerId,(t,r)=>Yr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(eo(e.params))),e.credential)}o(Xw,"readNativeMcpResource");var Ua=class extends k{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(P.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function PN(e){return{content:[{type:"text",text:e}],isError:!0}}o(PN,"buildToolErrorResult");function ON(e){return e.authUrl?new pr([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new Ua(e)}o(ON,"toConnectRequiredError");function UN(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(UN,"buildCredentialResolvedAttributes");function NN(e){ot(e.context,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:UN(e.credential)})}o(NN,"emitCredentialResolvedAnalyticsEvent");function zN(e){ot(e.context,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}o(zN,"emitCredentialMissingAnalyticsEvent");function $N(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):en({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o($N,"readRouteBindingCredentialCacheKey");function DN(e){return typeof e.authorizeAndLoadConnections=="function"}o(DN,"isRuntimeHttpCompositeAuthorizationRepository");function eS(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(eS,"readOwnedRouteBindingLookup");async function MN(e){let t=V().downstreamOAuthRepository;if(!DN(t))return new Map;let r=Fl(e.request);if(!r)return new Map;let n=new Map;for(let u of e.routeBindings){let d=eS(u);d!==void 0&&n.set(en(d),d)}if(n.size===0)return new Map;let a=[...n.values()],i=await t.authorizeAndLoadConnections({accessTokenHash:await ee(r),resource:Qr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:a,now:z(new Date)});if(i.kind!=="authorized")return new Map;let s=new Map;return i.upstreamConnections.forEach((u,d)=>{let p=a[d];p!==void 0&&s.set(en(p),u.connection)}),s}o(MN,"preloadCompositeAuthorizedConnections");function qN(e){let t=new Map;return r=>{let n=$N(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,u=eS(r),d=u===void 0?void 0:en(u),p=await Uw({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw zN({context:e.context,payload:p.payload,routeBinding:r}),ON(p.payload);return NN({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(qN,"createCredentialResolver");var Qw=500;function LN(e){return e.length<=Qw?e:`${e.slice(0,Qw)}...`}o(LN,"truncateAnalyticsDetail");function jN(e){ot(e.context,{eventType:J.MCP_GATEWAY_CAPABILITY_COMPLETED,outcome:e.result.isError===!0?"application_error":"success",routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",toolResultIsError:e.result.isError===!0,applicationError:e.result.isError===!0})}o(jN,"emitToolInvocationCompletedAnalyticsEvent");function HN(e){return e instanceof pr||e instanceof Ua?{eventType:J.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof k&&e.code===P.InvalidParams?{eventType:J.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:J.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(HN,"classifyToolInvocationFailure");function GN(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=HN(e.error);ot(e.context,{eventType:r.eventType,outcome:r.outcome,routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",reasonCode:r.reasonCode,reasonClass:r.reasonClass,errorType:r.errorType,mcpErrorType:r.mcpErrorType,attributes:{detail:LN(t)}})}o(GN,"emitToolInvocationFailedAnalyticsEvent");var BN=256*1024;function FN(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new k(P.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>BN)throw new k(P.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(FN,"assertToolArgumentsWithinLimit");function Rp(e){if(e.routeBindings.length===1)return e.routeBindings[0];let t=e.routeBindings.filter(r=>r.connectionPolicyName===e.upstreamPolicyName);if(t.length!==1)throw new k(P.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(Rp,"findBindingForPublishedCapability");function ro(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new k(P.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(ro,"requireSingleTransparentBinding");function VN(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:ro(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new k(P.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(VN,"resolvePublishedToolRoute");function KN(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:ro(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new k(P.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(KN,"resolvePublishedPromptRoute");function ZN(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:ro(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new k(P.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(ZN,"resolvePublishedResourceRoute");function tS(e){let t=MN({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=qN({context:e.context,preloadedConnections:t,request:e.request});return{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{tools:e.publishedVirtualServer.catalog.tools.filter(a=>a.enabled!==!1).map(as)};let n=ro(e);return Kw({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async callTool(n){let a=VN({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:n.name});try{FN(n);let i=await r(a.binding),s=await Jw({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:i});return jN({context:e.context,routeBinding:a.binding,toolName:n.name,result:s}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,isError:s.isError===!0},"Upstream tool invocation completed"),s}catch(i){if(GN({context:e.context,routeBinding:a.binding,toolName:n.name,error:i}),i instanceof pr||i instanceof Ua)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:n.name,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,ownerMode:a.binding.ownerMode,hasAuthUrl:i instanceof pr},"Upstream tool invocation requires user to complete a connect flow"),i;let s={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId};return i instanceof k&&(s.mcpErrorCode=i.code),i instanceof Error?(s.errorName=i.name,s.errorMessage=i.message,i.cause instanceof Error&&(s.causeName=i.cause.name,s.causeMessage=i.cause.message)):s.errorMessage=String(i),e.context.log.warn(s,"Upstream tool invocation failed; returning generic gateway error to MCP client"),PN(rt("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{prompts:e.publishedVirtualServer.catalog.prompts.filter(a=>a.enabled!==!1).map(is)};let n=ro(e);return Zw({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async getPrompt(n){let a=KN({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:n.name});return Yw({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:await r(a.binding)})},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resources:e.publishedVirtualServer.catalog.resources.filter(a=>a.enabled!==!1).map(ss)};let n=ro(e);return Ww({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async readResource(n){let a=ZN({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:n.uri});return Xw({upstreamServerId:a.binding.upstreamServerId,params:{...n,uri:a.upstreamUri},credential:await r(a.binding)})}}}o(tS,"createCapabilityDispatcher");var WN="0.1.0",nS="POST",JN="POST, OPTIONS";function bp(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:nS}})}o(bp,"jsonRpcMethodNotAllowedResponse");function YN(e){let t={Allow:nS},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=JN;let a=e.headers.get("access-control-request-headers");a&&(t["Access-Control-Allow-Headers"]=a)}return new Response(null,{status:204,headers:t})}o(YN,"buildOptionsResponse");function no(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(no,"readJsonRpcRequestId");function Cp(e){return e&&typeof e=="object"?e.params:void 0}o(Cp,"readMcpRequestParams");function rS(e,t){return e.headers.get(t)??void 0}o(rS,"readMcpHeader");function XN(e){return{mcpProtocolVersion:rS(e,"mcp-protocol-version")??Jr,mcpSessionId:rS(e,"mcp-session-id")}}o(XN,"buildServerTelemetryBase");function QN(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Jr),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(QN,"ensureProtocolVersionHeader");async function Ip(e,t){if(e.method==="OPTIONS")return YN(e);if(e.method==="GET")return bp("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return bp("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return bp("Only POST is supported by this virtual MCP server.");let r=jn(t),n=qg(r.virtualServerId),a=t_(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=XN(e),s=tS({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),u=de(e.url),d=new Ji({enableDnsRebindingProtection:!0,allowedOrigins:[u]}),p=new Wi(n.catalog.serverInfo??{name:r.virtualServerId,version:WN},{capabilities:{prompts:{},resources:{},tools:{}}});p.setRequestHandler(Bc,async m=>Xr({methodName:"tools/list",params:Cp(m),jsonRpcRequestId:no(m),...i},()=>s.listTools())),p.setRequestHandler(Co,async m=>Xr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:no(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(zc,async m=>Xr({methodName:"prompts/list",params:Cp(m),jsonRpcRequestId:no(m),...i},()=>s.listPrompts())),p.setRequestHandler(Dc,async m=>Xr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:no(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(kc,async m=>Xr({methodName:"resources/list",params:Cp(m),jsonRpcRequestId:no(m),...i},()=>s.listResources())),p.setRequestHandler(Oc,async m=>Xr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:no(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return QN(l)}o(Ip,"virtualServerHandler");async function ez(e,t){return dr("handler.mcp-virtual-server"),Ip(e,t)}o(ez,"McpVirtualServerHandler");var oo={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},tz="oauth-protected-resource-metadata",rz="/.well-known/oauth-protected-resource/";function nz(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(nz,"readRouteOperationId");function oz(e){return e.hasGatewayRouteContext?oo.VIRTUAL_MCP_SERVER:e.routeOperationId===tz||e.routeOperationId===void 0&&e.routePath.startsWith(rz)?oo.OAUTH_PROTECTED_RESOURCE_METADATA:oo.OTHER}o(oz,"classifyAnalyticsRouteSurface");function az(e){let t=e.route.path;return{routePath:t,routeSurface:oz({routePath:t,routeOperationId:nz(e),hasGatewayRouteContext:aa(e)!==void 0})}}o(az,"readAnalyticsRequestContext");function iz(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===oo.VIRTUAL_MCP_SERVER}o(iz,"isIntentionalMethodRejection");function sz(e){return iz(e)||e.response.status===401&&e.routeSurface===oo.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(sz,"classifyRequestCompletedOutcome");async function Tp(e,t){let r=Date.now(),n=az(t);return t.addResponseSendingFinalHook(a=>{let i=sz({response:a,routeSurface:n.routeSurface});ot(t,{eventType:J.MCP_GATEWAY_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Tp,"analyticsContextInbound");function cz(e){return e instanceof Response}o(cz,"isResponse");var oS="/mcp/";function uz(e){let t=e.route.path;if(!t.startsWith(oS))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(oS.length);if(!r||r.includes("/"))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(uz,"readVirtualServerIdFromRoute");async function Na(e,t){let n={virtualServerId:Se.parse(uz(t))};Hg(t,n),Rg(t,n);let a=await Tp(e,t);return cz(a)?a:Vl(a,t)}o(Na,"mcpOAuthInboundPolicy");var dz=o(async(e,t,r,n)=>(dr("policy.inbound.mcp-auth0-oauth"),Na(e,t)),"McpAuth0OAuthInboundPolicy");function lz(e){let t=`https://${e.auth0Domain}/`,r=`https://${e.auth0Domain}/.well-known/jwks.json`,n=`https://${e.auth0Domain}/authorize`,a=`https://${e.auth0Domain}/oauth/token`;return ds({oidc:{issuer:t,jwksUrl:r,audience:e.audience},browserLogin:{url:n,tokenUrl:a,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",audience:e.audience,...e.browserLoginOverrides??{}},gateway:e.gateway})}o(lz,"buildAuth0McpOAuthRuntimeConfig");var pz={policyType:"mcp-auth0-oauth-inbound",displayName:"MCP OAuth (Auth0)",getConfig(e){return lz(e)}};ts(pz);var mz=o(async(e,t,r,n)=>(dr("policy.inbound.mcp-oauth"),Na(e,t)),"McpOAuthInboundPolicy"),hz={policyType:"mcp-oauth-inbound",displayName:"MCP OAuth",getConfig(e){return ds(e)}};ts(hz);function fz(e){let t=Mt(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,virtualServerId:e.virtualServerId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.config.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}o(fz,"buildRouteAuthBaseFromConnection");function iS(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=Mt(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:Ln(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(iS,"buildRouteAuthBaseFromPolicyOptions");function sS(e,t){let n=yt().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return fz({connection:a,virtualServerId:t})}o(sS,"resolveRouteAuthBase");function aS(e,t){switch(e){case"user":return kr(t.subjectId);case"shared":return Ss()}}o(aS,"buildOwnerForPrincipal");function Ws(e,t){switch(e.ownerMode){case"shared":return{...e,owner:aS(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:aS(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Ws,"resolveRouteAuthForPrincipal");function gz(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Qi.parse(r)}o(gz,"readSingleAuthMode");function cS(e){return Dt.parse(e)}o(cS,"buildToolNamePrefixFromConnectionId");async function Ap(e,t,r,n){let a=os(r,n),i=gz({policyName:n,connection:a}),s=jn(t),u=iS({connection:a,virtualServerId:s.virtualServerId,authMode:i});if(u.ownerMode==="none")return ll(t,{...u,connectionPolicyName:n,toolNamePrefix:cS(a.id)}),e;let d=h_(t);return ll(t,{...Ws(u,d),connectionPolicyName:n,toolNamePrefix:cS(a.id)}),e}o(Ap,"mcpUpstreamConnectionPolicy");var _z=o(async(e,t,r,n)=>(dr("policy.inbound.mcp-upstream-connection"),Ap(e,t,r,n)),"McpUpstreamConnectionInboundPolicy");ae();ae();var uS="application/json",yz="application/x-www-form-urlencoded";function wz(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(wz,"normalizeContentType");function Sz(e,t){return e===t?!0:t===uS&&e.endsWith("+json")}o(Sz,"contentTypeMatches");function vz(e,t){if(!t||t.length===0)return;let r=wz(e.headers.get("content-type"));if(!t.some(n=>Sz(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(vz,"assertExpectedContentType");function Rz(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(Rz,"assertContentLengthWithinLimit");async function dS(e,t){let r=t.label??"Request body";vz(e,t.expectedContentTypes),Rz(e,t.maxBytes,r);let n=await Ms(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(dS,"readBoundedTextBody");async function lS(e,t){let r=await dS(e,{...t,expectedContentTypes:[uS]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(lS,"readBoundedJsonBody");async function Js(e,t){let r=await dS(e,{...t,expectedContentTypes:[yz]});return new URLSearchParams(r)}o(Js,"readBoundedFormUrlEncodedBody");var pS=Symbol("Html");function bz(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(bz,"escapeHtml");function Cz(e){return e===null||typeof e!="object"?!1:e[pS]===!0}o(Cz,"isHtml");function mS(e){return e==null||e===!1?"":Array.isArray(e)?e.map(mS).join(""):Cz(e)?e.value:bz(String(e))}o(mS,"renderValue");function Et(e){return{[pS]:!0,value:e}}o(Et,"trustedHtml");var Te=Et("");function N(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=mS(t[n]),r+=e[n+1]??"";return Et(r)}o(N,"html");function sr(e){return e.value}o(sr,"renderHtml");var Iz="text/html; charset=utf-8";function hS(e,t=200){return new Response(sr(e),{status:t,headers:{"content-type":Iz,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(hS,"apiKeyLoginHtmlResponse");function kp(e=401){return hS(N`<!doctype html><html><head><title>Login failed</title></head><body><main><h1>Login failed</h1><p>The API key could not be verified. Start the authorization flow again.</p></main></body></html>`,e)}o(kp,"apiKeyLoginFailureResponse");function fS(e){return hS(N`<!doctype html><html><head><title>API key login</title></head><body><main><h1>API key login</h1><form method="post" action="/oauth/api-key-login" autocomplete="off"><input type="hidden" name="state" value="${e}"><label for="apiKey">API key</label><input id="apiKey" name="apiKey" type="password" required autocomplete="off"><button type="submit">Continue</button></form></main></body></html>`)}o(fS,"renderApiKeyLoginForm");ae();ae();import{errors as TS,jwtVerify as AS,SignJWT as kS}from"jose";ae();import{errors as Dz,jwtVerify as Mz,SignJWT as qz}from"jose";function Nr(e){let t=Ee().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(Nr,"requireBrowserLoginField");ae();import{createRemoteJWKSet as Az,errors as za,jwtVerify as kz}from"jose";var Ez=c.object({id_token:c.string().min(1),token_type:c.string().min(1).optional(),expires_in:c.number().optional(),access_token:c.string().min(1).optional(),refresh_token:c.string().min(1).optional(),scope:c.string().min(1).optional()}),xz=c.object({error:c.string().min(1).optional(),error_description:c.string().min(1).optional(),error_uri:c.string().min(1).optional()});function Pz(e){let t=xz.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(Pz,"readIdpErrorFields");function Oz(e){return e instanceof za.JWTExpired?"expired":e instanceof za.JWTClaimValidationFailed?"claim":e instanceof za.JWSSignatureVerificationFailed?"signature":e instanceof za.JWKSNoMatchingKey?"jwks_no_match":e instanceof za.JWTInvalid?"invalid":e instanceof c.ZodError?"schema":"other"}o(Oz,"readJwtFailureKind");var Uz=c.object({sub:ie,nonce:c.string().min(1)}).catchall(c.unknown()),Ep;function Nz(e){return e instanceof Error&&"cause"in e?e.cause:e}o(Nz,"readErrorCause");function zz(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(zz,"readRuntimeGatewayCode");function $z(){if(!Ep){let e=Ee();Ep=Az(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Ep}o($z,"readFederatedJwks");async function gS(e){let t=Ee(),r=Nr("tokenUrl"),n=Nr("clientId"),a=Nr("clientSecret"),i=new URL("/oauth/callback",At(e.requestUrl)).toString(),s=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:a});try{let{response:u,json:d}=await _w(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:s},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!u.ok){let f=Pz(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:gt(r),idpStatus:u.status,...f},"Federated browser login token exchange returned non-2xx from the identity provider"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${u.status}${f.idpError?` idp_error=${f.idpError}`:""}${f.idpErrorDescription?` idp_error_description=${f.idpErrorDescription}`:""})`)})}let p=Ez.parse(d),l;try{({payload:l}=await kz(p.id_token,$z(),{issuer:t.oidc.issuer,audience:n}))}catch(f){let _={};throw ze(_,"error",f),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:Oz(f),idpHost:gt(r),expectedIssuer:t.oidc.issuer,..._},"Federated id_token failed jose verification"),f}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:gt(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=Uz.parse(l);return Bn({sub:m.sub,data:m},e.requestUrl)}catch(u){let d=_e(u)??zz(u);throw d!==void 0&&d!=="browser_login_verification_failed"?u:g("browser_login_verification_failed","Federated browser login callback could not be verified.",Nz(u))}}o(gS,"exchangeFederatedAuthorizationCode");var Pp="zuplo_mcp_session",_S="HS256",yS="zuplo-mcp-gateway",wS="zuplo-mcp-gateway",Lz=c.object({purpose:c.literal("gateway_browser_session"),sub:ie,browserLoginOrigin:c.string().min(1),roles:c.array(c.string().min(1)).optional(),exp:c.number().int().positive(),iat:c.number().int().positive().optional()});function jz(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let a=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}o(jz,"parseCookieHeader");async function SS(){return qt({purpose:"browser-session",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>xr(e,"browser-session"),"derive")})}o(SS,"getBrowserSessionKey");function xp(e){let t=new URL(de(e)),r=[`${Pp}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(xp,"buildBrowserSessionEvictionCookie");function Hz(e){let t=new URL(de(e.requestUrl)),r=[`${Pp}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(Hz,"serializeSessionCookie");function vS(e={}){return new URL(Nr("url")).origin}o(vS,"readBrowserLoginOrigin");function Op(){return Ee().browserLogin.stateTtlSeconds}o(Op,"readBrowserLoginStateTtlSeconds");function RS(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Bn(e.user,e.url)}o(RS,"resolveCurrentRequestPrincipal");async function Ys(e,t={}){let r=jz(e.headers.get("cookie")).get(Pp);if(!r)return{};try{let{payload:n}=await Mz(r,await SS(),{algorithms:[_S],issuer:yS,audience:wS}),a=Lz.parse(n);if(a.browserLoginOrigin!==vS(t))return{evictCookie:xp(e.url)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof Dz.JWTExpired?{evictCookie:xp(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:xp(e.url)})}}o(Ys,"readBrowserSession");async function $a(e){let t=Ee().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:vS({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new qz(r).setProtectedHeader({alg:_S,typ:"JWT"}).setIssuer(yS).setAudience(wS).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await SS());return Hz({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o($a,"createBrowserSessionCookie");async function bS(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(bS,"resolveApiKeyBrowserLoginPrincipal");async function CS(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Ys(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return gS({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(CS,"resolveBrowserLoginCallbackPrincipal");function IS(e){let t=Ee().browserLogin,r=new URL(Nr("url")),n=new URL("/oauth/callback",At(e.requestUrl));return i_(r)?(r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",Nr("clientId")),r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}o(IS,"buildBrowserLoginUrl");var ES=5*60,Gz=["mcp_user"],Xs="HS256",Qs="zuplo-mcp-gateway",ec="zuplo-mcp-gateway",Bz=c.object({purpose:c.literal("gateway_browser_login"),transactionId:Je,stateId:ms,exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),Fz=c.object({purpose:c.literal("gateway_authorization_setup"),transactionId:Je,stateId:ms,exp:c.number().int().positive(),iat:c.number().int().positive().optional()});async function xS(){return qt({purpose:"browser-login",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>xr(e,"browser-login"),"derive")})}o(xS,"getBrowserLoginKey");async function PS(){return qt({purpose:"authorization-csrf",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>xr(e,"authorization-csrf"),"derive")})}o(PS,"getCsrfKey");function Vz(e){return[...new Set([...Gz,...e.roles??[]])]}o(Vz,"buildRoles");function OS(e){return{repository:e.repository??V().downstreamOAuthRepository,now:e.now??new Date,ttlSeconds:Op()}}o(OS,"readPendingTransactionDependencies");function Kz(e,t){return e.subjectId===t.subjectId}o(Kz,"principalsMatch");function US(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(US,"toPendingPrincipal");function NS(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:z(e.now),expiresAt:z(Tt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:US(e.principal)}}o(NS,"createTransactionRecord");async function zS(e){if((await e.repository.savePendingAuthorizationTransaction(e.record,e.client===void 0?void 0:{client:e.client})).kind==="already_exists")throw g("oauth_state_reused","Authorization transaction state already exists.")}o(zS,"savePendingTransaction");async function Zz(e){return new kS({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:Xs,typ:"JWT"}).setIssuer(Qs).setAudience(ec).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await xS())}o(Zz,"signBrowserLoginState");async function $S(e){return new kS({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:_l()}).setProtectedHeader({alg:Xs,typ:"JWT"}).setIssuer(Qs).setAudience(ec).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await PS())}o($S,"signCsrfToken");async function tc(e){try{let{payload:t}=await AS(e,await xS(),{algorithms:[Xs],issuer:Qs,audience:ec}),r=Bz.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof TS.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(tc,"verifyBrowserLoginStateToken");async function Wz(e){try{let{payload:t}=await AS(e,await PS(),{algorithms:[Xs],issuer:Qs,audience:ec});return{transactionId:Fz.parse(t).transactionId}}catch(t){throw t instanceof TS.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Wz,"verifyCsrfToken");function Da(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Da,"pendingStateErrorCode");function DS(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Da(e==="consumed_already"?"consumed_already":e)}o(DS,"setupDecisionErrorCode");function Jz(e){if(e.kind!=="available")throw g(Da(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(Jz,"requireAwaitingSetup");function Yz(e){if(e.kind!=="available")throw g(Da(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(Yz,"requireAwaitingLogin");function Xz(e){if(!Kz(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(Xz,"requireCurrentPrincipalMatches");function MS(e){return typeof e.decideAuthorizationSetup=="function"}o(MS,"hasRuntimeHttpAuthorizationDecision");async function qS(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date,n=Op(),a=gl(),i=_l(),s=await Zz({transactionId:a,stateId:i,ttlSeconds:n}),u=NS({id:a,transaction:e.transaction,currentStateHash:await ee(s),phase:"awaiting_login",now:r,ttlSeconds:n});if(u.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return await zS({repository:t,record:u,client:e.transaction.client}),{transaction:u,browserLoginStateToken:s,browserLoginUrl:IS({state:s,nonce:i,virtualServerId:u.virtualServerId,requestUrl:e.requestUrl})}}o(qS,"startAwaitingLogin");async function LS(e){let{repository:t,now:r,ttlSeconds:n}=OS(e),a=gl(),i=await $S({transactionId:a,ttlSeconds:n}),s=NS({id:a,transaction:e.transaction,currentStateHash:await ee(i),phase:"awaiting_setup",principal:e.principal,now:r,ttlSeconds:n});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return await zS({repository:t,record:s,client:e.transaction.client}),{transaction:s,csrfToken:i}}o(LS,"startAwaitingSetup");async function Up(e){let{repository:t,now:r,ttlSeconds:n}=OS(e),a=await tc(e.browserLoginStateToken),i=await $S({transactionId:a.transactionId,ttlSeconds:n}),s=await t.advancePendingAuthorizationTransaction({id:a.transactionId,expectedPhase:"awaiting_login",currentStateHash:await ee(e.browserLoginStateToken),nextStateHash:await ee(i),nextPhase:"awaiting_setup",principal:US(e.principal),now:r});if(s.kind!=="advanced")throw g(Da(s.kind),"Browser login state is invalid, expired, or already used.");if(s.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:s.record,csrfToken:i}}o(Up,"completeLogin");async function jS(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date,n=await tc(e.browserLoginStateToken);return Yz(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await ee(e.browserLoginStateToken),now:r}))}o(jS,"getAwaitingLogin");async function Ma(e){let t=await Np(e);return Xz({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(Ma,"getSetup");async function Np(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date,n=await Wz(e.csrfToken);return Jz(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await ee(e.csrfToken),now:r}))}o(Np,"getSetupTransaction");async function Qz(e){let t=nt(),r=await ee(t),n=yl(),a=z(Tt(e.now,ES)),i={id:e.transaction.id,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,subjectId:e.transaction.principal.subjectId,scope:e.transaction.scope,roles:Vz(e.transaction.principal),codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:z(e.now),expiresAt:a};await e.repository.issueAuthorizationCode({...i,codeHash:r,grantId:n});let s=new URL(e.transaction.redirectUri);return s.searchParams.set("code",t),e.transaction.clientState&&s.searchParams.set("state",e.transaction.clientState),s}o(Qz,"createAuthorizationCodeRedirect");async function e$(e){let t=await Ma({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:e.now,repository:e.repository}),r=nt(),n=z(Tt(e.now,ES)),a=await e.repository.decideAuthorizationSetup({decision:"approve",transactionId:t.id,currentStateHash:await ee(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await ee(r),authorizationCodeExpiresAt:n,grantId:yl(),now:z(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":DS(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}o(e$,"createAuthorizationCodeRedirectWithDecision");async function t$(e){let t=await Ma({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:e.now,repository:e.repository}),r=await e.repository.decideAuthorizationSetup({decision:"cancel",transactionId:t.id,currentStateHash:await ee(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:z(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":DS(r.kind),"Authorization setup state is invalid, expired, or already used.");return HS({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(t$,"createCancelRedirectWithDecision");function HS(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}o(HS,"buildClientCancelRedirect");async function r$(e){let t=await Ma(e),r=await e.repository.consumePendingAuthorizationTransaction({id:t.id,currentStateHash:await ee(e.csrfToken),now:e.now});if(r.kind!=="consumed")throw g(Da(r.kind),"Authorization setup state is invalid, expired, or already used.");if(r.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return r.record}o(r$,"consumeSetup");async function GS(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date;return{repository:t,now:r,transaction:await r$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t})}}o(GS,"consumeSetupForDecision");async function BS(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date;if(MS(t))return e$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t});let n=await GS(e);return Qz({repository:n.repository,transaction:n.transaction,now:n.now})}o(BS,"approve");async function FS(e){let t=e.repository??V().downstreamOAuthRepository,r=e.now??new Date;if(MS(t))return t$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t});let{transaction:n}=await GS(e);return HS({redirectUri:n.redirectUri,clientState:n.clientState})}o(FS,"cancel");ae();var n$=1e4,o$=5*1024,a$=2,i$=90*24*60*60,zp=["authorization_code","refresh_token"],$p=["code"],s$=c.object({client_name:c.string().min(1).optional(),redirect_uris:c.array(c.string().min(1)).min(1),grant_types:c.array(c.enum(zp)).min(1).max(2).optional(),response_types:c.array(c.enum($p)).min(1).max(1).optional(),scope:c.literal(ve).optional(),token_endpoint_auth_method:ua.default("client_secret_basic")});function c$(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(c$,"isCimdClientIdCandidate");function ao(e,t="invalid_request"){if(u$(e))throw new D(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new D(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new D(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||Ve(r)))throw new D(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(ao,"assertValidRedirectUri");function u$(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(u$,"hasForbiddenRawRedirectUriCharacter");async function d$(e){let{response:t,json:r}=await yw(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:a$,maxResponseBytes:o$,timeoutMs:n$});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=o_.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");if(n.token_endpoint_auth_method!=="none")throw g("invalid_request","CIMD clients must use token_endpoint_auth_method none until private_key_jwt is implemented.");return n}o(d$,"fetchCimdMetadata");async function l$(e){let t=Ds(e),r=await d$({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(l$,"resolveCimdClient");async function qa(e,t,r){let n=ye.parse(t);if(c$(n)){if(!Ee().gateway.cimdEnabled)throw new D("invalid_client","OAuth client is not registered.");try{return await l$(n)}catch{throw new D("invalid_client","OAuth client is not registered.")}}let a=await e.getDcrClient(n);if(a){let i={kind:"dcr",clientId:n,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new D("invalid_client",n.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(qa,"resolveClient");function rc(e,t){if(!e.metadata.redirect_uris.some(r=>fs(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(rc,"assertRedirectRegistered");function p$(e){let t=VS(e.grant_types),r=e.response_types??[...$p];if(!m$(t))throw new D("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!h$(r))throw new D("invalid_client_metadata","response_types must be code.");if(!f$(e.scope))throw new D("invalid_client_metadata",`Only the ${ve} scope is supported.`)}o(p$,"assertSupportedDcrRequest");function VS(e){return e===void 0?[...zp]:Array.from(new Set(e))}o(VS,"normalizeGrantTypes");function m$(e){return e.length===0?!1:e.every(t=>zp.includes(t))}o(m$,"isSupportedGrantTypes");function h$(e){return e.length===$p.length&&e[0]==="code"}o(h$,"isSupportedResponseTypes");function f$(e){return e===void 0||e===ve}o(f$,"isSupportedDcrScope");function dn(e){if(e===void 0||e===ve)return ve;throw new D("invalid_request",`Only the ${ve} scope is supported.`)}o(dn,"assertSupportedOAuthScope");function jt(e,t){let r;try{r=new URL(t)}catch{throw new D("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new D("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Ve(r))throw new D("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=de(e),a=Lg(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new D("invalid_target","resource must match a published virtual MCP server.");return i}o(jt,"resolveResource");async function KS(e,t={}){let r=g$(t)?{repository:t}:t,n;try{n=s$.parse(e)}catch(f){if(f instanceof c.ZodError){let _=f.issues.some(w=>w.path[0]==="redirect_uris");throw new D(_?"invalid_redirect_uri":"invalid_client_metadata",f.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:f})}throw f}p$(n);for(let f of n.redirect_uris)ao(f,"invalid_redirect_uri");let a=r.repository??V().downstreamOAuthRepository,i=new Date,s=ye.parse(`dcr:${crypto.randomUUID()}`),u=Tt(i,i$),d=Math.floor(i.getTime()/1e3),p=Math.floor(u.getTime()/1e3),l={client_id:s,client_name:n.client_name??"Dynamically registered MCP client",redirect_uris:n.redirect_uris,grant_types:VS(n.grant_types),response_types:["code"],scope:ve,token_endpoint_auth_method:n.token_endpoint_auth_method,client_id_issued_at:d},m={clientId:s,clientName:String(l.client_name),redirectUris:n.redirect_uris,tokenEndpointAuthMethod:n.token_endpoint_auth_method,createdAt:z(i),clientExpiresAt:z(u)};if(n.token_endpoint_auth_method!=="none"){let f=nt();m.hashedClientSecret=await ee(f),m.clientSecretExpiresAt=z(u),l.client_secret=f,l.client_secret_expires_at=p,l.client_secret_issued_at=d}return await a.saveDcrClient(m),l}o(KS,"registerDownstreamClient");function g$(e){return typeof e.getDcrClient=="function"}o(g$,"isOAuthRepository");var _$=8;function Mp(e){let t=e.trim();try{let r=new URL(t);if(r.protocol==="https:")return r.toString()}catch{}if(/^data:image\/(?:png|jpe?g|webp);/i.test(t))return t}o(Mp,"safeIconSrc");function y$(e,t){if(e)try{let r=new URL(t).origin,n=new URL(e,r);return n.origin!==r||!n.pathname.startsWith("/auth/connections/")?void 0:n.toString()}catch{return}}o(y$,"safeGatewayConnectHref");function w$(e){if(e==="any")return Number.POSITIVE_INFINITY;let t=/^(\d+)x(\d+)$/.exec(e);return t?Math.max(Number(t[1]),Number(t[2])):0}o(w$,"parseIconSize");function S$(e,t){let r=e.filter(a=>a.theme===t);if(r.length>0)return r;let n=e.filter(a=>a.theme===void 0);return n.length>0?n:e}o(S$,"selectIconCandidates");function v$(e){return Mp(e.src)?e.sizes&&e.sizes.length>0?Math.max(...e.sizes.map(w$)):0:-1}o(v$,"readIconScore");function JS(e,t){if(!e||e.length===0)return;let r=S$(e,t),n,a=-1;for(let i of r){let s=v$(i);s>a&&(n=i,a=s)}return n}o(JS,"pickIcon");var R$='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>',ZS=Et(R$),b$=Et('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>'),C$=Et('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>'),YS=Et('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),WS=Et('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 1.5 2.5 3.5v4.2c0 3.4 2.4 5.6 5.5 6.8 3.1-1.2 5.5-3.4 5.5-6.8V3.5L8 1.5Z"/><path d="m5.8 8.2 1.6 1.6 3-3"/></svg>');function I$(e,t){let r=JS(e,"light");if(!r)return N`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ZS}</span>`;let n=Mp(r.src);return n?N`<span class="icon-frame"><img src="${n}" alt="${t}" loading="lazy" decoding="async"></span>`:N`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ZS}</span>`}o(I$,"renderIconFrame");function oc(e,t){let r=JS(e,"light");if(!r)return Te;let n=Mp(r.src);return n?N`<img class="inline-icon" src="${n}" alt="${t}" loading="lazy" decoding="async">`:Te}o(oc,"renderInlineIcon");function T$(e){switch(e){case"user":return"your account";case"shared":return"shared by your team";case"none":return"gateway-managed"}}o(T$,"ownerModeLabel");function A$(e){return e.endsWith("_oauth")||e==="oauth"?"OAuth":e.includes("static_secret")?"static credential":e.replaceAll("_"," ")}o(A$,"authModeLabel");function k$(e){switch(e){case"active":return N`<span class="status-badge status-badge--success">Connected</span>`;case"not_connected":return N`<span class="status-badge status-badge--neutral">Not connected</span>`;case"reconsent_required":return N`<span class="status-badge status-badge--warning">Reconnect required</span>`}}o(k$,"statusBadge");function E$(e){if(!e)return Te;let t=[];return e.destructiveHint&&t.push(N`<span class="badge badge--destructive" title="This tool may modify or delete data on your behalf.">destructive</span>`),e.readOnlyHint&&t.push(N`<span class="badge badge--muted" title="This tool only reads data and does not modify state.">read-only</span>`),e.openWorldHint&&t.push(N`<span class="badge badge--muted" title="This tool can access arbitrary URIs supplied at call time.">open-world</span>`),t.length>0?N`<span class="badge-row">${t}</span>`:Te}o(E$,"annotationBadges");function XS(e){let t=0,r=0;for(let n of e.tools)n.annotations?.destructiveHint===!0&&(t+=1),n.annotations?.readOnlyHint===!0&&(r+=1);return{tools:e.tools.length,prompts:e.prompts.length,resources:e.resources.length,destructiveTools:t,readOnlyTools:r}}o(XS,"summarizeCapabilities");function x$(e){let t=e.annotations?.title??e.title??e.name,r=e.description?N`<span class="capability-row__description">${e.description}</span>`:Te;return N`<li class="capability-row">${oc(e.icons,t)}<span class="capability-row__name">${t}</span>${E$(e.annotations)}${r}</li>`}o(x$,"renderToolRow");function P$(e){let t=e.title??e.name,r=e.description?N`<span class="capability-row__description">${e.description}</span>`:Te;return N`<li class="capability-row">${oc(e.icons,t)}<span class="capability-row__name">${t}</span>${r}</li>`}o(P$,"renderPromptRow");function O$(e){let t=e.title??e.name,r=e.mimeType===void 0?Te:N` · ${e.mimeType}`,n=e.description===void 0?Te:N` — ${e.description}`,a=N`<span class="capability-row__description"><code>${e.uri}</code>${r}${n}</span>`;return N`<li class="capability-row">${oc(e.icons,t)}<span class="capability-row__name">${t}</span>${a}</li>`}o(O$,"renderResourceRow");function Dp(e,t,r,n){if(t===0)return Te;let a=r.slice(0,_$),i=t-a.length,s=i>0?N`<li class="capability-row capability-row--more">+ ${i} more</li>`:Te;return N`<section class="capability-section"><h4 class="capability-section__title">${e} <span class="muted">(${t})</span></h4><ul class="capability-list">${a.map(n)}${s}</ul></section>`}o(Dp,"renderCapabilitySection");function nc(e,t,r=!1){return r?N`<span class="count-pill count-pill--destructive"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`:N`<span class="count-pill"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`}o(nc,"countPill");function U$(e){let t=XS(e);if(t.tools+t.prompts+t.resources===0)return N`<div class="upstream-card__capabilities upstream-card__capabilities--empty">No tools, prompts, or resources advertised.</div>`;let n=[];t.tools>0&&n.push(nc(t.tools===1?"tool":"tools",t.tools)),t.prompts>0&&n.push(nc(t.prompts===1?"prompt":"prompts",t.prompts)),t.resources>0&&n.push(nc(t.resources===1?"resource":"resources",t.resources)),t.destructiveTools>0&&n.push(nc("destructive",t.destructiveTools,!0));let a=[Dp("Tools",t.tools,e.tools,x$),Dp("Prompts",t.prompts,e.prompts,P$),Dp("Resources",t.resources,e.resources,O$)];return N`<details class="upstream-card__capabilities"><summary class="capabilities-summary"><span class="capabilities-summary__counts">${n}</span><span class="capabilities-summary__chevron" aria-hidden="true">${YS}</span></summary><div class="capabilities-detail">${a}</div></details>`}o(U$,"renderUpstreamCapabilities");function N$(e){if(!e||e.length===0)return Te;let t=e.map(n=>N`<code class="scope-chip">${n}</code>`),r=e.length===1?"scope":"scopes";return N`<details class="upstream-card__scopes"><summary class="scopes-summary"><span>Requested ${r} <span class="muted">(${e.length})</span></span><span class="capabilities-summary__chevron" aria-hidden="true">${YS}</span></summary><div class="scopes-list">${t}</div></details>`}o(N$,"renderUpstreamScopes");function z$(e,t){if(e.ownerMode!=="user")return Te;let r=y$(e.connectUrl,t);if(!r)return Te;let n=e.status==="active"?"Redo auth":e.status==="reconsent_required"?"Reconnect":"Connect",a=e.status==="active"?"Reconnect this upstream account or approve updated scopes.":void 0;return N`<a class="button button--secondary button--small" href="${r}"${a===void 0?Te:N` title="${a}"`}>${n}</a>`}o(z$,"renderActionButton");function $$(e,t){let r=z$(e,t);return sr(r)!==""?r:k$(e.status)}o($$,"renderUpstreamControl");function D$(e,t){let n=e.ownerMode==="user"&&e.status!=="active"?Et('<article class="upstream-card upstream-card--needs-action">'):Et('<article class="upstream-card">'),a=e.description?N`<p class="upstream-card__description">${e.description}</p>`:Te,i=e.transportHost?N`<code class="upstream-card__host">${e.transportHost}</code><span class="upstream-card__sep" aria-hidden="true">·</span>`:Te,s=N`<div class="upstream-card__head">${I$(e.serverIcons,e.upstreamDisplayName)}<div class="upstream-card__main"><div class="upstream-card__title-row"><h3 class="upstream-card__title">${e.upstreamDisplayName}</h3>${$$(e,t)}</div><div class="upstream-card__meta">${i}<span>${A$(e.authMode)}</span><span class="upstream-card__sep" aria-hidden="true">·</span><span>${T$(e.ownerMode)}</span></div>${a}</div></div>`,u=U$(e.capabilities),d=N$(e.scopesRequested);return N`${n}${s}${u}${d}</article>`}o(D$,"renderUpstreamCard");function M$(e){return e.reduce((t,r)=>{let n=XS(r.capabilities);return t.tools+=n.tools,t.prompts+=n.prompts,t.resources+=n.resources,t.destructiveTools+=n.destructiveTools,t.readOnlyTools+=n.readOnlyTools,t},{tools:0,prompts:0,resources:0,destructiveTools:0,readOnlyTools:0})}o(M$,"aggregateCapabilities");function q$(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(q$,"deriveMode");function L$(e){if(e.mode==="setup"){let n=e.upstreams.filter(u=>u.ownerMode==="user"&&u.status!=="active"),a=n.length>0&&n.every(u=>u.status==="reconsent_required"),i=n.length===1?"the service":`the ${n.length} services`,s=a?N`Re-authorize ${i} below to refresh access. Authorization will continue automatically once each is ready.`:N`Connect ${i} below before continuing. Authorization will continue automatically once each is ready.`;return N`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${b$}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${s}</p></div></div>`}let t=M$(e.upstreams);if(t.destructiveTools===0)return Te;let r=t.destructiveTools===1?"tool can":"tools can";return N`<div class="banner banner--alert" role="alert"><span class="banner__icon" aria-hidden="true">${C$}</span><div class="banner__body"><p class="banner__title">${t.destructiveTools} ${r} modify or delete data</p><p class="banner__message">Review the destructive tools below before authorizing <strong>${e.clientDisplayName}</strong>.</p></div></div>`}o(L$,"renderBanner");function j$(e){return e.mode==="grant"?N`<form class="actions" method="post" action="/oauth/setup"><input type="hidden" name="state" value="${e.state}"><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve">Authorize</button></form>`:N`<form class="actions" method="post" action="/oauth/setup"><input type="hidden" name="state" value="${e.state}"><input type="hidden" name="decision" value="continue"><button class="button button--primary" type="submit">Check again</button></form>`}o(j$,"renderActions");var H$=`
976
- *,*::before,*::after{box-sizing:border-box}
977
- :root{
978
- --bg:#ffffff;
979
- --surface:#ffffff;
980
- --surface-2:#f1f5f9;
981
- --border:#e2e8f0;
982
- --border-strong:#c9cace;
983
- --text:#20222e;
984
- --text-2:#475569;
985
- --text-3:#64748b;
986
- --brand:#ff00bd;
987
- --brand-strong:#d600a0;
988
- --brand-soft:#fff0f7;
989
- --brand-ring:rgba(255,0,189,.15);
990
- --success:#13a688;
991
- --success-soft:rgba(19,166,136,.10);
992
- --success-border:rgba(19,166,136,.32);
993
- --warning:#b45309;
994
- --warning-soft:#fff7ed;
995
- --warning-border:#fcd9b6;
996
- --danger:#d03c38;
997
- --danger-soft:rgba(208,60,56,.08);
998
- --danger-border:rgba(208,60,56,.28);
999
- --radius:2px;
1000
- --radius-md:6px;
1001
- --radius-lg:8px;
1002
- --shadow-sm:0 1px 2px rgba(15,23,42,.04);
1003
- --shadow-md:0 1px 3px rgba(15,23,42,.06),0 1px 2px rgba(15,23,42,.04);
1004
- --shadow-lg:0 8px 24px rgba(15,23,42,.08);
1005
- --font-sans:Inter,"Inter Fallback",-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;
1006
- --font-heading:"Readex Pro","Readex Pro Fallback",Inter,system-ui,sans-serif;
1007
- --font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace;
1008
- }
1009
- @media (prefers-color-scheme: dark){
1010
- :root{
1011
- --bg:#0a0c10;
1012
- --surface:#15171c;
1013
- --surface-2:#1e2128;
1014
- --border:#262932;
1015
- --border-strong:#3a3e48;
1016
- --text:#fafafa;
1017
- --text-2:#9ba3b0;
1018
- --text-3:#71757f;
1019
- --brand:#ff33c8;
1020
- --brand-strong:#ff66d4;
1021
- --brand-soft:rgba(255,0,189,.14);
1022
- --brand-ring:rgba(255,0,189,.28);
1023
- --success:#34d399;
1024
- --success-soft:rgba(19,166,136,.16);
1025
- --success-border:rgba(52,211,153,.32);
1026
- --warning:#fbbf24;
1027
- --warning-soft:rgba(251,191,36,.10);
1028
- --warning-border:rgba(251,191,36,.32);
1029
- --danger:#f87171;
1030
- --danger-soft:rgba(208,60,56,.14);
1031
- --danger-border:rgba(248,113,113,.32);
1032
- --shadow-sm:0 1px 2px rgba(0,0,0,.4);
1033
- --shadow-md:0 1px 3px rgba(0,0,0,.45),0 1px 2px rgba(0,0,0,.3);
1034
- --shadow-lg:0 12px 28px rgba(0,0,0,.5);
1035
- }
1036
- }
1037
- html,body{margin:0;padding:0}
1038
- html{background:var(--bg);height:100%}
1039
- body{
1040
- font-family:var(--font-sans);
1041
- background:var(--bg);
1042
- color:var(--text);
1043
- font-size:14px;
1044
- line-height:1.5;
1045
- -webkit-font-smoothing:antialiased;
1046
- -moz-osx-font-smoothing:grayscale;
1047
- height:100vh;
1048
- height:100dvh;
1049
- display:flex;flex-direction:column;
1050
- overflow:hidden;
1051
- }
1052
- .topbar{
1053
- flex-shrink:0;
1054
- background:var(--surface);
1055
- border-bottom:1px solid var(--border);
1056
- }
1057
- .topbar__inner{
1058
- max-width:640px;margin:0 auto;
1059
- display:flex;align-items:center;justify-content:space-between;
1060
- gap:16px;padding:14px 24px;
1061
- }
1062
- .brand{
1063
- display:flex;align-items:center;gap:10px;
1064
- color:var(--text);font-weight:600;font-size:13px;
1065
- letter-spacing:-.01em;
1066
- }
1067
- .brand__mark{
1068
- width:22px;height:22px;border-radius:var(--radius);
1069
- background:var(--brand);color:#fff;
1070
- display:inline-flex;align-items:center;justify-content:center;
1071
- font-weight:700;font-size:12px;letter-spacing:0;
1072
- font-family:var(--font-heading);
1073
- }
1074
- .brand__name{color:var(--text-2);font-weight:500}
1075
- .principal{
1076
- display:inline-flex;align-items:center;gap:6px;
1077
- font-size:12.5px;color:var(--text-3);
1078
- padding:4px 10px;border-radius:9999px;
1079
- background:var(--surface-2);
1080
- max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
1081
- }
1082
- .shell-main{
1083
- flex:1;min-height:0;
1084
- display:flex;flex-direction:column;
1085
- width:100%;
1086
- }
1087
- .static-top{flex-shrink:0;background:var(--bg)}
1088
- .static-top__inner{
1089
- max-width:640px;margin:0 auto;width:100%;
1090
- padding:32px 24px 16px;
1091
- display:flex;flex-direction:column;gap:18px;
1092
- }
1093
- .hero{display:flex;flex-direction:column;gap:6px;margin:0}
1094
- .hero__title{
1095
- margin:0;font-family:var(--font-heading);
1096
- font-size:28px;font-weight:600;letter-spacing:-.02em;
1097
- color:var(--text);line-height:1.2;
1098
- }
1099
- .hero__connection{
1100
- margin:2px 0 0;font-size:15px;color:var(--text-2);
1101
- display:flex;align-items:center;gap:10px;flex-wrap:wrap;
1102
- line-height:1.4;
1103
- }
1104
- .hero__client,.hero__server{
1105
- color:var(--text);font-weight:600;
1106
- display:inline-flex;align-items:center;gap:6px;
1107
- min-width:0;
1108
- }
1109
- .hero__server .inline-icon{
1110
- width:16px;height:16px;border-radius:3px;margin:0;
1111
- vertical-align:baseline;
1112
- }
1113
- .hero__arrow{
1114
- color:var(--text-3);font-weight:500;
1115
- display:inline-flex;align-items:center;
1116
- }
1117
- .hero__description{
1118
- margin:6px 0 0;color:var(--text-2);font-size:13.5px;line-height:1.5;
1119
- }
1120
- .banner{
1121
- display:flex;align-items:flex-start;gap:12px;
1122
- padding:12px 14px;border-radius:var(--radius-md);
1123
- border:1px solid;
1124
- font-size:13.5px;
1125
- }
1126
- .banner__icon{
1127
- flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;
1128
- width:18px;height:18px;margin-top:1px;
1129
- }
1130
- .banner__body{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
1131
- .banner__title{margin:0;font-weight:600;color:var(--text);font-size:13.5px}
1132
- .banner__message{margin:0;color:var(--text-2);font-size:13px;line-height:1.5}
1133
- .banner--warning{background:var(--warning-soft);border-color:var(--warning-border)}
1134
- .banner--warning .banner__icon{color:var(--warning)}
1135
- .banner--alert{background:var(--danger-soft);border-color:var(--danger-border)}
1136
- .banner--alert .banner__icon{color:var(--danger)}
1137
- .banner--alert .banner__title{color:var(--danger)}
1138
- .upstream-region{
1139
- flex:1;min-height:0;
1140
- display:flex;flex-direction:column;
1141
- background:var(--bg);
1142
- }
1143
- .upstream-region__head{
1144
- flex-shrink:0;
1145
- max-width:640px;width:100%;margin:0 auto;
1146
- padding:8px 24px 8px;
1147
- display:flex;align-items:center;justify-content:space-between;gap:12px;
1148
- }
1149
- .section-label{
1150
- margin:0;font-size:11px;font-weight:600;
1151
- text-transform:uppercase;letter-spacing:.07em;
1152
- color:var(--text-3);
1153
- }
1154
- .section-label__count{color:var(--text-3);font-weight:500;margin-left:4px}
1155
- .upstream-region__scroll{
1156
- flex:1;min-height:0;
1157
- overflow-y:auto;
1158
- overscroll-behavior:contain;
1159
- scrollbar-width:thin;
1160
- scrollbar-color:var(--border-strong) transparent;
1161
- }
1162
- .upstream-region__scroll::-webkit-scrollbar{width:8px}
1163
- .upstream-region__scroll::-webkit-scrollbar-track{background:transparent}
1164
- .upstream-region__scroll::-webkit-scrollbar-thumb{background:var(--border-strong);border-radius:4px;border:2px solid var(--bg)}
1165
- .upstream-region__scroll-inner{
1166
- max-width:640px;margin:0 auto;width:100%;
1167
- padding:0 24px 24px;
1168
- }
1169
- .upstream-list{
1170
- display:flex;flex-direction:column;gap:10px;
1171
- margin:0;padding:0;list-style:none;
1172
- }
1173
- .upstream-card{
1174
- background:var(--surface);
1175
- border:1px solid var(--border);
1176
- border-radius:var(--radius-md);
1177
- padding:16px;
1178
- display:flex;flex-direction:column;gap:12px;
1179
- transition:border-color .12s ease,background .12s ease;
1180
- }
1181
- .upstream-card--needs-action{
1182
- border-color:var(--warning-border);
1183
- background:linear-gradient(to bottom,color-mix(in srgb,var(--warning-soft) 70%,var(--surface)),var(--surface) 56px);
1184
- }
1185
- .upstream-card__head{display:flex;align-items:flex-start;gap:12px}
1186
- .icon-frame{
1187
- flex-shrink:0;width:36px;height:36px;
1188
- border-radius:var(--radius-md);border:1px solid var(--border);
1189
- background:var(--surface-2);color:var(--text-3);
1190
- display:inline-flex;align-items:center;justify-content:center;
1191
- overflow:hidden;
1192
- }
1193
- .icon-frame img{max-width:100%;max-height:100%;object-fit:contain}
1194
- .icon-frame--fallback svg{width:20px;height:20px}
1195
- .inline-icon{
1196
- width:14px;height:14px;border-radius:2px;object-fit:contain;
1197
- vertical-align:-2px;margin-right:4px;
1198
- }
1199
- .upstream-card__main{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}
1200
- .upstream-card__title-row{
1201
- display:flex;align-items:center;gap:10px;justify-content:space-between;
1202
- min-width:0;
1203
- }
1204
- .upstream-card__title{
1205
- margin:0;font-family:var(--font-heading);
1206
- font-size:14.5px;font-weight:600;
1207
- color:var(--text);letter-spacing:-.005em;line-height:1.3;
1208
- overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;
1209
- }
1210
- .upstream-card__meta{
1211
- display:flex;align-items:center;gap:6px;flex-wrap:wrap;
1212
- font-size:12px;color:var(--text-3);
1213
- }
1214
- .upstream-card__host{
1215
- font-family:var(--font-mono);font-size:11.5px;
1216
- background:var(--surface-2);color:var(--text-2);
1217
- padding:1px 6px;border-radius:var(--radius);
1218
- }
1219
- .upstream-card__sep{color:var(--border-strong)}
1220
- .upstream-card__description{
1221
- margin:4px 0 0;font-size:13px;color:var(--text-2);line-height:1.5;
1222
- }
1223
- .status-badge{
1224
- display:inline-flex;align-items:center;gap:6px;
1225
- padding:3px 9px;border-radius:9999px;
1226
- font-size:11.5px;font-weight:600;letter-spacing:.005em;
1227
- white-space:nowrap;border:1px solid transparent;
1228
- flex-shrink:0;
1229
- }
1230
- .status-badge::before{
1231
- content:"";width:6px;height:6px;border-radius:50%;
1232
- background:currentColor;flex-shrink:0;
1233
- }
1234
- .status-badge--success{
1235
- background:var(--success-soft);color:var(--success);
1236
- border-color:var(--success-border);
1237
- }
1238
- .status-badge--warning{
1239
- background:var(--warning-soft);color:var(--warning);
1240
- border-color:var(--warning-border);
1241
- }
1242
- .status-badge--neutral{
1243
- background:var(--surface-2);color:var(--text-2);
1244
- border-color:var(--border);
1245
- }
1246
- .upstream-card__capabilities{
1247
- border-top:1px solid var(--border);
1248
- padding-top:12px;
1249
- }
1250
- .upstream-card__capabilities--empty{
1251
- font-size:12.5px;color:var(--text-3);font-style:italic;
1252
- }
1253
- .capabilities-summary,.scopes-summary{
1254
- display:flex;align-items:center;justify-content:space-between;
1255
- gap:12px;cursor:pointer;list-style:none;user-select:none;
1256
- font-size:13px;color:var(--text-2);
1257
- padding:2px 0;
1258
- }
1259
- .capabilities-summary::-webkit-details-marker,
1260
- .scopes-summary::-webkit-details-marker{display:none}
1261
- .capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}
1262
- .capabilities-summary:focus-visible,.scopes-summary:focus-visible{
1263
- outline:2px solid var(--brand);outline-offset:2px;border-radius:var(--radius);
1264
- }
1265
- .capabilities-summary__counts{
1266
- display:flex;gap:14px;align-items:center;flex-wrap:wrap;
1267
- }
1268
- .count-pill{
1269
- display:inline-flex;align-items:baseline;gap:4px;
1270
- font-size:12.5px;color:var(--text-2);
1271
- }
1272
- .count-pill__num{
1273
- font-weight:600;font-variant-numeric:tabular-nums;
1274
- color:var(--text);font-size:13px;
1275
- }
1276
- .count-pill--destructive .count-pill__num{color:var(--danger)}
1277
- .count-pill--destructive .count-pill__label{color:var(--danger)}
1278
- .capabilities-summary__chevron{
1279
- color:var(--text-3);transition:transform .15s ease;
1280
- display:inline-flex;flex-shrink:0;
1281
- }
1282
- details[open] > .capabilities-summary .capabilities-summary__chevron,
1283
- details[open] > .scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}
1284
- .capabilities-detail{margin-top:12px}
1285
- .capability-section{margin-top:16px}
1286
- .capability-section:first-child{margin-top:8px}
1287
- .capability-section__title{
1288
- margin:0 0 6px;font-size:11px;font-weight:600;
1289
- text-transform:uppercase;letter-spacing:.07em;
1290
- color:var(--text-3);
1291
- }
1292
- .capability-list{
1293
- list-style:none;margin:0;padding:0;
1294
- display:flex;flex-direction:column;gap:6px;font-size:13px;
1295
- }
1296
- .capability-row{
1297
- display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;
1298
- padding:3px 0;
1299
- }
1300
- .capability-row__name{
1301
- font-weight:500;font-family:var(--font-mono);
1302
- font-size:12.5px;color:var(--text);
1303
- }
1304
- .capability-row__description{
1305
- color:var(--text-3);font-size:12.5px;
1306
- flex-basis:100%;line-height:1.45;
1307
- }
1308
- .capability-row__description code{
1309
- font-family:var(--font-mono);background:var(--surface-2);
1310
- padding:1px 4px;border-radius:var(--radius);color:var(--text-2);
1311
- }
1312
- .capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}
1313
- .upstream-card__scopes{
1314
- border-top:1px solid var(--border);padding-top:12px;
1315
- }
1316
- .scopes-list{
1317
- display:flex;flex-wrap:wrap;gap:5px;margin-top:10px;
1318
- }
1319
- .scope-chip{
1320
- font-family:var(--font-mono);font-size:11.5px;
1321
- background:var(--surface-2);color:var(--text-2);
1322
- padding:2px 7px;border-radius:var(--radius);
1323
- border:1px solid var(--border);
1324
- }
1325
- .badge{
1326
- display:inline-flex;align-items:center;
1327
- border-radius:var(--radius);padding:1px 5px;
1328
- font-size:10px;font-weight:600;letter-spacing:.04em;
1329
- text-transform:uppercase;
1330
- }
1331
- .badge--destructive{background:var(--danger-soft);color:var(--danger)}
1332
- .badge--muted{background:var(--surface-2);color:var(--text-3)}
1333
- .badge-row{display:inline-flex;gap:4px;flex-wrap:wrap}
1334
- .muted{color:var(--text-3)}
1335
- .button{
1336
- font:inherit;font-weight:500;font-size:14px;
1337
- padding:9px 16px;border-radius:var(--radius);
1338
- border:1px solid transparent;cursor:pointer;
1339
- text-decoration:none;
1340
- display:inline-flex;align-items:center;justify-content:center;gap:6px;
1341
- white-space:nowrap;
1342
- transition:background .12s ease,border-color .12s ease,color .12s ease,box-shadow .12s ease,transform .04s ease;
1343
- }
1344
- .button:active{transform:translateY(1px)}
1345
- .button--small{font-size:13px;padding:6px 12px}
1346
- .button--primary{
1347
- background:var(--brand);color:#ffffff;
1348
- border-color:var(--brand);
1349
- }
1350
- .button--primary:hover{background:var(--brand-strong);border-color:var(--brand-strong)}
1351
- .button--primary:focus-visible{
1352
- outline:0;
1353
- box-shadow:0 0 0 3px var(--brand-ring);
1354
- }
1355
- .button--secondary{
1356
- background:var(--surface);color:var(--text);
1357
- border-color:var(--border-strong);
1358
- }
1359
- .button--secondary:hover{background:var(--surface-2)}
1360
- .button--secondary:focus-visible{
1361
- outline:0;
1362
- box-shadow:0 0 0 3px var(--brand-ring);
1363
- border-color:var(--brand);
1364
- }
1365
- .action-bar{
1366
- flex-shrink:0;
1367
- background:var(--surface);
1368
- border-top:1px solid var(--border);
1369
- }
1370
- .action-bar__inner{
1371
- max-width:640px;margin:0 auto;
1372
- display:flex;align-items:center;justify-content:space-between;gap:16px;
1373
- padding:12px max(24px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));
1374
- }
1375
- .fineprint{
1376
- margin:0;flex:1;color:var(--text-3);font-size:12px;
1377
- line-height:1.45;display:flex;align-items:center;gap:6px;
1378
- }
1379
- .fineprint__icon{
1380
- flex-shrink:0;display:inline-flex;color:var(--text-3);
1381
- }
1382
- .fineprint strong{color:var(--text-2);font-weight:600}
1383
- .actions{display:flex;gap:8px;margin:0;flex-shrink:0}
1384
- .empty{
1385
- text-align:center;padding:32px 24px;
1386
- color:var(--text-3);font-size:13.5px;
1387
- border:1px dashed var(--border);border-radius:var(--radius-md);
1388
- background:var(--surface);
1389
- }
1390
- @media (max-width:600px){
1391
- .topbar__inner{padding:12px 16px}
1392
- .principal{font-size:11.5px;max-width:160px;padding:3px 8px}
1393
- .static-top__inner{padding:24px 16px 12px;gap:14px}
1394
- .upstream-region__head{padding:6px 16px}
1395
- .upstream-region__scroll-inner{padding:0 16px 20px}
1396
- .hero__title{font-size:24px}
1397
- .hero__connection{font-size:14px;gap:6px}
1398
- .upstream-card{padding:14px}
1399
- .action-bar__inner{flex-direction:column;align-items:stretch;gap:10px;padding:12px 16px max(12px,env(safe-area-inset-bottom))}
1400
- .actions{flex-direction:column-reverse;width:100%}
1401
- .button{width:100%;padding:11px 16px}
1402
- .fineprint{justify-content:center;text-align:center;font-size:11.5px}
1403
- }
1404
- @media (prefers-reduced-motion: reduce){
1405
- *{transition:none!important}
1406
- }
1407
- `,G$=Et(H$);function qp(e){let t=q$(e.upstreams),r=[...e.upstreams].sort((m,f)=>{let _=o(y=>y.ownerMode!=="user"?2:y.status==="active"?1:0,"blockedRank"),w=_(m)-_(f);return w!==0?w:m.upstreamDisplayName.localeCompare(f.upstreamDisplayName)}),n=e.principalLabel?N`<span class="principal" title="Signed in as ${e.principalLabel}">${e.principalLabel}</span>`:Te,a=e.virtualServerDescription?N`<p class="hero__description">${e.virtualServerDescription}</p>`:Te,i=oc(e.virtualServerIcons,e.virtualServerDisplayName),s=L$({mode:t,upstreams:r,clientDisplayName:e.clientDisplayName}),u=r.length===0?N`<div class="empty">This virtual server does not declare any upstream services.</div>`:N`<ul class="upstream-list">${r.map(m=>N`<li>${D$(m,e.gatewayOrigin)}</li>`)}</ul>`,d=j$({mode:t,state:e.state}),p=t==="grant"?N`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${WS}</span><span><strong>${e.clientDisplayName}</strong> will receive a token scoped to <strong>${e.virtualServerDisplayName}</strong>. You can revoke access at any time.</span></p>`:N`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${WS}</span><span>Authorization continues automatically once every required service is connected.</span></p>`,l=r.length>0?N`<span class="section-label__count">(${r.length})</span>`:Te;return sr(N`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Authorize MCP access · ${e.virtualServerDisplayName}</title><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><meta name="robots" content="noindex"><style>${G$}</style></head><body><header class="topbar"><div class="topbar__inner"><div class="brand"><span class="brand__mark" aria-hidden="true">Z</span><span class="brand__name">Zuplo MCP Gateway</span></div>${n}</div></header><main class="shell-main"><div class="static-top"><div class="static-top__inner"><section class="hero"><h1 class="hero__title">Authorize access</h1><p class="hero__connection"><span class="hero__client">${e.clientDisplayName}</span><span class="hero__arrow" aria-label="will access">→</span><span class="hero__server">${i}${e.virtualServerDisplayName}</span></p>${a}</section>${s}</div></div><section class="upstream-region" aria-labelledby="upstreams-heading"><div class="upstream-region__head"><h2 id="upstreams-heading" class="section-label">Upstream services${l}</h2></div><div class="upstream-region__scroll"><div class="upstream-region__scroll-inner">${u}</div></div></section></main><div class="action-bar" role="region" aria-label="Authorization decision"><div class="action-bar__inner">${p}${d}</div></div></body></html>`)}o(qp,"renderConsentPage");function B$(e){try{return new URL(e).host}catch{return}}o(B$,"safeUrlHost");function F$(e){if(e.mode==="user_oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(F$,"readOAuthScopes");function Lp(e){return e!==void 0&&e.length>0}o(Lp,"hasItems");function V$(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Lp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Lp(r)?r:void 0}o(V$,"readServerIcons");async function K$(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Zl({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(K$,"readConnectUrl");function ln(e,t){return t===void 0?{}:{[e]:t}}o(ln,"optionalRequirementField");function Z$(e){return e.isUserOwned?A_(e.connection):{connected:!0,status:"active"}}o(Z$,"readSetupConnectionStatus");function W$(e){let t=F$(e);return Lp(t)?t:void 0}o(W$,"readScopesRequested");function J$(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(J$,"readUpdatedAt");function Y$(e){if(e.virtualServer.catalog.catalogSource!=="openapi")return{tools:[],prompts:[],resources:[]};let t=o(r=>r.upstreamPolicyName===e.registeredConnection.policyName,"ownsCapability");return{tools:e.virtualServer.catalog.tools.filter(r=>r.enabled!==!1&&t(r)).map(as),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(is),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(ss)}}o(Y$,"readVirtualServerCapabilities");async function X$(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=As(r),u=s==="user",d=Z$({connection:e.connection,isUserOwned:u}),p=await K$({...e,connected:d.connected,isUserOwned:u});return{upstreamServerId:a,authProfileId:i,authMode:r,ownerMode:s,upstreamDisplayName:n.displayName,status:d.status,connected:d.connected,capabilities:Y$({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...ln("description",n.description),...ln("transportHost",B$(n.transport.baseUrl)),...ln("scopesRequested",W$(t)),...ln("serverIcons",V$({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...ln("connectUrl",p),...ln("updatedAt",J$({connectionStatus:d,isUserOwned:u})),...ln("expiresAt",e.connection?.expiresAt)}}o(X$,"buildSetupRequirement");function QS(e){let t=yt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(QS,"requireVirtualServer");async function jp(e){let t=QS(e.transaction.virtualServerId),r=kr(e.transaction.principal.subjectId),n=[],a=new Map;for(let u of t.connections)As(u.authMode)==="user"&&(a.set(u,n.length),n.push({owner:r,upstreamServerId:u.upstreamServerId,authProfileId:u.authProfileId}));let i=await V().upstreamConnectionRepository.batchGet(n),s=[];for(let u of t.connections){let d=As(u.authMode)==="user",p=a.get(u);s.push(await X$({connection:d&&p!==void 0?i[p]:void 0,registeredConnection:u,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(jp,"requirementsForSetup");function Q$(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(Q$,"readVirtualServerDisplayName");async function Hp(e){let t=e.repository??V().downstreamOAuthRepository,r=QS(e.transaction.virtualServerId),n=Q$({virtualServer:r}),a=await t.getDcrClient(e.transaction.clientId),i={gatewayOrigin:de(e.requestUrl),virtualServerDisplayName:n,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=r.serverInfo?.title;return s!==void 0&&s!==n&&(i.virtualServerDescription=s),i}o(Hp,"consentContext");function ev(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(ev,"hasUnresolvedUserUpstream");var eD=["mcp_user"],tD="dev-browser-user",rD=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/mcp/{virtualServerId} or add resource={protected resource URI from protected-resource metadata}."].join(" "),nD=c.object({response_type:c.literal("code"),client_id:c.string().min(1),redirect_uri:c.string().min(1),resource:c.url(),code_challenge:c.string().min(43),code_challenge_method:Hn,state:c.string().min(1).optional(),scope:c.literal(ve).default(ve)}),oD=c.enum(["continue","approve","cancel"]).default("continue"),aD=c.object({state:c.string().min(1),decision:oD}),iD=c.object({state:c.string().min(1),apiKey:c.string().min(1)}),pn=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function tv(e){return typeof e=="string"&&e.length>0?e:void 0}o(tv,"readQueryString");function sD(e,t){let r=tv(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new D("invalid_target",rD)}let n=Qr(t,e.url);if(r===void 0||r===n)return n;throw new D("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(sD,"requireAuthorizeResource");async function cD(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Ys(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=RS(e);return{principal:i,setCookie:await $a({principal:i,requestUrl:e.url,virtualServerId:t})}}o(cD,"resolveBrowserPrincipal");async function uD(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Ys(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(uD,"requireSetupPrincipal");async function rv(e){let t=await jp({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await Hp({transaction:e.transaction,requestUrl:e.requestUrl,...e.repository===void 0?{}:{repository:e.repository}}),n={kind:"setup_page",html:qp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(rv,"renderSetup");function dD(e){return typeof e.decideAuthorizationSetup=="function"}o(dD,"usesRuntimeHttpAuthorizationOperations");function lD(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new D("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(lD,"toAuthorizationTransactionClient");async function Gp(e,t={}){let r=nD.parse({...e.query,resource:sD(e,t.virtualServerId),state:tv(e.query.state)}),n=dn(r.scope);ao(r.redirect_uri);let a=V().downstreamOAuthRepository,i=new Date,s=ye.parse(r.client_id),u=dD(a)&&s.startsWith("dcr:")?void 0:await qa(a,r.client_id,i);u!==void 0&&rc(u,r.redirect_uri);let d=u===void 0,p=d?jt(e.url,r.resource):void 0;try{let l=p??jt(e.url,r.resource),m=lD(u);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:s,virtualServerId:l.virtualServerId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved");let f={clientId:u?.clientId??s,...m===void 0?{}:{client:m},redirectUri:r.redirect_uri,resource:r.resource,virtualServerId:l.virtualServerId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:_,setCookie:w}=await cD(e,l.virtualServerId,t.context);if(!_){let S=await qS({transaction:f,requestUrl:e.url,now:i,repository:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:s,virtualServerId:l.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let v={kind:"redirect",location:S.browserLoginUrl};return w!==void 0&&(v.setCookie=w),v}let y=await LS({transaction:f,principal:_,now:i,repository:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:s,virtualServerId:l.virtualServerId,subjectId:_.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),rv({transaction:y.transaction,csrfToken:y.csrfToken,requestUrl:e.url,repository:a,setCookie:w})}catch(l){throw d?l:pD({redirectUri:r.redirect_uri,clientState:r.state,cause:l})}}o(Gp,"authorizeDownstreamClient");function pD(e){if(e.cause instanceof pn)return e.cause;let t=mD(e.cause);return t?new pn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(pD,"toDownstreamAuthorizeRedirectError");function mD(e){if(e instanceof D)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof c.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(mD,"mapToOAuthRedirectError");async function nv(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let l=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...l===void 0?{}:{idpErrorDescription:l},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",l??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await tc(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await CS(i),u=V().downstreamOAuthRepository,d=await Up({browserLoginStateToken:n,principal:s,repository:u}),p=await rv({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,repository:u});return p.setCookie=await $a({principal:s,requestUrl:e.url,virtualServerId:d.transaction.virtualServerId}),p}o(nv,"completeBrowserLoginCallback");async function ov(e){let t=Ee(),r=new URL(e.url);if(!Ve(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",de(e.url)),i=new URL(de(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:ie.parse(tD),roles:eD};return{kind:"redirect",location:a,setCookie:await $a({principal:s,requestUrl:e.url})}}o(ov,"completeLocalDevBrowserLogin");async function av(e){let t=iD.parse(e.body),r=V().downstreamOAuthRepository,n=await jS({browserLoginStateToken:t.state,repository:r}),a=await bS({apiKey:t.apiKey,virtualServerId:n.virtualServerId}),i=await Up({browserLoginStateToken:t.state,principal:a,repository:r});await Nw({apiKey:t.apiKey,principal:a,virtualServerId:i.transaction.virtualServerId});let s=new URL("/oauth/setup",At(e.request.url));return s.searchParams.set("state",i.csrfToken),{kind:"redirect",location:s,setCookie:await $a({principal:a,requestUrl:e.request.url,virtualServerId:i.transaction.virtualServerId})}}o(av,"completeApiKeyBrowserLogin");function hD(e){let t=e.method==="POST"?e.body:e.query;return aD.parse(t)}o(hD,"readSetupContinueRequest");async function iv(e){let{state:t,decision:r}=hD({method:e.request.method,query:e.request.query,body:e.body}),n=V().downstreamOAuthRepository,a=new Date,i=await Np({csrfToken:t,now:a,repository:n}),s=await uD(e.request,i.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await FS({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n})};let u=await Ma({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n}),d=await jp({transaction:u,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||ev(d)){let p=await Hp({repository:n,transaction:u,requestUrl:e.request.url});return{kind:"setup_page",html:qp({state:t,virtualServerId:u.virtualServerId,upstreams:d,...p})}}return{kind:"redirect",location:await BS({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n})}}o(iv,"continueDownstreamAuthorizeSetup");ae();var fD=new Set(["authorization_code","refresh_token"]),gD=c.discriminatedUnion("grant_type",[c.object({grant_type:c.literal("authorization_code"),code:c.string().min(1),redirect_uri:c.string().min(1),client_id:c.string().min(1).optional(),code_verifier:ls,resource:c.url().optional(),scope:c.literal(ve).optional(),client_secret:c.string().min(1).optional()}),c.object({grant_type:c.literal("refresh_token"),refresh_token:c.string().min(1),client_id:c.string().min(1).optional(),resource:c.url().optional(),scope:c.literal(ve).optional(),client_secret:c.string().min(1).optional()})]);function _D(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!fD.has(t)))throw new D("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(_D,"assertSupportedGrantType");var yD=c.object({token:c.string().min(1),client_id:c.string().min(1).optional(),token_type_hint:c.string().optional(),client_secret:c.string().min(1).optional()});function cv(){return Ee().gateway.accessTokenTtlSeconds}o(cv,"readAccessTokenTtlSeconds");function uv(){return Ee().gateway.refreshTokenTtlSeconds}o(uv,"readRefreshTokenTtlSeconds");async function sv(e){if(!e.client.hashedClientSecret||!e.clientSecret||e.clientSecretSource!==e.requiredSource)throw new D("invalid_client",e.missingMessage);if(!await l_({value:e.clientSecret,expectedHash:e.client.hashedClientSecret}))throw new D("invalid_client","Client authentication failed.")}o(sv,"requireClientSecretAuthentication");async function dv(e){switch(e.client.metadata.token_endpoint_auth_method){case"none":if(e.clientSecret)throw new D("invalid_request","Public clients must not authenticate with client_secret.");return;case"client_secret_basic":await sv({...e,requiredSource:"basic",missingMessage:"Client authentication with HTTP Basic is required."});return;case"client_secret_post":await sv({...e,requiredSource:"post",missingMessage:"Client authentication with client_secret_post is required."});return;case"private_key_jwt":throw new D("invalid_client","private_key_jwt client authentication is not supported.")}}o(dv,"requireClientAuthentication");function Bp(e,t){let r=cv(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:z(Tt(e,a)),expiresIn:a}}o(Bp,"calculateAccessTokenExpiresAt");async function wD(e){let t=nt(),r=await ee(t),n=Bp(e.now,e.grant.expiresAt);return await e.repository.saveAccessToken({tokenHash:r,grantId:e.grant.id,clientId:e.grant.clientId,resource:e.grant.resource,virtualServerId:e.grant.virtualServerId,subjectId:e.grant.subjectId,scope:e.grant.scope,roles:e.grant.roles,createdAt:z(e.now),expiresAt:n.expiresAt}),{accessToken:t,expiresIn:n.expiresIn}}o(wD,"issueOpaqueAccessToken");function lv(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new D("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new D("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new D("invalid_client","Malformed HTTP Basic client authentication.")}}o(lv,"readBasicClientSecret");function pv(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new D("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new D("invalid_client","Client authentication or client_id is required.");return t}o(pv,"resolveAuthenticatedClientId");function mv(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new D("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(mv,"resolveClientSecretInput");function hv(e){return typeof e.exchangeAuthorizationCodeWithClientAuth=="function"&&typeof e.refreshTokenWithClientAuth=="function"&&typeof e.revokeOAuthTokenWithClientAuth=="function"}o(hv,"usesRuntimeHttpTokenOperations");async function fv(e){let t=ye.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await ee(e.clientSecret)}}o(fv,"buildRuntimeHttpClientAuth");async function gv(e){_D(e.body);let t=gD.parse(e.body),r=lv(e.authorizationHeader),n=pv({basicClientId:r.clientId,bodyClientId:t.client_id}),a=V().downstreamOAuthRepository,i=new Date,s=mv({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});if(hv(a))return SD({parsed:t,clientId:n,clientSecretInput:s,now:i,repository:a,requestUrl:e.requestUrl});let u=await qa(a,n,i);if(await dv({client:u,...s}),t.grant_type==="authorization_code"){ao(t.redirect_uri),rc(u,t.redirect_uri),dn(t.scope),t.resource!==void 0&&jt(e.requestUrl??t.resource,t.resource);let w=nt(),y=nt(),S=z(Tt(i,uv())),v=Bp(i,S),R=await a.exchangeAuthorizationCode({codeHash:await ee(t.code),clientId:u.clientId,redirectUri:t.redirect_uri,...t.resource===void 0?{}:{resource:t.resource},codeChallenge:await Rl(t.code_verifier),currentRefreshTokenHash:await ee(w),accessTokenHash:await ee(y),now:i,grantExpiresAt:S,accessTokenExpiresAt:v.expiresAt});if(R.kind==="resource_mismatch")throw new D("invalid_target","Token request resource must match the authorization code resource.");if(R.kind!=="exchanged")throw new D("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context?.log.info({event:"oauth_token_issued",grantType:"authorization_code",clientId:u.clientId,scope:R.grant.scope,resource:R.grant.resource,expiresInSeconds:v.expiresIn},"OAuth access token issued (authorization_code grant)"),{access_token:y,token_type:"Bearer",expires_in:v.expiresIn,refresh_token:w,scope:R.grant.scope,resource:R.grant.resource}}dn(t.scope);let d=await ee(t.refresh_token);t.resource!==void 0&&jt(e.requestUrl??t.resource,t.resource);let p=nt(),l=await ee(p),m=await a.rotateRefreshToken({currentTokenHash:d,nextTokenHash:l,clientId:u.clientId,...t.resource===void 0?{}:{resource:t.resource},now:i});if(m.kind==="resource_mismatch")throw new D("invalid_target","Token request resource must match the refresh token grant resource.");if(m.kind!=="rotated")throw new D("invalid_grant","Refresh token is invalid, expired, or revoked.");let f=m.grant;if(f.revokedAt||f.clientId!==u.clientId)throw new D("invalid_grant","Refresh token grant is invalid or revoked.");jt(e.requestUrl??f.resource,f.resource);let _=await wD({repository:a,grant:f,now:i});return e.context?.log.info({event:"oauth_token_refresh_rotated",grantType:"refresh_token",clientId:u.clientId,scope:f.scope,resource:f.resource,expiresInSeconds:_.expiresIn},"OAuth refresh token rotated and access token issued"),{access_token:_.accessToken,token_type:"Bearer",expires_in:_.expiresIn,refresh_token:p,scope:f.scope,resource:f.resource}}o(gv,"exchangeDownstreamToken");async function SD(e){let t=await fv({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){ao(e.parsed.redirect_uri),dn(e.parsed.scope),e.parsed.resource!==void 0&&jt(e.requestUrl??e.parsed.resource,e.parsed.resource);let u=nt(),d=nt(),p=z(Tt(e.now,uv())),l=Bp(e.now,p),m=await e.repository.exchangeAuthorizationCodeWithClientAuth({clientAuth:t,codeHash:await ee(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Rl(e.parsed.code_verifier),currentRefreshTokenHash:await ee(u),accessTokenHash:await ee(d),grantExpiresAt:p,accessTokenExpiresAt:l.expiresAt,now:z(e.now)});if(m.kind==="invalid_client")throw new D("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new D("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new D("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return{access_token:d,token_type:"Bearer",expires_in:l.expiresIn,refresh_token:u,scope:m.grant.scope,resource:m.grant.resource}}dn(e.parsed.scope),e.parsed.resource!==void 0&&jt(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=nt(),n=nt(),a=z(Tt(e.now,cv())),i=await e.repository.refreshTokenWithClientAuth({clientAuth:t,currentRefreshTokenHash:await ee(e.parsed.refresh_token),nextRefreshTokenHash:await ee(r),accessTokenHash:await ee(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:z(e.now)});if(i.kind==="invalid_client")throw new D("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new D("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new D("invalid_grant","Refresh token is invalid, expired, or revoked.");jt(e.requestUrl??i.grant.resource,i.grant.resource);let s=i.accessToken.expiresAt;return{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(SD,"exchangeDownstreamTokenWithRuntimeHttp");async function _v(e){let t=yD.parse(e.body),r=lv(e.authorizationHeader),n=pv({basicClientId:r.clientId,bodyClientId:t.client_id}),a=V().downstreamOAuthRepository,i=mv({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});if(hv(a)){let d=new Date;if((await a.revokeOAuthTokenWithClientAuth({clientAuth:await fv({clientId:n,...i}),tokenHash:await ee(t.token),now:z(d)})).kind==="invalid_client")throw new D("invalid_client","Client authentication failed.");return}let s=await qa(a,n,new Date);await dv({client:s,...i});let u=await ee(t.token);await a.revokeOAuthToken({tokenHash:u,clientId:s.clientId,now:new Date}),e.context?.log.info({event:"oauth_token_revoked",clientId:s.clientId,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed")}o(_v,"revokeDownstreamToken");var vD=64*1024,RD=16*1024,bD="text/html; charset=utf-8";function CD(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(CD,"formDataToObject");async function ID(e){return lS(e,{maxBytes:vD,label:"Request body"})}o(ID,"readJsonBody");async function ac(e){return CD(await Js(e,{maxBytes:RD,label:"Request body"}))}o(ac,"readFormBody");async function ic(e,t,r){let n=_e(r),a=r instanceof c.ZodError?yv(r):r instanceof Error?r.message:void 0,i={code:n??"invalid_request"};return a!==void 0&&(i.detail=a),_t(e,t,i)}o(ic,"handleProblem");function La(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(La,"oauthErrorResponse");function TD(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(TD,"readOAuthProtocolHeaders");function AD(e,t){let r=rt("internal_server_error");return La({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:TD(e,t)})}o(AD,"oauthProtocolErrorResponse");function kD(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(kD,"readZodOAuthErrorCode");function ED(e){let t={error:kD(e)},r=yv(e);return r!==void 0&&(t.errorDescription=r),La(t)}o(ED,"oauthZodErrorResponse");function xD(e){let t=_e(e);if(t===void 0)return;let r=rt(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:OD(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,La(n)}o(xD,"oauthGatewayProblemResponse");function PD(){let t={error:"server_error",status:500,errorDescription:rt("internal_server_error").publicDetail};return La(t)}o(PD,"oauthFallbackErrorResponse");function OD(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(OD,"readOAuthStatus");function io(e,t={}){return e instanceof pn?UD(e):e instanceof D?AD(e,t):e instanceof c.ZodError?ED(e):xD(e)??PD()}o(io,"oauthProblemResponse");function Ht(e,t,r){let n={event:t},a=!1;if(r instanceof D)n.oauthError=r.errorCode,n.status=r.status,ze(n,"error",r);else if(r instanceof pn)n.oauthError=r.errorCode,ze(n,"error",r);else if(r instanceof c.ZodError){n.code="invalid_request",ze(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=_e(r);if(i!==void 0){let s=rt(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",ze(n,"error",r)}else a=!0,ze(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Ht,"logUnexpectedOAuthHandlerError");function UD(e){let t;try{t=new URL(e.redirectUri)}catch{return La({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(UD,"downstreamAuthorizeRedirectErrorResponse");function yv(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(yv,"formatZodErrorDetail");function ND(e,t){let r={event:"browser_login_callback_failed",code:_e(t)??"invalid_request"};ze(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(ND,"logBrowserLoginCallbackFailure");function Fp(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}o(Fp,"redirectResultResponse");function sc(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":bD,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Fp(e)}o(sc,"authorizeResultResponse");async function wv(e,t){try{return Response.json(Sl(e.url))}catch(r){return Ht(t,"oauth_authorization_server_metadata_failed",r),ic(e,t,r)}}o(wv,"authorizationServerMetadataHandler");async function Sv(e,t){try{let r=Se.parse(e.params.virtualServerId),n=oa(r);return Response.json(s_({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Ht(t,"oauth_authorization_server_metadata_failed",r),ic(e,t,r)}}o(Sv,"scopedAuthorizationServerMetadataHandler");async function vv(e,t){try{let r=await KS(await ID(e)),n=r;return t.log.info({event:"oauth_dcr_client_registered",clientId:typeof n.client_id=="string"?n.client_id:void 0,clientName:typeof n.client_name=="string"?n.client_name:void 0,redirectUriCount:Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,tokenEndpointAuthMethod:typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0},"OAuth Dynamic Client Registration completed"),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Ht(t,"oauth_register_failed",r),io(r)}}o(vv,"registerHandler");async function Rv(e,t){try{return sc(await Gp(e,{context:t}))}catch(r){return Ht(t,"oauth_authorize_failed",r),io(r,{includeInvalidClientChallenge:!1})}}o(Rv,"authorizeHandler");async function bv(e,t){try{let r=Se.parse(e.params.virtualServerId),n=oa(r);return sc(await Gp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Ht(t,"oauth_authorize_scoped_failed",r),io(r,{includeInvalidClientChallenge:!1})}}o(bv,"scopedAuthorizeHandler");async function Cv(e,t){try{let r=await nv(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),sc(r)}catch(r){return ND(t,r),ic(e,t,r)}}o(Cv,"callbackHandler");async function Iv(e,t){try{return Fp(await ov(e))}catch(r){return Ht(t,"oauth_dev_login_failed",r),io(r)}}o(Iv,"devLoginHandler");async function Tv(e,t){try{if(e.method==="GET"){let r=typeof e.query.state=="string"?e.query.state:void 0;return r?fS(r):kp(400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Fp(await av({request:e,body:await ac(e)}))}catch(r){return Ht(t,"oauth_api_key_login_failed",r),kp()}}o(Tv,"apiKeyLoginHandler");async function Av(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await iv({request:e,body:e.method==="POST"?await ac(e):void 0,context:t});return sc(r)}catch(r){return Ht(t,"oauth_setup_failed",r),ic(e,t,r)}}o(Av,"setupHandler");async function kv(e,t){try{return Response.json(await gv({body:await ac(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Ht(t,"oauth_token_failed",r),io(r)}}o(kv,"tokenHandler");async function Ev(e,t){try{return await _v({body:await ac(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Ht(t,"oauth_revoke_failed",r),io(r)}}o(Ev,"revokeHandler");var zD={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},xv=new Vt("upstream-request");function $D(e){let t=xv.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o($D,"readUpstreamRequestContext");function DD(e,t){return t.some(r=>r===e)}o(DD,"requestContextMatchesKind");function MD(e){return typeof e=="string"?[e]:e}o(MD,"toExpectedKinds");function mn(e,t){xv.set(e,t)}o(mn,"setUpstreamRequestContext");function hn(e,t){let r=$D(e),n=MD(t);if(!DD(r.kind,n)){let a=zD[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(hn,"requireUpstreamRequestContext");var qD="text/html; charset=utf-8",LD="none";function Pv(e){return N`<!doctype html><html><head><title>${e.title}</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body data-gateway-error-code="${e.code??LD}"><main><h1>${e.title}</h1><p>${e.body}</p></main></body></html>`}o(Pv,"browserResultHtml");function Ov(e,t=200){return new Response(sr(e),{status:t,headers:{"content-type":qD,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Ov,"browserResultResponse");function cc(e){return Ov(Pv(e))}o(cc,"browserConnectionSuccessResponse");function so(e){let t=Ig(e);return Ov(Pv({title:t.title,body:t.body,code:e}),400)}o(so,"browserConnectionFailureResponse");var jD="text/html; charset=utf-8",HD=16*1024;function GD(e,t=200){return new Response(sr(e),{status:t,headers:{"content-type":jD,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(GD,"htmlResponse");function BD(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(BD,"safeRedirect");function FD(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(FD,"requireBrowserTicket");function VD(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(VD,"appPasswordTicketMatchesTarget");async function Uv(e){let t=FD(e.browserTicket),r=await Os(t);if(!VD(r,e))throw g("oauth_callback_mismatch","App password capture ticket did not match the requested upstream flow.");return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(Uv,"readAppPasswordTarget");function KD(e){let t=ep(e.upstreamServerId,e.authProfileId),r=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,n=t.kind==="basic_auth_app_password"?N`<label for="username">${t.usernameLabel}</label><input id="username" name="username" required autocomplete="username"><label for="appPassword">${t.passwordLabel}</label><input id="appPassword" name="appPassword" type="password" required autocomplete="current-password">`:N`<label for="token">${t.label}</label><input id="token" name="token" type="password" required autocomplete="off">`;return GD(N`<!doctype html><html><head><title>Connect upstream</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;margin:0;padding:32px;background:#f8fafc;color:#0f172a}main{max-width:440px;margin:0 auto;background:white;border:1px solid #dbe3ee;border-radius:8px;padding:24px;box-shadow:0 1px 2px rgba(15,23,42,.06)}label{display:block;font-size:14px;font-weight:600;margin:16px 0 6px}input{box-sizing:border-box;width:100%;border:1px solid #b8c3d4;border-radius:6px;padding:10px 12px;font:inherit}button{margin-top:20px;border:0;border-radius:6px;background:#0f172a;color:white;padding:10px 14px;font:inherit;font-weight:600;cursor:pointer}p{color:#475569;line-height:1.5}</style></head><body><main><h1>Connect upstream</h1><p>Enter the per-user credential for this approved upstream. The gateway stores it encrypted and keeps it out of MCP client configuration.</p><form method="post" action="${r}" autocomplete="off"><input type="hidden" name="browserTicket" value="${e.browserTicket}">${n}<button type="submit">Connect</button></form></main></body></html>`)}o(KD,"renderCaptureForm");function uc(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw g("invalid_request",`Missing form field: ${t}`);return r}o(uc,"readRequiredFormValue");function ZD(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(ZD,"readCaptureFormTargetInput");async function WD(e){return KD(await Uv(ZD(e)))}o(WD,"handleCaptureFormRequest");async function JD(e){let t=await Js(e.request,{maxBytes:HD,label:"App password request body"});return{form:t,target:await Uv({upstreamServerId:e.upstreamServerId,browserTicket:uc(t,"browserTicket")})}}o(JD,"readSubmittedAppPasswordTarget");async function YD(e){let t=Vn(e.target.ticket);if(await Us(e.target.ticket),ep(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Ns({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:uc(e.form,"token")});return}await Xy({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:uc(e.form,"username"),appPassword:uc(e.form,"appPassword")})}o(YD,"saveSubmittedAppPasswordCredential");function XD(e,t){return t.ticket.returnTo?BD(e,t.ticket.returnTo):cc({title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(XD,"appPasswordSuccessResponse");async function QD(e){let t=await JD({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await YD(t),XD(e.request.url,t.target)}o(QD,"handleAppPasswordSubmission");function eM(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(eM,"methodNotAllowedResponse");function tM(e){let t=_e(e);return so(Yi(t)?t:"oauth_state_invalid")}o(tM,"appPasswordFailureResponse");async function rM(e){switch(e.request.method){case"GET":return WD(e.appPasswordRequest);case"POST":return QD(e);default:return eM()}}o(rM,"handleAppPasswordMethod");async function Vp(e,t){let r=hn(t,"app_password");try{return await rM({request:e,appPasswordRequest:r})}catch(n){return tM(n)}}o(Vp,"appPasswordHandler");var nM=["callback_authorization_code","callback_provider_error","callback_invalid"];function oM(e){return"cause"in e?e.cause:void 0}o(oM,"readErrorCause");function aM(e){return e.stack?.split(`
1408
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(aM,"readFirstStackFrame");function Nv(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=aM(r))}o(Nv,"addErrorAttributes");function iM(e,t){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),ot(e,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),so("provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),so("oauth_state_invalid");case"callback_authorization_code":return t}}o(iM,"requireAuthorizationCallbackRequest");function sM(e,t){ot(e,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(sM,"emitCallbackReceivedAnalyticsEvent");function cM(e,t){ot(e,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(cM,"emitTokenExchangeSucceededAnalyticsEvent");function uM(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return cc({title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(uM,"buildSuccessfulCallbackResponse");function dM(e){let t={detail:e instanceof Error?e.message:void 0};return Nv(t,"error",e),e instanceof Error&&Nv(t,"cause",oM(e)),t}o(dM,"buildTokenExchangeFailureAttributes");function lM(e){ot(e.context,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:_e(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:dM(e.error)})}o(lM,"emitTokenExchangeFailedAnalyticsEvent");function pM(e){let t=_e(e);return so(Yi(t)?t:"upstream_token_exchange_failed")}o(pM,"tokenExchangeFailureResponse");async function Kp(e,t){let r=hn(t,nM),n=iM(t,r);if(n instanceof Response)return n;sM(t,n);try{let a=await $w({request:e,callbackRequest:n});return cM(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,virtualServerId:a.virtualServerId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),uM(e,a)}catch(a){let i={event:"upstream_oauth_token_exchange_failed",code:_e(a)??"upstream_token_exchange_failed",upstreamServerId:n.upstreamServerId};return ze(i,"error",a),t.log.warn(i,"Upstream OAuth token exchange failed; user shown connection-failure page"),lM({context:t,callbackRequest:n,error:a}),pM(a)}}o(Kp,"callbackHandler");function mM(e){let t=_e(e);return t==="unknown_upstream_server"?t:"not_found"}o(mM,"clientMetadataProblemCode");function hM(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(hM,"clientMetadataProblemDetail");async function zv(e,t){let r=hn(t,"connect"),n=await zw({request:e,connectRequest:r});if(ot(t,{eventType:J.MCP_GATEWAY_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:n.virtualServerId,upstreamServerTitle:n.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,virtualServerId:n.virtualServerId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(n.authUrl,302);let a=await Wn({requestUrl:e.url,owner:n.owner,initiatedBySubjectId:n.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,upstreamDisplayName:n.upstreamDisplayName,virtualServerId:n.virtualServerId,subject:"virtual server",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}o(zv,"connectHandler");async function $v(e,t){let r=hn(t,"client_metadata");try{let n=Sw(e.url),a=vw(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=mM(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),_t(e,t,{code:a,detail:hM(n)})}}o($v,"oauthClientMetadataHandler");function cr(e){if(typeof e=="string"&&e.length!==0)return e}o(cr,"readOptionalQueryString");function fM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(fM,"requirePathString");function Dv(e){let t=cr(e);return t?Se.parse(t):void 0}o(Dv,"readOptionalVirtualServerId");function gM(e,t){let r=cr(e);return r?De.parse(r):Ln(t,"user_oauth")}o(gM,"readOptionalAuthProfileId");function _M(e){let t=Dv(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(_M,"readRequiredVirtualServerId");function yM(e){let t=cr(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(yM,"readOptionalBrowserTicket");function wM(e){let t=vs(cr(e));return t===void 0?{}:{returnTo:t}}o(wM,"readOptionalReturnTo");function SM(e){let t=Dv(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(SM,"readOptionalVirtualServerIdContext");function vM(e){let t=cr(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(vM,"readOptionalProviderErrorDescription");function RM(e){let t=Mt(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(RM,"requireConnectableRouteAuth");function bM(e,t,r,n){let a=Ws(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(bM,"buildConnectContextForPrincipal");function CM(e,t,r){let n=Vn(t),a=Mt(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(CM,"buildConnectContextForTicket");async function IM(e,t){let r=RM(sS(t,_M(e.query.virtualServerId))),n=e.query.redirect==="true",a=cr(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=Bn(e.user,e.url);return bM(r,s,n,wM(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await Os(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await Us(i),CM(r,i,n)}o(IM,"resolveConnectContext");async function TM(e,t,r){let n=$e.parse(fM(e,"connection"));switch(r){case"connect":mn(t,await IM(e,n));return;case"app_password":mn(t,{kind:"app_password",upstreamServerId:n,...SM(e),...yM(e)});return;case"callback":{let a=cr(e.query.error);if(a){mn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...vM(e)});return}let i=cr(e.query.code),s=cr(e.query.state);if(i&&s){mn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}mn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":mn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:gM(e.query.authProfileId,n)});return}}o(TM,"resolveUpstreamRequestInbound");async function AM(e,t,r){try{await TM(e,t,r);return}catch(n){let a=_e(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return _t(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(AM,"applyUpstreamRequestContext");function ja(e,t){return o(async(n,a)=>{let i=await AM(n,a,e);return i||t(n,a)},"wrapped")}o(ja,"withUpstreamRequestContext");var kM={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function EM(){return new Response(null,{status:204,headers:kM})}o(EM,"buildWellKnownPreflightResponse");function xM(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(xM,"withWellKnownCorsHeaders");function Zp(e){return async(t,r)=>t.method==="OPTIONS"?EM():xM(await e(t,r))}o(Zp,"wrapWellKnownHandler");var PM=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Zp(wv)},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Zp(Sv)},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Zp(c_)},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:vv},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:Rv},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:bv},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:Cv},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:Iv},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:Tv},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:Av},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:kv},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:Ev},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ja("client_metadata",$v)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ja("connect",zv)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ja("callback",Kp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:ja("app_password",Vp)}];function Mv(e){if(e)return e.find(t=>rs(t.policyType))}o(Mv,"findMcpOAuthPolicy");function qv(e){return Mv(e)!==void 0}o(qv,"shouldRegisterMcpGatewayInternalRoutes");function OM(e){let t=Xd(e.policyType);if(!t){let r=Qd();throw new Ft(`MCP gateway: unknown MCP authorization policy type '${String(e.policyType)}'. Registered policy types: ${r.length>0?r.join(", "):"<none>"}.`)}try{return t.getConfig(e.handler.options)}catch(r){throw r instanceof c.ZodError?new Ft(UM(e.name??e.policyType,r),{cause:r}):r}}o(OM,"resolveOAuthConfigFromPolicy");function UM(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
46
+ - `)}`,new Error(P)}let B=`${c}/$ref`,E=fe(e,z,r,n,a,i,s,B,d);if(E.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:B,error:"A subschema had errors."},...E.errors),r==="4"||r==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(_)){let j=_.length,z=!1;for(let B=0;B<j;B++)if(l===_[B]||_[B]==="integer"&&l==="number"&&e%1===0&&e===e){z=!0;break}z||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_.join('", "')}".`})}else _==="integer"?(l!=="number"||e%1||e!==e)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`}):_!==void 0&&l!==_&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`});if(S!==void 0&&(l==="object"||l==="array"?$n(e,S)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`}):e!==S&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`})),w!==void 0&&(l==="object"||l==="array"?w.some(j=>$n(e,j))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(j=>e===j)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),b!==void 0){let j=`${c}/not`;fe(e,b,r,n,a,i,s,j).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:j,error:'Instance matched "not" schema.'})}let Ma=[];if(R!==void 0){let j=`${c}/anyOf`,z=T.length,B=!1;for(let E=0;E<R.length;E++){let P=R[E],H=Object.create(d),D=fe(e,P,r,n,a,y===!0?i:null,s,`${j}/${E}`,H);T.push(...D.errors),B=B||D.valid,D.valid&&Ma.push(H)}B?T.length=z:T.splice(z,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:j,error:"Instance does not match any subschemas."})}if(q!==void 0){let j=`${c}/allOf`,z=T.length,B=!0;for(let E=0;E<q.length;E++){let P=q[E],H=Object.create(d),D=fe(e,P,r,n,a,y===!0?i:null,s,`${j}/${E}`,H);T.push(...D.errors),B=B&&D.valid,D.valid&&Ma.push(H)}B?T.length=z:T.splice(z,0,{instanceLocation:s,keyword:"allOf",keywordLocation:j,error:"Instance does not match every subschema."})}if(N!==void 0){let j=`${c}/oneOf`,z=T.length,B=N.filter((E,P)=>{let H=Object.create(d),D=fe(e,E,r,n,a,y===!0?i:null,s,`${j}/${P}`,H);return T.push(...D.errors),D.valid&&Ma.push(H),D.valid}).length;B===1?T.length=z:T.splice(z,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:j,error:`Instance does not match exactly one subschema (${B} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...Ma),qe!==void 0){let j=`${c}/if`;if(fe(e,qe,r,n,a,i,s,j,d).valid){if(it!==void 0){let B=fe(e,it,r,n,a,i,s,`${c}/then`,d);B.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "then" schema.'},...B.errors)}}else if(dn!==void 0){let B=fe(e,dn,r,n,a,i,s,`${c}/else`,d);B.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "else" schema.'},...B.errors)}}if(l==="object"){if(v!==void 0)for(let E of v)E in e||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${E}".`});let j=Object.keys(e);if(ao!==void 0&&j.length<ao&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${ao} properties.`}),Zs!==void 0&&j.length>Zs&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${Zs} properties.`}),kp!==void 0){let E=`${c}/propertyNames`;for(let P in e){let H=`${s}/${at(P)}`,D=fe(P,kp,r,n,a,i,H,E);D.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:E,error:`Property name "${P}" does not match schema.`},...D.errors)}}if(Ks!==void 0){let E=`${c}/dependantRequired`;for(let P in Ks)if(P in e){let H=Ks[P];for(let D of H)D in e||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:E,error:`Instance has "${P}" but does not have "${D}".`})}}if(Ws!==void 0)for(let E in Ws){let P=`${c}/dependentSchemas`;if(E in e){let H=fe(e,Ws[E],r,n,a,i,s,`${P}/${at(E)}`,d);H.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${E}" but does not match dependant schema.`},...H.errors)}}if(Js!==void 0){let E=`${c}/dependencies`;for(let P in Js)if(P in e){let H=Js[P];if(Array.isArray(H))for(let D of H)D in e||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not have "${D}".`});else{let D=fe(e,H,r,n,a,i,s,`${E}/${at(P)}`);D.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not match dependant schema.`},...D.errors)}}}let z=Object.create(null),B=!1;if(qt!==void 0){let E=`${c}/properties`;for(let P in qt){if(!(P in e))continue;let H=`${s}/${at(P)}`,D=fe(e[P],qt[P],r,n,a,i,H,`${E}/${at(P)}`);if(D.valid)d[P]=z[P]=!0;else if(B=a,T.push({instanceLocation:s,keyword:"properties",keywordLocation:E,error:`Property "${P}" does not match schema.`},...D.errors),B)break}}if(!B&&Er!==void 0){let E=`${c}/patternProperties`;for(let P in Er){let H=new RegExp(P,"u"),D=Er[P];for(let Ze in e){if(!H.test(Ze))continue;let zp=`${s}/${at(Ze)}`,Mp=fe(e[Ze],D,r,n,a,i,zp,`${E}/${at(P)}`);Mp.valid?d[Ze]=z[Ze]=!0:(B=a,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:E,error:`Property "${Ze}" matches pattern "${P}" but does not match associated schema.`},...Mp.errors))}}}if(!B&&no!==void 0){let E=`${c}/additionalProperties`;for(let P in e){if(z[P])continue;let H=`${s}/${at(P)}`,D=fe(e[P],no,r,n,a,i,H,E);D.valid?d[P]=!0:(B=a,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:E,error:`Property "${P}" does not match additional properties schema.`},...D.errors))}}else if(!B&&oo!==void 0){let E=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let H=`${s}/${at(P)}`,D=fe(e[P],oo,r,n,a,i,H,E);D.valid?d[P]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:E,error:`Property "${P}" does not match unevaluated properties schema.`},...D.errors)}}}else if(l==="array"){Xs!==void 0&&e.length>Xs&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${Xs}).`}),Qs!==void 0&&e.length<Qs&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${Qs}).`});let j=e.length,z=0,B=!1;if(Ys!==void 0){let E=`${c}/prefixItems`,P=Math.min(Ys.length,j);for(;z<P;z++){let H=fe(e[z],Ys[z],r,n,a,i,`${s}/${z}`,`${E}/${z}`);if(d[z]=!0,!H.valid&&(B=a,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:E,error:"Items did not match schema."},...H.errors),B))break}}if(io!==void 0){let E=`${c}/items`;if(Array.isArray(io)){let P=Math.min(io.length,j);for(;z<P;z++){let H=fe(e[z],io[z],r,n,a,i,`${s}/${z}`,`${E}/${z}`);if(d[z]=!0,!H.valid&&(B=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...H.errors),B))break}}else for(;z<j;z++){let P=fe(e[z],io,r,n,a,i,`${s}/${z}`,E);if(d[z]=!0,!P.valid&&(B=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...P.errors),B))break}if(!B&&Ep!==void 0){let P=`${c}/additionalItems`;for(;z<j;z++){let H=fe(e[z],Ep,r,n,a,i,`${s}/${z}`,P);d[z]=!0,H.valid||(B=a,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...H.errors))}}}if(Op!==void 0)if(j===0&&Nt===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Nt!==void 0&&j<Nt)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${j}) than minContains (${Nt}).`});else{let E=`${c}/contains`,P=T.length,H=0;for(let D=0;D<j;D++){let Ze=fe(e[D],Op,r,n,a,i,`${s}/${D}`,E);Ze.valid?(d[D]=!0,H++):T.push(...Ze.errors)}H>=(Nt||0)&&(T.length=P),Nt===void 0&&Ea===void 0&&H===0?T.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:E,error:"Array does not contain item matching schema."}):Nt!==void 0&&H<Nt?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${Nt} items matching schema. Only ${H} items were found.`}):Ea!==void 0&&H>Ea&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Ea} items matching schema. ${H} items were found.`})}if(!B&&Up!==void 0){let E=`${c}/unevaluatedItems`;for(z;z<j;z++){if(d[z])continue;let P=fe(e[z],Up,r,n,a,i,`${s}/${z}`,E);d[z]=!0,P.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:E,error:"Items did not match unevaluated items schema."},...P.errors)}}if(vv)for(let E=0;E<j;E++){let P=e[E],H=typeof P=="object"&&P!==null;for(let D=0;D<j;D++){if(E===D)continue;let Ze=e[D];(P===Ze||H&&(typeof Ze=="object"&&Ze!==null)&&$n(P,Ze))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${E} and ${D}.`}),E=Number.MAX_SAFE_INTEGER,D=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Ur!==void 0&&(so===!0&&e<=Ur||e<Ur)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${so?"or equal to ":""} ${Ur}.`}),Or!==void 0&&(co===!0&&e>=Or||e>Or)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${co?"or equal to ":""} ${Or}.`})):(Ur!==void 0&&e<Ur&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Ur}.`}),Or!==void 0&&e>Or&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Or}.`}),so!==void 0&&e<=so&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${so}.`}),co!==void 0&&e>=co&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${co}.`})),Ua!==void 0){let j=e%Ua;Math.abs(0-j)>=11920929e-14&&Math.abs(Ua-j)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Ua}.`})}}else if(l==="string"){let j=Oa===void 0&&$a===void 0?0:ng(e);Oa!==void 0&&j<Oa&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${j} < ${Oa}).`}),$a!==void 0&&j>$a&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${j} > ${$a}).`}),$p!==void 0&&!new RegExp($p,"u").test(e)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),ir!==void 0&&Td[ir]&&!Td[ir](e)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${ir}".`})}return{valid:T.length===0,errors:T}}o(fe,"validate");var Di=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Wt(t)}validate(t){return fe(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Wt(t,this.lookup)}};var zn=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new Di(t,this.draft,this.shortcircuit);return n=>{let a=r.validate(n);return a.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:a.errors.map(i=>`${i.instanceLocation}: ${i.error}`).join("; ")}}}};function kd(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(kd,"truncate");function og(e){return"cause"in e?e.cause:void 0}o(og,"readCause");function Oe(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=kd(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=kd(r.message);let n=og(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=kd(n.message),n=og(n)}}o(Oe,"addErrorLogFields");function mt(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(mt,"safeHost");function ag(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(ag,"setLogProperties");function Ed(e,t){ag(e,{subjectId:t.subjectId})}o(Ed,"applyGatewayPrincipalLogProperties");function ig(e,t){ag(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(ig,"applyGatewayRouteLogProperties");var Mn={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},sg={...Mn.runtime,...Mn.config,...Mn.downstream_auth,...Mn.downstream_oauth,...Mn.upstream_auth,...Mn.upstream_mcp};function Qo(e){return typeof e=="string"&&Object.hasOwn(sg,e)}o(Qo,"isGatewayProblemCode");function Hi(e){return Qo(e)&&Qe(e).callbackFailure===!0}o(Hi,"isGatewayCallbackFailureCode");function Qe(e){return sg[e]}o(Qe,"readGatewayProblemDefinition");function Ud(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";default:return"internal_server_error"}}o(Ud,"readDefaultGatewayProblemCodeForStatus");var cg="gatewayCode";function ug(e){let t=Qe(e);return{title:t.title,body:t.publicDetail}}o(ug,"readGatewayCallbackFailureContent");function he(e){if(!(e instanceof qa))return;let t=e.extensionMembers?.[cg];return Qo(t)?t:void 0}o(he,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Qe(n.code),i=n.privateDetail??(Li(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=mT(n);return new qa({message:i,extensionMembers:{[cg]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function ft(e,t,r){let n=Qe(r.code),a=fT(r.code,r.detail),i=Li(r.code)?r.title??n.title:n.title,c={problem:{...uo.getProblemFromStatus(n.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:n.status,title:i,detail:a,code:r.code}};return r.headers!==void 0&&(c.additionalHeaders=r.headers),uo.format(c,e,t)}o(ft,"gatewayProblemResponse");function Li(e){return Qe(e).status<500}o(Li,"canExposeGatewayProblemDetail");function mT(e){return!e.privateDetail||Li(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(mT,"readRuntimeErrorCause");function fT(e,t){let r=Qe(e);return Li(e)&&t||r.publicDetail}o(fT,"readSafeGatewayProblemDetail");ie();var hT=["shared-oauth","user_oauth","static_secret","user-secret","shared-secret"],gT=["none","client_secret_basic","client_secret_post"],Xe=u.string().min(1).brand(),Pe=u.string().min(1).brand(),et=u.string().min(1).brand(),Ot=u.string().min(1).brand(),Bi=u.enum(hT),Od=u.enum(gT),Gi=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),$d=u.object({name:Gi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();var zd=new Map;function Vi(e){zd.set(e.policyType,e)}o(Vi,"registerMcpAuthorizationPolicy");function Md(e){if(e!==void 0)return zd.get(e)}o(Md,"getMcpAuthorizationPolicy");function Fi(e){return Md(e)!==void 0}o(Fi,"isRegisteredMcpAuthorizationPolicyType");function qd(){return[...zd.keys()]}o(qd,"listMcpAuthorizationPolicyTypes");ie();var pg=Xe,yT=u.object({mode:u.literal("auto")}).strict(),ST=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Od.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:u.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),mg=u.discriminatedUnion("mode",[yT,ST]),_T=mg.default({mode:"auto"}),Nd=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:_T}).strict(),dg=Nd.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),fg=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),wT=new Set([...fg,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),vT=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),bT=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:Gi,value:u.string().min(1)}).strict()).min(1)}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.headers.entries()){let i=a.name.toLowerCase();fg.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for static secret injection`,path:["headers",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate static secret header ${a.name}`,path:["headers",n,"name"]}),r.add(i)}}),jd=u.discriminatedUnion("kind",[vT,bT]),RT=u.object({kind:u.literal("basic_auth_app_password"),usernameLabel:u.string().min(1).default("Username"),passwordLabel:u.string().min(1).default("App password")}).strict(),CT=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Dd=u.discriminatedUnion("kind",[RT,CT]),Hd=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),IT=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:dg}).strict(),u.object({mode:u.literal("user_oauth"),oauth:dg}).strict(),u.object({mode:u.literal("static_secret"),secret:jd}).strict(),u.object({mode:u.literal("user-secret"),secret:Dd}).strict(),u.object({mode:u.literal("shared-secret"),secret:Hd}).strict()]),PT=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array($d).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();wT.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for native MCP transport request headers`,path:["requestHeaders",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate native MCP transport request header ${a.name}`,path:["requestHeaders",n,"name"]}),r.add(i)}}),YG=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:fn.optional(),authProfiles:u.record(et,IT),transport:PT}).strict().superRefine((e,t)=>{Object.keys(e.authProfiles).length===0&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one profile",path:["authProfiles"]})}),xT=u.object({"shared-oauth":Nd.optional(),user_oauth:Nd.optional(),static_secret:u.object({secret:jd}).strict().optional(),"user-secret":u.object({secret:Dd}).strict().optional(),"shared-secret":u.object({secret:Hd}).strict().optional()}).strict().superRefine((e,t)=>{Object.values(e).every(r=>r===void 0)&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one upstream auth profile"})}),lg=u.object({id:pg,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:fn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array($d).default([]),authProfiles:xT}).strict(),AT=u.object({name:Gi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),Zi={id:pg.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:fn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(AT).default([])},TT=u.discriminatedUnion("authMode",[u.object({...Zi,authMode:u.enum(["shared-oauth","user_oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:mg.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Od.optional()}).strict(),u.object({...Zi,authMode:u.literal("static_secret"),secret:jd}).strict(),u.object({...Zi,authMode:u.literal("user-secret"),secret:Dd}).strict(),u.object({...Zi,authMode:u.literal("shared-secret"),secret:Hd}).strict()]);function hg(e){throw g("internal_server_error",e)}o(hg,"throwGatewayConfigError");function kT(e){let t="mcp-upstream-";return e.startsWith(t)||hg(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),Xe.parse(e.slice(t.length))}o(kT,"inferUpstreamConnectionIdFromPolicyName");function ET(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(ET,"buildDefaultProtectedResourceMetadataUrl");function qn(e,t){return et.parse(`${e}:${t}`)}o(qn,"buildUpstreamAuthProfileId");function Ki(e,t){let r=lg.safeParse(e);if(r.success)return r.data;let n=TT.parse(e),a=n.id??(t===void 0?void 0:kT(t));a===void 0&&hg("Upstream policy options must include id when policy name is unavailable.");let i=n.requestHeaders.map(c=>({name:c.name,value:c.value,required:c.required})),s=(()=>{switch(n.authMode){case"shared-oauth":case"user_oauth":{let c=n.clientRegistration??(n.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:n.clientId,...n.clientSecret===void 0?{}:{clientSecret:n.clientSecret},...n.tokenEndpointAuthMethod===void 0?{}:{tokenEndpointAuthMethod:n.tokenEndpointAuthMethod}});return{[n.authMode]:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,clientRegistration:c}}}case"static_secret":case"user-secret":case"shared-secret":return{[n.authMode]:{secret:n.secret}}}})();return lg.parse({id:a,displayName:n.displayName,...n.summary===void 0?{}:{description:n.summary},...n.serverInfo===void 0?{}:{serverInfo:n.serverInfo},mcpUrl:n.mcpUrl,protectedResourceMetadataUrl:n.protectedResourceMetadataUrl??ET(n.mcpUrl),requestHeaders:i,authProfiles:s})}o(Ki,"parseUpstreamConnectionPolicyOptions");function gg(e){return e.mode==="shared-oauth"||e.mode==="user_oauth"}o(gg,"isUpstreamOAuthAuthConfig");ie();var UT=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),OT=u.looseObject({}),$T=u.looseObject({name:Ot,namespace:Ot.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:OT}),zT=u.looseObject({name:Ot,namespace:Ot.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),MT=u.looseObject({name:Ot,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),qT=u.enum(["openapi","upstream_mcp"]),NT=u.object({catalogSource:qT.default("openapi"),serverInfo:UT.optional(),tools:u.array($T).default([]),prompts:u.array(zT).default([]),resources:u.array(MT).default([])}).strict();function yg(e){return NT.parse(e??{})}o(yg,"parseVirtualServerRouteOptions");function Wi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Wi,"toMcpTool");function Ji(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ji,"toMcpPrompt");function Yi(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Yi,"toMcpResource");var jT="mcp-upstream-connection-inbound",Sg="/mcp/";function He(e){throw new jt(e)}o(He,"throwRegistryError");function _g(e){return e.policyType===jT}o(_g,"isUpstreamConnectionPolicy");function DT(e){return Fi(e.policyType)}o(DT,"isMcpOAuthInboundPolicy");function HT(e){e.startsWith(Sg)||He(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(Sg.length);return(!t||t.includes("/"))&&He(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),Pe.parse(t)}o(HT,"readVirtualServerIdFromPath");function LT(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&He(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&He(`Upstream policy ${e.policyName} does not declare an auth mode.`),Bi.parse(r)}o(LT,"readSingleAuthMode");function BT(e){let t=e.connection.authProfiles[e.authMode];t||He(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":case"user_oauth":{let n=t;return{mode:e.authMode,oauth:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,redirectPath:r,clientRegistration:n.clientRegistration}}}case"static_secret":return{mode:"static_secret",secret:t.secret};case"user-secret":return{mode:"user-secret",secret:t.secret};case"shared-secret":return{mode:"shared-secret",secret:t.secret}}}o(BT,"buildResolvedAuthConfig");function GT(e){let t=LT({policyName:e.policyName,connection:e.connection}),r=qn(e.connection.id,t),n=BT({connection:e.connection,authMode:t,authProfileId:r}),a={displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},authProfiles:{[r]:n},transport:{baseUrl:e.connection.mcpUrl,resourceMetadataUrl:e.connection.protectedResourceMetadataUrl,requestHeaders:e.connection.requestHeaders}};return{policyName:e.policyName,upstreamServerId:e.connection.id,config:a,authMode:t,authProfileId:r,authConfig:n}}o(GT,"buildRegisteredConnection");function VT(e){let t=new Map;for(let r of e)t.has(r.name)&&He(`Duplicate policy name ${r.name} in policies.json.`),t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}});return t}o(VT,"buildPolicyMap");function FT(e){let t=new Map,r=new Set;for(let n of e.values()){if(!_g(n))continue;let a=Ki(n.handler.options,n.name);r.has(a.id)&&He(`Duplicate upstream MCP connection id ${a.id} in policies.json.`),r.add(a.id);let i=GT({policyName:n.name,connection:a});t.set(n.name,i)}return t}o(FT,"buildConnectionsByPolicyName");function ZT(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(ZT,"readOperationId");function wg(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return Ot.parse(t)}catch{He(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(wg,"buildPublishedCapabilityName");function Bd(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||He(`MCP virtual server route ${e.routePath} declares capability ${e.capabilityName} for upstream policy ${e.authoredPolicyName}, but that policy is not bound to the route.`),e.authoredPolicyName;if(e.connections.length===1)return e.connections[0]?.policyName;He(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Bd,"readCapabilityUpstreamPolicy");function Ld(e){e.seen.has(e.key)&&He(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Ld,"assertUniqueCatalogKey");function KT(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=wg({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Bd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(KT,"normalizeCatalogTool");function WT(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=wg({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Bd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(WT,"normalizeCatalogPrompt");function JT(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Bd({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(JT,"normalizeCatalogResource");function YT(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>KT({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>WT({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>JT({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Ld({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Ld({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Ld({kind:"resource",key:String(d.uri),routePath:e.routePath,seen:c});return{catalogSource:t,...e.catalog.serverInfo===void 0?{}:{serverInfo:e.catalog.serverInfo},tools:r,prompts:n,resources:a}}o(YT,"normalizeVirtualServerCatalog");function QT(e){let t=new Map,r=new Set;for(let n of e.routes){let a=n.policies?.inbound??[];if(a.length===0)continue;let i=a[0],s=i===void 0?void 0:e.policyByName.get(i);if(!s||!DT(s))continue;let c=ZT(n);c||He(`MCP virtual server route ${n.path} must declare an operationId in routes.oas.json.`),r.has(c)&&He(`Duplicate MCP virtual server operationId ${c} across routes.`),r.add(c);let d=HT(n.path);t.has(d)&&He(`Duplicate MCP virtual server id ${d} across routes.`);let p=[];for(let h of a.slice(1)){let y=e.policyByName.get(h);if(!y||!_g(y))continue;let _=e.connectionsByPolicyName.get(h);_||He(`Upstream connection policy ${h} referenced by route ${n.path} could not be resolved.`),p.push(_)}let l=yg(n.handler.options),m=YT({catalog:l,connections:p,routePath:n.path});m.catalogSource==="upstream_mcp"&&p.length!==1&&He(`MCP virtual server route ${n.path} uses upstream MCP catalog mode but declares ${p.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(d,{virtualServerId:d,operationId:c,routePath:n.path,handlerExport:n.handler.export,serverInfo:m.serverInfo,catalog:m,connections:p})}return t}o(QT,"buildVirtualServers");function vg(e){let t=VT(e.policies),r=FT(t),n=QT({routes:e.routes,policyByName:t,connectionsByPolicyName:r}),a=new Map;for(let i of r.values())a.set(i.upstreamServerId,i);return{byVirtualServerId:n,connectionsById:a}}o(vg,"buildGatewayConnectionRegistry");var Qi;function bg(e){Qi=e}o(bg,"setGatewayConnectionRegistry");function ht(){if(!Qi)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return Qi}o(ht,"getGatewayConnectionRegistry");function Rg(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return t}o(Rg,"getRegisteredVirtualServer");function Xo(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(Xo,"requireRegisteredVirtualServer");function Cg(){return Qi}o(Cg,"tryGetGatewayConnectionRegistry");var Ig=new Dt("gateway-route");function Pg(e,t){Ig.set(e,t)}o(Pg,"setGatewayRouteContext");function ea(e){return Ig.get(e)}o(ea,"readGatewayRouteContext");function Nn(e){let t=ea(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(Nn,"requireGatewayRouteContext");var Fr="2025-06-18";var XT=new Set(["localhost","::1"]);function gt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(gt,"normalizeHostname");function Le(e){let t=gt(e.hostname);return e.protocol==="http:"&&(XT.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(Le,"isLoopbackHttpUrl");function ce(e){return new URL(e).origin}o(ce,"readGatewayRequestOrigin");import{metrics as ek,context as Xi,propagation as Ag,SpanKind as Tg,SpanStatusCode as Gd,trace as ta}from"@opentelemetry/api";var tk="mcp-gateway",rk="mcp-gateway",nk=Fr,ok="2.0",kg=ta.getTracer(tk),Vd=ek.getMeter(rk),ak=Vd.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),ik=Vd.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),sk=Vd.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),ck=["traceparent","tracestate","baggage"];function Fd(){return performance.now()/1e3}o(Fd,"nowSeconds");function Eg(e,t){t(Math.max(Fd()-e,0))}o(Eg,"recordDurationSeconds");function xg(e){return e===void 0?void 0:String(e)}o(xg,"stringifyAttribute");function $e(e,t,r){r!==void 0&&(e[t]=r)}o($e,"assignAttribute");function uk(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(uk,"readTargetName");function Ug(e){let t=uk({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(Ug,"buildMcpOperationSpanName");function Zd(e){let t={"mcp.method.name":e.methodName};return $e(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??ok),$e(t,"jsonrpc.request.id",xg(e.jsonRpcRequestId)),$e(t,"mcp.protocol.version",e.mcpProtocolVersion??nk),$e(t,"mcp.session.id",e.mcpSessionId),$e(t,"mcp.resource.uri",e.resourceUri),$e(t,"rpc.response.status_code",xg(e.rpcResponseStatusCode)),$e(t,"error.type",e.errorType),e.capabilityType==="tool"&&($e(t,"gen_ai.operation.name","execute_tool"),$e(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&$e(t,"gen_ai.prompt.name",e.capabilityName),$e(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),$e(t,"network.protocol.version",e.networkProtocolVersion),$e(t,"network.transport",e.networkTransport),$e(t,"server.address",e.serverAddress),$e(t,"server.port",e.serverPort),$e(t,"client.address",e.clientAddress),$e(t,"client.port",e.clientPort),t}o(Zd,"buildMcpOperationAttributes");function dk(e){let t=Zd({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(dk,"buildMcpSessionAttributes");function Og(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:Gd.ERROR}),t instanceof Error&&e.recordException(t)}o(Og,"setSpanError");function $g(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o($g,"readErrorType");function lk(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Xi.active():Ag.extract(Xi.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(lk,"readServerParentContext");function pk(e){let t=ta.getSpanContext(Xi.active()),r=ta.getSpanContext(e);if(!(!t||!ta.isSpanContextValid(t))&&!(r&&ta.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(pk,"readAmbientSpanLink");function zg(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(zg,"readResultErrorType");async function Zr(e,t){let r=Fd(),n=Zd({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return kg.startActiveSpan(Ug(e),{kind:Tg.CLIENT,attributes:n},async a=>{try{let i=await t(),s=zg(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:Gd.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??$g(i);throw n["error.type"]=s,Og(a,i,s),i}finally{Eg(r,i=>{ak.record(i,n)}),a.end()}})}o(Zr,"runMcpClientOperation");async function Kr(e,t){let r=Fd(),n=lk(e.params),a=Zd({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=pk(n);return kg.startActiveSpan(Ug(e),{kind:Tg.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=zg(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:Gd.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??$g(c);throw a["error.type"]=d,Og(s,c,d),c}finally{Eg(r,c=>{ik.record(c,a)}),s.end()}})}o(Kr,"runMcpServerOperation");function Mg(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return Ag.inject(Xi.active(),t._meta,{set(r,n,a){ck.includes(n)&&(r[n]=a)}}),t}o(Mg,"injectMcpTraceContextIntoParams");function qg(e,t){let r=dk({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});sk.record(Math.max(t,0),r)}o(qg,"recordMcpClientSessionDuration");var Kd=new Dt("route-upstream-bindings");function mk(e){let t=Kd.get(e);if(t)return t;let r={bindings:[]};return Kd.set(e,r),r}o(mk,"readOrCreateRouteUpstreamBindingRegistry");function Ng(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Ng,"buildRouteBindingDuplicateKey");function Wd(e,t){let r=mk(e),n=Ng(t);if(r.bindings.find(i=>Ng(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.bindings.push(t)}o(Wd,"appendResolvedUpstreamBindingContext");function jg(e){return Kd.get(e)?.bindings??[]}o(jg,"readResolvedUpstreamBindingContexts");ie();var Q=u.string().datetime({offset:!0}).brand();function ne(e){return Q.parse(e.toISOString())}o(ne,"toIsoTimestamp");function Jt(e,t){return new Date(e.getTime()+t*1e3)}o(Jt,"addSeconds");ie();var ra=u.string().trim().min(1),na={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},fk=u.object({issuer:u.url(),jwksUrl:u.url(),audience:ra}),hk=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:ra.optional(),clientSecret:ra.optional(),scope:ra.default("openid profile email"),audience:ra.optional(),remoteTimeoutMs:u.coerce.number().int().positive().default(1e4),stateTtlSeconds:u.coerce.number().int().positive().default(900),sessionTtlSeconds:u.coerce.number().int().positive().default(28800)}).strict(),gk=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(na.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(na.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(na.cimdEnabled)}).strict().default(na),yk=u.object({oidc:fk,browserLogin:hk,gateway:gk.optional().default(na)}).strict();function Dg(e){return Sk(e.browserLogin.url)?"local_dev":"federated_oidc"}o(Dg,"readBrowserLoginKind");function Sk(e){let t;try{t=new URL(e)}catch{return!1}return Le(t)&&t.pathname==="/oauth/dev-login"}o(Sk,"isLoopbackDevLoginUrl");function es(e){return yk.parse(e)}o(es,"parseMcpOAuthRuntimeConfig");var Jd;function Hg(e){Jd=e}o(Hg,"setGatewayOAuthConfig");function xe(){if(!Jd)throw g("internal_server_error","MCP gateway OAuth config has not been initialized. An `mcp-oauth-inbound` policy (or a provider-specific wrapper such as `mcp-auth0-oauth-inbound`) must be registered in policies.json so the gateway can derive its OAuth runtime configuration from policy options.");return Jd}o(xe,"getGatewayOAuthConfig");function Ct(e){return ce(e)}o(Ct,"readGatewayOAuthIssuer");ie();var _k=43,wk=128,vk=/^[A-Za-z0-9._~-]+$/,Yd="S256",ts=u.literal(Yd),rs=u.string().min(_k).max(wk).regex(vk);ie();var ns=["none","client_secret_post","client_secret_basic"],bk=[...ns,"private_key_jwt"],Rk=["awaiting_login","awaiting_setup"],Ck=u.string().min(1).brand(),Be=u.string().min(1).brand(),oa=u.uuid().brand(),yt=u.uuid().brand(),os=u.uuid().brand(),Qd=u.enum(ns),Ik=u.enum(bk),Z2=u.enum(Rk),Lg=u.object({client_id:Be,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),token_endpoint_auth_method:Ik.default("none")}),Xd=u.object({clientId:Be,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:Qd,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:Q.optional(),clientExpiresAt:Q,revokedAt:Q.optional(),createdAt:Q}),el=u.object({clientId:Be,resource:u.string(),virtualServerId:Pe,subjectId:Ck,scope:u.string(),roles:u.array(u.string()),createdAt:Q,expiresAt:Q}),K2=el.extend({id:yt,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:ts}),tl=el.extend({id:oa,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:Q.optional(),revokedReason:u.string().optional()}),as=el.extend({tokenHash:u.string(),grantId:oa,revokedAt:Q.optional()});function rl(){return yt.parse(crypto.randomUUID())}o(rl,"createDownstreamAuthorizationTransactionId");function nl(){return os.parse(crypto.randomUUID())}o(nl,"createDownstreamBrowserLoginStateId");function Bg(){return oa.parse(crypto.randomUUID())}o(Bg,"createDownstreamGrantId");var ye="mcp:tools";function Gg(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return Le(r)&&Le(n)&&gt(r.hostname)===gt(n.hostname)&&r.pathname===n.pathname&&r.search===n.search}o(Gg,"redirectUriMatchesRegistration");function Vg(e){return Le(e)&&e.pathname==="/oauth/dev-login"}o(Vg,"isLoopbackDevLoginUrl");function is(e,t){return new URL(e,Ct(t)).toString()}o(is,"buildGatewayOAuthUrl");function ol(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ce(e.requestUrl)).toString()}o(ol,"buildScopedAuthorizationServerIssuer");function Pk(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ce(e.requestUrl)).toString()}o(Pk,"buildScopedAuthorizationEndpoint");function al(e){let t=xe();return{issuer:Ct(e),authorization_endpoint:is("/oauth/authorize",e),token_endpoint:is("/oauth/token",e),registration_endpoint:is("/oauth/register",e),revocation_endpoint:is("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ye],code_challenge_methods_supported:[Yd],token_endpoint_auth_methods_supported:ns,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":Dg(t)}}o(al,"buildAuthorizationServerMetadata");function Fg(e){let t=ol(e);return{...al(e.requestUrl),issuer:t,authorization_endpoint:Pk(e)}}o(Fg,"buildScopedAuthorizationServerMetadata");async function Zg(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=Xo(r);return Response.json(xk(n.virtualServerId,e.url))}catch(r){let n=he(r);return ft(e,t,{code:n==="unknown_virtual_server"?n:"not_found",detail:(r instanceof Error?r.message:void 0)??"The requested protected resource metadata document was not found."})}}o(Zg,"protectedResourceMetadataHandler");function xk(e,t){return{resource:Wr(e,t),resource_name:e,authorization_servers:[ol({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ye],mcp_protocol_version:Fr}}o(xk,"buildProtectedResourceMetadataResponseBody");function Wr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ce(t)).toString()}o(Wr,"buildCanonicalMcpResourceForVirtualServer");function Kg(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ce(t)).toString()}o(Kg,"buildProtectedResourceMetadataUrlForVirtualServer");import{base64url as il}from"jose";var Ak="sha256:",Tk=32;function Wg(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Wg,"copyToArrayBuffer");function Yt(){let e=crypto.getRandomValues(new Uint8Array(Tk));return il.encode(e)}o(Yt,"createOpaqueToken");async function pe(e){let t=await crypto.subtle.digest("SHA-256",Wg(new TextEncoder().encode(e)));return`${Ak}${il.encode(new Uint8Array(t))}`}o(pe,"hashOpaqueValue");async function Jg(e){let t=await crypto.subtle.digest("SHA-256",Wg(new TextEncoder().encode(e)));return il.encode(new Uint8Array(t))}o(Jg,"calculatePkceS256Challenge");ie();var kk=u.record(u.string(),u.unknown()),Yg=u.string().min(1),Ek=u.union([Yg.transform(e=>[e]),u.array(Yg)]),Se=u.string().min(1).brand(),Uk=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Ok=["https://zuplo.com/roles","roles","role","permissions","groups"],Qg=new Dt("gateway-principal");function $k(e){let t=kk.safeParse(e);return t.success?t.data:{}}o($k,"toClaimRecord");function zk(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(zk,"readValidationFailureDetail");function Mk(e,t,r){for(let i of Uk){let s=Se.safeParse(t[i]);if(s.success)return s.data}let n=Se.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",zk(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===Ct(r)?n.data:Se.parse(`${a}|${n.data}`)}o(Mk,"readNormalizedSubjectId");function qk(e){let t=new Set;for(let r of Ok){let n=Ek.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(qk,"readRoles");function jn(e,t){let r=$k(e?.data),n={subjectId:Mk(e,r,t)},a=qk(r);return a&&(n.roles=a),n}o(jn,"parseGatewayPrincipal");function Xg(e){let t=cl(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Xg,"requireGatewayPrincipal");function ey(e,t){Qg.set(e,t)}o(ey,"setGatewayPrincipal");function cl(e){return Qg.get(e)}o(cl,"readGatewayPrincipal");function ss(e){let r=['realm="OAuth"',`resource_metadata="${sl(Kg(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${sl(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${sl(e.scope)}"`),`Bearer ${r.join(", ")}`}o(ss,"buildGatewayBearerChallenge");function sl(e){let t="";for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);n<=31||n===127||(t+=e[r])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}o(sl,"sanitizeQuotedHeaderParameter");ie();ie();function cs(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(cs,"parseSafeRelativeReturnTo");ie();var Nk=["user","shared"],Dn=u.enum(Nk);function Cr(e){return{mode:"user",subjectId:e}}o(Cr,"buildUserUpstreamConnectionOwner");function us(){return{mode:"shared"}}o(us,"buildSharedUpstreamConnectionOwner");var ty=u.object({ownerMode:Dn,initiatedBySubjectId:Se,ownerSubjectId:Se.optional(),upstreamServerId:Xe,authProfileId:et,virtualServerId:Pe,returnTo:u.string().min(1).transform(e=>cs(e)).optional()});function ry(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}o(ry,"validateUpstreamOwnerState");var Hn=ty.superRefine(ry),ny=ty.omit({returnTo:!0}).superRefine(ry);function aa(e){return Hn.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,returnTo:e.returnTo})}o(aa,"buildUpstreamOwnerState");function Ln(e){if(e.ownerMode==="shared")return us();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return Cr(e.ownerSubjectId)}o(Ln,"resolveUpstreamConnectionOwnerFromState");var jk=["active","not_connected","reconsent_required"],Dk=["basic_auth_app_password","bearer_token"],oy=u.string().trim().min(1).brand(),Bn=u.uuid().brand(),ia=u.uuid().brand(),ul=u.enum(jk),Hk=u.enum(Dk),ay=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:Se.optional()}),Lk=ay.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:Hk.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),Bk=u.object({id:oy,subjectId:Se.optional(),ownerMode:Dn,upstreamServerId:Xe,authProfileId:et,status:ul,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:Q.optional(),metadata:Lk.optional(),createdAt:Q,updatedAt:Q});function dl(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(dl,"validateUpstreamConnectionOwnerShape");var Gn=Bk.superRefine(dl);function Jr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Jr,"readUpstreamConnectionLookupKey");var ll=Hn.extend({id:Bn,callbackPath:u.string().min(1),expiresAt:Q,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(ay.shape);function iy(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(iy,"readUpstreamConnectionStatus");function ds(){return oy.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(ds,"createUpstreamConnectionId");function sy(){return Bn.parse(crypto.randomUUID())}o(sy,"createOAuthStateId");function cy(){return ia.parse(crypto.randomUUID())}o(cy,"createBrowserConnectTicketId");ie();var ml=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:Se}).strict(),u.object({mode:u.literal("shared")}).strict()]),dy=u.object({owner:ml,upstreamServerId:Xe,authProfileId:et}).strict(),ly=u.object({items:u.array(dy).min(1).max(100)}).strict(),fl=u.object({items:u.array(u.object({key:u.object({ownerMode:Dn,subjectId:Se.optional(),upstreamServerId:Xe,authProfileId:et}).strict(),connection:Gn.strict().optional()}).strict())}).strict(),py=Gn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(dl),my=Gn.strict(),fy=u.object({owner:ml,upstreamServerId:Xe,authProfileId:et}).strict(),hy=u.object({owner:ml,upstreamServerId:Xe,authProfileId:et,connection:Gn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:ul,updatedAt:Gn.shape.updatedAt.optional()}).strict()}).strict(),Gk=u.enum(["none","client_secret_basic","client_secret_post"]),Yr=u.object({clientId:Be,clientName:u.string().min(1),tokenEndpointAuthMethod:Gk}).strict(),hl=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Be}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Be,clientSecretHashInput:u.string().min(1)}).strict()]),gl=u.object({id:yt,currentStateHash:u.string().min(1),clientId:Be,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:Pe,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),createdAt:Q,expiresAt:Q,consumedAt:Q.optional()}).strict(),uy=gl.omit({id:!0,consumedAt:!0}).extend({transactionId:yt,client:Yr.optional()}).strict(),yl=u.object({subjectId:Se,roles:u.array(u.string()).optional()}).strict(),Vk=gl.extend({phase:u.literal("awaiting_login")}).strict(),pl=gl.extend({phase:u.literal("awaiting_setup"),principal:yl}).strict(),Fk=u.discriminatedUnion("phase",[Vk,pl]),Sl=u.object({transaction:Fk,client:Yr}).strict(),gy=Xd.omit({revokedAt:!0}).strict(),yy=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:Yr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Sy=u.object({clientId:Be}).strict(),_y=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:Xd.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),wy=u.discriminatedUnion("phase",[uy.extend({phase:u.literal("awaiting_login")}).strict(),uy.extend({phase:u.literal("awaiting_setup"),principal:yl}).strict()]),vy=u.discriminatedUnion("kind",[Sl.extend({kind:u.literal("started")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("redirect_uri_mismatch")}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),by=u.object({transactionId:yt,currentStateHash:u.string().min(1),now:Q}).strict(),Ry=u.discriminatedUnion("kind",[Sl.extend({kind:u.literal("available")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Cy=u.object({transactionId:yt,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:yl,now:Q}).strict(),Iy=u.discriminatedUnion("kind",[Sl.extend({kind:u.literal("advanced")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Py=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:yt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:Se}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:Q,grantId:oa,now:Q}).strict(),u.object({decision:u.literal("cancel"),transactionId:yt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:Se}).strict(),now:Q}).strict()]),xy=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:pl,client:Yr}).strict(),u.object({kind:u.literal("cancelled"),transaction:pl,client:Yr}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed_already")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Ay=u.object({clientAuth:hl,codeHash:u.string().min(1),redirectUri:u.string().min(1),resource:u.string().min(1).optional(),codeChallenge:u.string().min(1),currentRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),grantExpiresAt:Q,accessTokenExpiresAt:Q,now:Q}).strict(),Ty=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:Yr,grant:tl.strict()}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("binding_mismatch")}).strict()]),ky=u.object({clientAuth:hl,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:Q,now:Q}).strict(),Ey=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:Yr,grant:tl.strict(),accessToken:as.strict(),matched:u.literal("current")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),Uy=u.object({clientAuth:hl,tokenHash:u.string().min(1),now:Q}).strict(),Oy=u.discriminatedUnion("kind",[u.object({kind:u.literal("revoked_access_token")}).strict(),u.object({kind:u.literal("revoked_grant")}).strict(),u.object({kind:u.literal("client_mismatch")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("invalid_client")}).strict()]),$y=u.object({tokenHash:u.string().min(1),now:Q}).strict(),zy=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:as.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),My=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:Pe,upstreamConnectionKeys:u.array(dy).max(100),now:Q}).strict(),qy=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:Se,roles:u.array(u.string())}).strict(),accessToken:as.strict(),upstreamConnections:fl.shape.items}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict()]),Ny=u.object({record:ll}).strict(),jy=u.object({kind:u.literal("saved")}).strict(),Dy=u.object({id:Bn,now:Q}).strict(),Hy=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:ll}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Ly=u.object({id:ia,expiresAt:Q,now:Q}).strict(),By=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var Gy=100;function Vy(e){return e!==null&&typeof e=="object"}o(Vy,"isProblemDetailsShape");var Zk="/zups/v2/mcp/storage";function ze(e){return`${Zk}/${e}`}o(ze,"buildStoragePath");function Kk(){return ze("upstream-connections/batch-get")}o(Kk,"buildBatchGetUpstreamConnectionsPath");function Wk(){return ze("upstream-connections/upsert")}o(Wk,"buildUpsertUpstreamConnectionPath");function Jk(){return ze("authorization/read-setup")}o(Jk,"buildReadAuthorizationSetupPath");function Yk(){return ze("oauth/register-client")}o(Yk,"buildRegisterClientPath");function Qk(){return ze("oauth/read-client")}o(Qk,"buildReadClientPath");function Xk(){return ze("authorization/start")}o(Xk,"buildStartAuthorizationPath");function e0(){return ze("authorization/read-pending")}o(e0,"buildReadPendingAuthorizationPath");function t0(){return ze("authorization/advance-pending")}o(t0,"buildAdvancePendingAuthorizationPath");function r0(){return ze("authorization/decide-setup")}o(r0,"buildDecideAuthorizationSetupPath");function n0(){return ze("token/exchange-authorization-code")}o(n0,"buildExchangeAuthorizationCodePath");function o0(){return ze("token/refresh")}o(o0,"buildRefreshTokenPath");function a0(){return ze("token/revoke")}o(a0,"buildRevokeOAuthTokenPath");function i0(){return ze("token/validate-access-token")}o(i0,"buildValidateAccessTokenPath");function s0(){return ze("mcp/authorize-and-load-connections")}o(s0,"buildAuthorizeAndLoadConnectionsPath");function c0(){return ze("upstream-oauth-state/save")}o(c0,"buildSaveUpstreamOAuthStatePath");function u0(){return ze("upstream-oauth-state/consume")}o(u0,"buildConsumeUpstreamOAuthStatePath");function d0(){return ze("browser-connect-ticket/consume")}o(d0,"buildConsumeBrowserConnectTicketPath");function l0(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(l0,"responseKeyMatchesLookup");function p0(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(p0,"authorizationSetupMatchesLookup");function Ky(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(Ky,"connectionMatchesLookup");function m0(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&wl(e.scopes,t.scopes)&&_l(e.expiresAt,t.expiresAt)&&h0(e.metadata,t.metadata)}o(m0,"connectionMatchesUpsertRecord");function _l(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(_l,"optionalTimestampInstantsMatch");function f0(e,t){return Date.parse(e)<=Date.parse(t)}o(f0,"timestampInstantIsAtOrBefore");function wl(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(wl,"stringArraysMatch");function h0(e,t){let r=Fy(e),n=Fy(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(h0,"metadataMatches");function Fy(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(Fy,"definedMetadataEntries");function be(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(be,"throwInvalidStorageResponse");async function g0(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){be("Gateway Service storage response did not match the runtime storage contract.",r)}}o(g0,"parseRuntimeHttpStorageResponse");function Wy(e,t){e.length!==t.length&&be("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];l0(n.key,a)||be("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!Ky(n.connection,a)&&be("Gateway Service storage response connection did not match the response key.")}}o(Wy,"validateUpstreamConnectionItemsMatchLookups");function y0(e,t){p0(e,t)||be("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Ky(e.connection,t)&&be("Gateway Service storage response authorization setup connection did not match the request.");let r=e.connection?.status==="active",n=e.connection?.status??"not_connected",a=e.connection?.updatedAt;(e.connectionStatus.connected!==r||e.connectionStatus.status!==n||!_l(e.connectionStatus.updatedAt,a))&&be("Gateway Service storage response authorization setup status did not match the connection.")}o(y0,"validateAuthorizationSetupResponseMatchesLookup");function S0(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&be("Gateway Service storage response registered client did not match the request.")}o(S0,"validateRegisterClientResponseMatchesRequest");function _0(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&be("Gateway Service storage response client did not match the request.")}o(_0,"validateReadClientResponseMatchesRequest");function w0(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.virtualServerId!==t.virtualServerId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&be("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&be("Gateway Service storage response started authorization principal did not match the request."))}o(w0,"validateStartAuthorizationResponseMatchesRequest");function Zy(e,t){e.kind!=="available"&&e.kind!=="advanced"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&be("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&be("Gateway Service storage response advanced authorization did not match the request."))}o(Zy,"validatePendingAuthorizationResponseMatchesRequest");function v0(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&be("Gateway Service storage response authorization setup transaction did not match the request.")}o(v0,"validateAuthorizationSetupDecisionResponseMatchesRequest");function b0(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!_l(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&be("Gateway Service storage response authorization-code exchange did not match the request.")}o(b0,"validateExchangeAuthorizationCodeResponseMatchesRequest");function R0(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&be("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!f0(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!P0(e.accessToken,e.grant))&&be("Gateway Service storage response token refresh access token did not match the request."))}o(R0,"validateRefreshTokenResponseMatchesRequest");function C0(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&be("Gateway Service storage response access token did not match the request.")}o(C0,"validateAccessTokenValidationResponseMatchesRequest");function I0(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!wl(e.principal.roles,e.accessToken.roles))&&be("Gateway Service storage response MCP authorization did not match the request."),Wy(e.upstreamConnections,t.upstreamConnectionKeys))}o(I0,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function P0(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&wl(e.roles,t.roles)}o(P0,"accessTokenMatchesGrant");async function x0(e){try{return await e.clone().json()}catch{return}}o(x0,"readProblemDetails");async function A0(e){let t=await x0(e),r=Vy(t)&&typeof t.status=="number"?t.status:e.status,n=Vy(t)&&Qo(t.code)?t.code:Ud(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(A0,"throwRuntimeHttpStorageError");var ls=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??Np.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}async#e(t){let r=t.requestSchema.parse(t.input),n=new URL(t.path,this.#t),a=new Headers({"Content-Type":"application/json"});jp(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await A0(i),{request:r,response:await g0(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=Jr(s),d=n.get(c);if(d!==void 0)return d;let p=r.length;return r.push(s),n.set(c,p),p}),i=[];for(let s=0;s<r.length;s+=Gy){let c=r.slice(s,s+Gy);i.push(...await this.#n(c))}return a.map(s=>i[s])}async upsertUpstreamConnection(t){let{request:r,response:n}=await this.#e({input:t,path:Wk(),requestSchema:py,responseSchema:my});return m0(n,r)||be("Gateway Service storage response connection did not match the request."),n}async readAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:Jk(),requestSchema:fy,responseSchema:hy});return y0(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:Yk(),requestSchema:gy,responseSchema:yy});return S0(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:Qk(),requestSchema:Sy,responseSchema:_y});return _0(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Xk(),requestSchema:wy,responseSchema:vy});return w0(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:e0(),requestSchema:by,responseSchema:Ry});return Zy(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:t0(),requestSchema:Cy,responseSchema:Iy});return Zy(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:r0(),requestSchema:Py,responseSchema:xy});return v0(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:c0(),requestSchema:Ny,responseSchema:jy});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:u0(),requestSchema:Dy,responseSchema:Hy});return n.kind==="available"&&n.record.id!==r.id&&be("Gateway Service storage response upstream OAuth state did not match the request."),n}async consumeBrowserConnectTicket(t){let{response:r}=await this.#e({input:t,path:d0(),requestSchema:Ly,responseSchema:By});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:n0(),requestSchema:Ay,responseSchema:Ty});return b0(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:o0(),requestSchema:ky,responseSchema:Ey});return R0(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:a0(),requestSchema:Uy,responseSchema:Oy});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:i0(),requestSchema:$y,responseSchema:zy});return C0(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:s0(),requestSchema:My,responseSchema:qy});return I0(n,r),n}async#n(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:Kk(),requestSchema:ly,responseSchema:fl});return Wy(n.items,t),n.items.map(a=>a.connection)}};var T0="__zuploMcpGatewayStorageBackend",vl;function k0(){return new ls({})}o(k0,"buildProductionStorageBackend");function J(){let e=globalThis[T0];return e||(vl||(vl=k0()),vl)}o(J,"getStorage");function bl(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(bl,"readBearerToken");function E0(e,t,r){return ft(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(E0,"gatewayAuthenticationRequiredResponse");async function U0(e,t,r){let n=await J().validateAccessToken({tokenHash:await pe(e),now:ne(new Date)});if(n.kind!=="valid")throw t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed"),g("authentication_required","Gateway access token is expired, revoked, or invalid.");return n.record}o(U0,"validateGatewayAccessToken");function O0(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.virtualServerId!==e.virtualServerId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedVirtualServerId:e.virtualServerId,tokenVirtualServerId:e.accessToken.virtualServerId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(O0,"assertAccessTokenResource");function $0(e,t,r){return ft(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":ss({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ye} scope required by this MCP resource.`,scope:ye})}})}o($0,"insufficientScopeResponse");function z0(e){return{subjectId:e.subjectId,roles:e.roles}}o(z0,"principalFromAccessToken");function M0(e){let t=he(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),ft(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":ss({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(M0,"gatewayTokenRejectedResponse");async function Rl(e,t){let r=Nn(t),n=Wr(r.virtualServerId,e.url),a=bl(e),i=ss({virtualServerId:r.virtualServerId,requestUrl:e.url});if(!a)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",virtualServerId:r.virtualServerId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),E0(e,t,i);try{let s=await U0(a,t,r.virtualServerId);if(O0({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ye)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ye,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),$0(e,t,r.virtualServerId);let c=z0(s);return ey(t,c),Ed(t,c),e}catch(s){return M0({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Rl,"gatewayTokenInbound");var q0=2,Jy=4,N0=24,j0=16,Yy=512,D0=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,H0=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,L0=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,B0=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,G0=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,V0=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Qy(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(Qy,"readRoute");function F0(e){let t=Qy(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(F0,"readRoutePath");function Z0(e){let t=Qy(e)?.raw;if(typeof t!="function")return;let r=t();if(!r||typeof r!="object")return;let n=r.operationId;return typeof n=="string"&&n.length>0?n:void 0}o(Z0,"readRouteOperationId");function K0(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(K0,"deriveStatusClass");function W0(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="shared"?"shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(W0,"deriveOriginAttributionMode");function J0(e){if(!e)return;let t=e.toLowerCase();return t.includes("desktop")||t.includes("claude")||t.includes("chatgpt")?"desktop":t.includes("vscode")||t.includes("cursor")||t.includes("zed")||t.includes("jetbrains")||t.includes("ide")?"ide":t.includes("extension")?"extension":t.includes("agent")||t.includes("bot")||t.includes("worker")||t.includes("service")?"service":"unknown"}o(J0,"deriveClientKind");function Y0(e,t){return t==="success"?"none":e===K.MCP_GATEWAY_REQUEST_RECEIVED||e===K.MCP_GATEWAY_REQUEST_REJECTED||e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===K.MCP_GATEWAY_POLICY_DECISION?"policy":e===K.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===K.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o(Y0,"deriveFailureStage");function Q0(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_POLICY_DECISION||e===K.MCP_GATEWAY_GUARDRAIL_DECISION||e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===K.MCP_GATEWAY_CAPABILITY_FAILED||e===K.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===K.MCP_GATEWAY_REQUEST_REJECTED||e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(Q0,"deriveFailureOrigin");function X0(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_POLICY_DECISION?"policy":e===K.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===K.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o(X0,"deriveReasonClass");function eE(e){return e.length<=Yy?e:`${e.slice(0,Yy)}...`}o(eE,"truncateAnalyticsString");function tE(e){return eE(e.replace(H0,"$1[REDACTED]$3").replace(B0,"$1$2[REDACTED]").replace(L0,"$1$2[REDACTED]").replace(G0,"Bearer [REDACTED]").replace(V0,"Basic [REDACTED]"))}o(tE,"redactAnalyticsString");function Xy(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return tE(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=Jy?"[DEPTH_LIMIT]":e.slice(0,j0).map(r=>Xy(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=Jy?"[DEPTH_LIMIT]":eS(e,t+1)}}o(Xy,"sanitizeAnalyticsValue");function eS(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,N0)){if(D0.test(n)){r[n]="[REDACTED]";continue}let i=Xy(a,t);i!==void 0&&(r[n]=i)}return Object.keys(r).length===0?void 0:r}o(eS,"sanitizeMcpGatewayAnalyticsAttributes");function M(e){return e===void 0?null:e}o(M,"nullable");function rE(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(rE,"readEnvironment");function nE(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(nE,"readRequestId");function oE(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(oE,"attributesToJsonString");function aE(e,t){let r=cl(e),n=ea(e),a=eS(t.attributes),i=nE(e),s=t.ownerMode??t.routeBinding?.ownerMode??null,c=t.upstreamAuthMode??t.routeBinding?.authMode??null,d=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId??null,p=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId??null,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName??null,m=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId??null,h=t.clientKind??J0(t.clientName)??null,y=W0(s??void 0,c??void 0)??null,_=K0(t.httpStatusCode)??null,S=t.reasonClass??X0(t.eventType,t.outcome),w=t.failureOrigin??Q0(t.eventType,t.outcome),v=t.failureStage??Y0(t.eventType,t.outcome);return{schemaVersion:q0,outcome:t.outcome,subjectId:M(r?.subjectId),environment:rE(e),traceId:t.traceId??i,spanId:M(t.spanId),parentEventId:M(t.parentEventId),mcpSessionId:M(t.mcpSessionId),routeSurface:M(t.routeSurface),routePath:F0(e)??null,operationId:Z0(e)??null,virtualServerName:d,virtualServerTitle:M(t.virtualServerTitle),upstreamServerName:p,upstreamServerTitle:l,upstreamBindingId:M(t.upstreamBindingId),clientName:M(t.clientName),clientTitle:M(t.clientTitle),clientVersion:M(t.clientVersion),clientKind:h,authProfileId:m,upstreamAuthMode:c,ownerMode:s,authMethod:M(t.authMethod),originAttributionMode:y,httpMethod:M(t.httpMethod),httpStatusCode:M(t.httpStatusCode),statusClass:_,mcpMethod:M(t.mcpMethod),mcpProtocolVersion:M(t.mcpProtocolVersion),mcpStatus:M(t.mcpStatus),mcpErrorType:M(t.mcpErrorType),applicationError:M(t.applicationError),applicationErrorCode:M(t.applicationErrorCode),toolResultIsError:M(t.toolResultIsError),capabilityType:M(t.capabilityType),capabilityName:M(t.capabilityName),capabilityTitle:M(t.capabilityTitle),upstreamCapabilityName:M(t.upstreamCapabilityName),upstreamCapabilityTitle:M(t.upstreamCapabilityTitle),capabilitySchemaHash:M(t.capabilitySchemaHash),policyId:M(t.policyId),policyAction:M(t.policyAction),guardrailType:M(t.guardrailType),guardrailDirection:M(t.guardrailDirection),guardrailFindingCount:M(t.guardrailFindingCount),redactionCount:M(t.redactionCount),requestMutated:M(t.requestMutated),responseMutated:M(t.responseMutated),latencyMs:M(t.latencyMs),gatewayLatencyMs:M(t.gatewayLatencyMs),upstreamLatencyMs:M(t.upstreamLatencyMs),authLatencyMs:M(t.authLatencyMs),policyLatencyMs:M(t.policyLatencyMs),requestBytes:M(t.requestBytes),responseBytes:M(t.responseBytes),estimatedInputTokens:M(t.estimatedInputTokens),estimatedOutputTokens:M(t.estimatedOutputTokens),estimatedContextTokens:M(t.estimatedContextTokens),contextPressureBucket:M(t.contextPressureBucket),responseMimeTypes:M(t.responseMimeTypes),base64Suspected:M(t.base64Suspected),truncated:M(t.truncated),isLargePayloadRequest:M(t.isLargePayloadRequest),isLargePayloadResponse:M(t.isLargePayloadResponse),payloadCaptureMode:M(t.payloadCaptureMode),reasonCode:M(t.reasonCode),reasonClass:S,errorType:t.errorType??t.reasonCode??null,failureOrigin:w,failureStage:v,customMetadataJson:M(t.customMetadataJson),attributesJson:oE(a)}}o(aE,"buildMcpGatewayAnalyticsMetadata");function tt(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,aE(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(tt,"emitMcpGatewayAnalyticsEvent");function rt(e){let t=ht().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(rt,"getUpstreamServerConfig");function iE(e){let t=ht().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(iE,"resolveUpstreamAuthProfileId");function Ir(e){iE(e);let t=ht().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(Ir,"getUpstreamAuthConfig");function Qr(e,t){let r=Ir({upstreamServerId:e,authProfileId:t});if(!gg(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(Qr,"requireUpstreamOAuthConfig");var sE={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},user_oauth:{authMode:"user_oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},static_secret:{authMode:"static_secret",ownerMode:"none",connectSupport:"none",connectUnsupportedDetail:"Static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"configured_static_secret"},"shared-secret":{authMode:"shared-secret",ownerMode:"shared",connectSupport:"none",connectUnsupportedDetail:"Shared static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"shared_secret_connection"},"user-secret":{authMode:"user-secret",ownerMode:"user",connectSupport:"user_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_secret_connection"}};function $t(e){return sE[e]}o($t,"describeUpstreamAuthMode");function ps(e){return $t(e).ownerMode}o(ps,"resolveOwnerModeForUpstreamAuthMode");ie();import{errors as uS,jwtVerify as dS,SignJWT as lS}from"jose";ie();var tS=u.string().trim().min(1),cE=u.object({TOKEN_ENCRYPTION_KEY:tS,OAUTH_STATE_SIGNING_KEY:tS}),uE=["TOKEN_ENCRYPTION_KEY","OAUTH_STATE_SIGNING_KEY"];function dE(e){let t=lo[e];return typeof t=="string"?t:void 0}o(dE,"readEnvValue");function lE(){let e={};for(let t of uE){let r=dE(t);r!==void 0&&(e[t]=r)}return e}o(lE,"readRawEnv");var Cl;function pE(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.map(String).join("."):"environment"}: ${t.message}`)}o(pE,"formatZodIssues");function mE(e){return new jt(["Invalid MCP gateway environment configuration.","Validation failed for these environment variables:",...pE(e)].join(`
47
+ `),{cause:e})}o(mE,"createEnvValidationError");function fE(e){let t=cE.safeParse(e);if(!t.success)throw mE(t.error);return t.data}o(fE,"parseGatewayEnv");function hE(){return Cl||(Cl=fE(lE())),Cl}o(hE,"readEnv");function rS(){return hE()}o(rS,"getEnv");import{base64url as gE}from"jose";var yE=new TextEncoder,Il=32;function nS(e,t={}){let r=[SE(e),yE.encode(e)],n;for(let a of r)if(a){if(a.byteLength>=Il){n=a;break}(n===void 0||a.byteLength>n.byteLength)&&(n=a)}if(n===void 0||n.byteLength<Il){let a=t.name??"secret key material",i=n?.byteLength??0;throw new Error(`${a} must decode to at least ${Il} bytes (got ${i}). Generate a high-entropy value with for example: openssl rand -base64 32 | tr '+/' '-_' | tr -d '='.`)}return n}o(nS,"decodeConfiguredSecretKeyMaterial");function SE(e){try{return gE.decode(e)}catch{return}}o(SE,"tryDecodeBase64Url");var oS=new Map,aS=new Map;function _E(e){let t=oS.get(e);return t||(t=nS(rS()[e],{name:e}),oS.set(e,t)),t}o(_E,"getMasterKeyMaterial");async function zt(e){let t=aS.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(_E(e.envVar));return aS.set(e.purpose,r),r}o(zt,"readCachedDerivedKey");var wE="SHA-256";var vE="zuplo-mcp-gateway:",bE=new TextEncoder,iS=new WeakMap;async function Pr(e,t){let r=iS.get(e);r||(r=new Map,iS.set(e,r));let n=r.get(t);if(n)return n;let a=await RE(e,t);return r.set(t,a),a}o(Pr,"deriveGatewaySigningKey");async function RE(e,t){let r=sS(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=bE.encode(`${vE}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:wE,salt:new Uint8Array,info:sS(a)},n,32*8);return new Uint8Array(i)}o(RE,"hkdfExpand");function sS(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(sS,"copyToArrayBuffer");var ms="HS256",pS=15*60,CE=15*60,fs="zuplo-mcp-gateway",hs="zuplo-mcp-gateway",IE=ny.extend({id:Bn}),PE=IE.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),mS=Hn.extend({id:ia,purpose:u.literal("browser_connect")}),xE=Hn.extend({purpose:u.literal("browser_connect")}),AE=mS.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),fS=pS*1e3;async function hS(){return zt({purpose:"oauth-state",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>Pr(e,"oauth-state"),"derive")})}o(hS,"getOAuthStateKey");async function gS(){return zt({purpose:"browser-connect",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>Pr(e,"browser-connect"),"derive")})}o(gS,"getBrowserConnectKey");async function yS(e){let t=Math.floor(Date.now()/1e3)+pS;return new lS(e).setProtectedHeader({alg:ms,typ:"JWT"}).setIssuer(fs).setAudience(hs).setIssuedAt().setExpirationTime(t).sign(await hS())}o(yS,"signOAuthState");async function gs(e){try{let{payload:t}=await dS(e,await hS(),{algorithms:[ms],issuer:fs,audience:hs});return PE.parse(t)}catch(t){throw t instanceof uS.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(gs,"verifyOAuthState");async function SS(e){let t=Math.floor(Date.now()/1e3)+CE,r=xE.parse(e),n=mS.parse({...r,id:cy()});return new lS(n).setProtectedHeader({alg:ms,typ:"JWT"}).setIssuer(fs).setAudience(hs).setIssuedAt().setExpirationTime(t).sign(await gS())}o(SS,"signBrowserConnectTicket");async function ys(e){try{let{payload:t}=await dS(e,await gS(),{algorithms:[ms],issuer:fs,audience:hs});return AE.parse(t)}catch(t){throw t instanceof uS.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(ys,"verifyBrowserConnectTicket");async function Ss(e){if((await J().consumeBrowserConnectTicket({id:e.id,expiresAt:ne(new Date(e.exp*1e3)),now:ne(new Date)})).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(Ss,"consumeBrowserConnectTicket");function TE(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(TE,"buildConnectRequiredMessage");async function _S(e){let t=ce(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("virtualServerId",e.virtualServerId),r.searchParams.set("browserTicket",await SS({...aa(e),purpose:"browser_connect"})),r.toString()}o(_S,"buildGatewayBrowserTicketUrl");function kE(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(kE,"buildGatewayConnectPath");async function Pl(e){return _S({...e,path:kE(e.upstreamServerId),redirect:!0})}o(Pl,"buildGatewayConnectUrl");async function wS(e){return _S({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(wS,"buildGatewayAppPasswordCaptureUrl");async function Vn(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Pl(t),message:TE(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Vn,"buildRedirectConnectRequiredResponse");function vS(e){return bS({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(vS,"buildAdminConnectRequiredResponse");function bS(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(bS,"buildAdminSetupRequiredResponse");function RS(e){return bS({...e,message:e.requiresReconsent?`An administrator must replace the ${e.upstreamDisplayName} static credential before this tool can be used.`:`An administrator must configure the ${e.upstreamDisplayName} static credential before this tool can be used.`})}o(RS,"buildAdminStaticSecretRequiredResponse");ie();import{base64url as xr}from"jose";var EE="SHA-256",Zn="AES-GCM",UE=12,Al="zuplo-secret",Tl=1,CS="env:TOKEN_ENCRYPTION_KEY",OE=u.object({version:u.literal(Tl),keyId:u.literal(CS),algorithm:u.literal(Zn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function Fn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Fn,"copyToArrayBuffer");async function xl(){return zt({purpose:"token-encryption",envVar:"TOKEN_ENCRYPTION_KEY",derive:o(async e=>{let t=await crypto.subtle.digest(EE,Fn(e));return crypto.subtle.importKey("raw",t,{name:Zn},!1,["encrypt","decrypt"])},"derive")})}o(xl,"getEncryptionKey");function IS(e){return Fn(new TextEncoder().encode(`${Al}:v${e.version}:${e.keyId}`))}o(IS,"getAssociatedData");function $E(e){return`${Al}:v${e.version}:${xr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o($E,"encodeEnvelope");function zE(e){let t=`${Al}:v${Tl}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(xr.decode(r));return OE.parse(JSON.parse(n))}o(zE,"decodeEnvelope");async function Xr(e){let t=await xl(),r=crypto.getRandomValues(new Uint8Array(UE)),n={version:Tl,keyId:CS},a=await crypto.subtle.encrypt({name:Zn,iv:r,additionalData:IS(n)},t,new TextEncoder().encode(e));return $E({...n,algorithm:Zn,iv:xr.encode(r),ciphertext:xr.encode(new Uint8Array(a))})}o(Xr,"encryptSecret");async function Qt(e){let t=zE(e);if(t){let s=await xl(),c=await crypto.subtle.decrypt({name:Zn,iv:Fn(xr.decode(t.iv)),additionalData:IS(t)},s,Fn(xr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await xl(),i=await crypto.subtle.decrypt({name:Zn,iv:Fn(xr.decode(r))},a,Fn(xr.decode(n)));return new TextDecoder().decode(i)}o(Qt,"decryptSecret");function ME(e,t){let r=Ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(ME,"requireTenantStaticSecretConfig");function PS(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(PS,"hasUsableTenantStaticSecret");async function qE(e){if(!PS(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Qt(e.connection.metadata.encryptedStaticSecret)}}o(qE,"resolveTenantStaticSecretCredential");async function xS(e){let t=rt(e.upstreamServerId);ME(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(PS(r))return{kind:"authorized",credential:await qE({connection:r})};let n={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:RS(n)}}o(xS,"resolveTenantStaticSecretCredentialForRequest");ie();async function kl(e){return J().upsertUpstreamConnection({id:ds(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(kl,"upsertStaticSecretConnection");var NE=u.string().trim().min(1).max(320),jE=u.string().min(1).max(4096),DE=u.string().trim().min(1).max(4096);function El(e,t){let r=Ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(El,"requireUserStaticSecretConfig");function HE(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(HE,"encodeBase64Utf8");function LE(e){return`Basic ${HE(`${e.username}:${e.appPassword}`)}`}o(LE,"buildBasicAuthHeader");function AS(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(AS,"hasEncryptedUserStaticSecret");async function BE(e){if(!AS(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await Qt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:LE({username:e.connection.metadata.staticSecretUsername,appPassword:await Qt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(BE,"resolveUserStaticSecretCredential");async function TS(e){if(El(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=NE.parse(e.username),n=jE.parse(e.appPassword);return kl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Xr(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(TS,"saveUserStaticSecretCredential");async function _s(e){let t=El(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=DE.parse(e.token);return kl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Xr(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(_s,"saveUserStaticBearerTokenCredential");function Ul(e,t){return El(e,t)}o(Ul,"readUserStaticSecretCaptureConfig");async function kS(e){let t=rt(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(AS(r))return{kind:"authorized",credential:await BE({connection:r})};let n={requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:await Vn(n)}}o(kS,"resolveUserStaticSecretCredentialForRequest");function ES(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return wS({requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}})}o(ES,"buildUserStaticSecretConnectUrl");var Ol;Ol=globalThis.crypto;async function GE(e){return(await Ol).getRandomValues(new Uint8Array(e))}o(GE,"getRandomValues");async function VE(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await GE(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(VE,"random");async function FE(e){return await VE(e)}o(FE,"generateVerifier");async function ZE(e){let t=await(await Ol).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(ZE,"generateChallenge");async function $l(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await FE(e),r=await ZE(t);return{code_verifier:t,code_challenge:r}}o($l,"pkceChallenge");ie();var Me=Bp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Zp.custom,message:"URL must be parseable",fatal:!0}),Hp}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ws=Ce({resource:f().url(),authorization_servers:C(Me).optional(),jwks_uri:f().url().optional(),scopes_supported:C(f()).optional(),bearer_methods_supported:C(f()).optional(),resource_signing_alg_values_supported:C(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:ae().optional(),authorization_details_types_supported:C(f()).optional(),dpop_signing_alg_values_supported:C(f()).optional(),dpop_bound_access_tokens_required:ae().optional()}),sa=Ce({issuer:f(),authorization_endpoint:Me,token_endpoint:Me,registration_endpoint:Me.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),service_documentation:Me.optional(),revocation_endpoint:Me.optional(),revocation_endpoint_auth_methods_supported:C(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:C(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(f()).optional(),code_challenge_methods_supported:C(f()).optional(),client_id_metadata_document_supported:ae().optional()}),KE=Ce({issuer:f(),authorization_endpoint:Me,token_endpoint:Me,userinfo_endpoint:Me.optional(),jwks_uri:Me,registration_endpoint:Me.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),acr_values_supported:C(f()).optional(),subject_types_supported:C(f()),id_token_signing_alg_values_supported:C(f()),id_token_encryption_alg_values_supported:C(f()).optional(),id_token_encryption_enc_values_supported:C(f()).optional(),userinfo_signing_alg_values_supported:C(f()).optional(),userinfo_encryption_alg_values_supported:C(f()).optional(),userinfo_encryption_enc_values_supported:C(f()).optional(),request_object_signing_alg_values_supported:C(f()).optional(),request_object_encryption_alg_values_supported:C(f()).optional(),request_object_encryption_enc_values_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),display_values_supported:C(f()).optional(),claim_types_supported:C(f()).optional(),claims_supported:C(f()).optional(),service_documentation:f().optional(),claims_locales_supported:C(f()).optional(),ui_locales_supported:C(f()).optional(),claims_parameter_supported:ae().optional(),request_parameter_supported:ae().optional(),request_uri_parameter_supported:ae().optional(),require_request_uri_registration:ae().optional(),op_policy_uri:Me.optional(),op_tos_uri:Me.optional(),client_id_metadata_document_supported:ae().optional()}),vs=I({...KE.shape,...sa.pick({code_challenge_methods_supported:!0}).shape}),ca=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Kp.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),OS=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),US=Me.optional().or(O("").transform(()=>{})),WE=I({redirect_uris:C(Me),token_endpoint_auth_method:f().optional(),grant_types:C(f()).optional(),response_types:C(f()).optional(),client_name:f().optional(),client_uri:Me.optional(),logo_uri:US,scope:f().optional(),contacts:C(f()).optional(),tos_uri:US,policy_uri:f().optional(),jwks_uri:Me.optional(),jwks:Vp().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),zl=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:ee().optional(),client_secret_expires_at:ee().optional()}).strip(),ua=WE.merge(zl),q9=I({error:f(),error_description:f().optional()}).strip(),N9=I({token:f(),token_type_hint:f().optional()}).strip();function $S(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o($S,"resourceUrlFromServerUrl");function zS({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return a.startsWith(i)}o(zS,"checkResourceAllowed");var Re=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},da=class extends Re{static{o(this,"InvalidRequestError")}};da.errorCode="invalid_request";var en=class extends Re{static{o(this,"InvalidClientError")}};en.errorCode="invalid_client";var tn=class extends Re{static{o(this,"InvalidGrantError")}};tn.errorCode="invalid_grant";var rn=class extends Re{static{o(this,"UnauthorizedClientError")}};rn.errorCode="unauthorized_client";var la=class extends Re{static{o(this,"UnsupportedGrantTypeError")}};la.errorCode="unsupported_grant_type";var pa=class extends Re{static{o(this,"InvalidScopeError")}};pa.errorCode="invalid_scope";var ma=class extends Re{static{o(this,"AccessDeniedError")}};ma.errorCode="access_denied";var Xt=class extends Re{static{o(this,"ServerError")}};Xt.errorCode="server_error";var fa=class extends Re{static{o(this,"TemporarilyUnavailableError")}};fa.errorCode="temporarily_unavailable";var ha=class extends Re{static{o(this,"UnsupportedResponseTypeError")}};ha.errorCode="unsupported_response_type";var ga=class extends Re{static{o(this,"UnsupportedTokenTypeError")}};ga.errorCode="unsupported_token_type";var ya=class extends Re{static{o(this,"InvalidTokenError")}};ya.errorCode="invalid_token";var Sa=class extends Re{static{o(this,"MethodNotAllowedError")}};Sa.errorCode="method_not_allowed";var _a=class extends Re{static{o(this,"TooManyRequestsError")}};_a.errorCode="too_many_requests";var nn=class extends Re{static{o(this,"InvalidClientMetadataError")}};nn.errorCode="invalid_client_metadata";var wa=class extends Re{static{o(this,"InsufficientScopeError")}};wa.errorCode="insufficient_scope";var va=class extends Re{static{o(this,"InvalidTargetError")}};va.errorCode="invalid_target";var MS={[da.errorCode]:da,[en.errorCode]:en,[tn.errorCode]:tn,[rn.errorCode]:rn,[la.errorCode]:la,[pa.errorCode]:pa,[ma.errorCode]:ma,[Xt.errorCode]:Xt,[fa.errorCode]:fa,[ha.errorCode]:ha,[ga.errorCode]:ga,[ya.errorCode]:ya,[Sa.errorCode]:Sa,[_a.errorCode]:_a,[nn.errorCode]:nn,[wa.errorCode]:wa,[va.errorCode]:va};var er=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function JE(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(JE,"isClientAuthMethod");var Ml="code",ql="S256";function YE(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&JE(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(YE,"selectClientAuthMethod");function QE(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":XE(a,i,r);return;case"client_secret_post":eU(a,i,n);return;case"none":tU(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(QE,"applyClientAuthentication");function XE(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(XE,"applyBasicAuth");function eU(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(eU,"applyPostAuth");function tU(e,t){t.set("client_id",e)}o(tU,"applyPublicAuth");async function NS(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=OS.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=MS[a]||Xt;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Xt(a)}}o(NS,"parseErrorResponse");async function Ar(e,t){try{return await Nl(e,t)}catch(r){if(r instanceof en||r instanceof rn)return await e.invalidateCredentials?.("all"),await Nl(e,t);if(r instanceof tn)return await e.invalidateCredentials?.("tokens"),await Nl(e,t);throw r}}o(Ar,"auth");async function Nl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),c,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await DS(d,{fetchFn:i}),!c)try{c=await jS(t,{resourceMetadataUrl:l},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let R=await sU(t,{resourceMetadataUrl:l,fetchFn:i});d=R.authorizationServerUrl,p=R.authorizationServerMetadata,c=R.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await rU(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let R=p?.client_id_metadata_document_supported===!0,q=e.clientMetadataUrl;if(q&&!Dl(q))throw new nn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${q}`);if(R&&q)y={client_id:q},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let qe=await pU(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(qe),y=qe}}let _=!e.redirectUrl;if(r!==void 0||_){let R=await lU(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}let S=await e.tokens();if(S?.refresh_token)try{let R=await dU(d,{metadata:p,clientInformation:y,refreshToken:S.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}catch(R){if(!(!(R instanceof Re)||R instanceof Xt))throw R}let w=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:b}=await cU(d,{metadata:p,clientInformation:y,state:w,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(v),"REDIRECT"}o(Nl,"authInternal");function Dl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Dl,"isHttpsUrl");async function rU(e,t,r){let n=$S(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!zS({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(rU,"selectResourceURL");function Hl(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=jl(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=jl(e,"scope")||void 0,c=jl(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(Hl,"extractWWWAuthenticateParams");function jl(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(jl,"extractFieldFromWwwAuth");async function jS(e,t,r=fetch){let n=await aU(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return ws.parse(await n.json())}o(jS,"discoverOAuthProtectedResourceMetadata");async function Ll(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ll(e,void 0,r):void 0;throw n}}o(Ll,"fetchWithCorsRetry");function nU(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(nU,"buildWellKnownPath");async function qS(e,t,r=fetch){return await Ll(e,{"MCP-Protocol-Version":t},r)}o(qS,"tryMetadataDiscovery");function oU(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(oU,"shouldAttemptFallback");async function aU(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??dr,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=nU(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await qS(s,i,r);if(!n?.metadataUrl&&oU(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await qS(d,i,r)}return c}o(aU,"discoverMetadataWithFallback");function iU(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),n.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(iU,"buildDiscoveryUrls");async function DS(e,{fetchFn:t=fetch,protocolVersion:r=dr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=iU(e);for(let{url:i,type:s}of a){let c=await Ll(i,n,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?sa.parse(await c.json()):vs.parse(await c.json())}}}o(DS,"discoverAuthorizationServerMetadata");async function sU(e,t){let r,n;try{r=await jS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));let a=await DS(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(sU,"discoverOAuthServerInfo");async function cU(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ml))throw new Error(`Incompatible auth server: does not support response type ${Ml}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ql))throw new Error(`Incompatible auth server: does not support code challenge method ${ql}`)}else c=new URL("/authorize",e);let d=await $l(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",Ml),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",ql),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}o(cU,"startAuthorization");function uU(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(uU,"prepareAuthorizationCodeRequest");async function HS(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(d,r,c,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],m=YE(n,l);QE(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await NS(p);return ca.parse(await p.json())}o(HS,"executeTokenRequest");async function dU(e,{metadata:t,clientInformation:r,refreshToken:n,resource:a,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await HS(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(dU,"refreshAuthorization");async function lU(e,t,{metadata:r,resource:n,authorizationCode:a,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=uU(a,p,e.redirectUrl)}let d=await e.clientInformation();return HS(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(lU,"fetchToken");async function pU(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await NS(s);return ua.parse(await s.json())}o(pU,"registerClient");function mU(){let e=lo.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}o(mU,"isTestOnlyAllowHttpLoopbackIdpEnabled");var fU=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),hU=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function LS(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}o(LS,"parseIpv4Octets");function gU([e,t],r){let n=r.firstMax??r.first;return e<r.first||e>n?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}o(gU,"ipv4RangeMatches");function BS(e){let t=LS(e);return t!==void 0&&hU.some(r=>gU(t,r))}o(BS,"isPrivateIpv4");function Bl(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}o(Bl,"parseIpv6Word");function yU(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(yU,"formatIpv4FromWords");function SU(e){let t=e.slice(7),r=LS(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Bl(n),c=Bl(a);return i===void 0&&s!==void 0&&c!==void 0?yU(s,c):void 0}o(SU,"parseIpv6MappedIpv4");function _U(e){return Bl(e.split(":").find(Boolean))}o(_U,"readFirstIpv6Hextet");function wU(e){let t=gt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=SU(t);return n===void 0||BS(n)}let r=_U(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(wU,"isPrivateIpv6");function Gl(e){let t=gt(e);return fU.has(t)||t.endsWith(".internal")||BS(t)||wU(t)}o(Gl,"isBlockedOutboundHostname");function GS(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);let r=Le(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=gt(t.hostname);if(!r&&Gl(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(GS,"validateConfiguredOutboundUrl");function VS(e){let t=new URL(e),r=Le(t),n=r&&mU();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");let a=gt(t.hostname);if(!r&&Gl(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(VS,"validateIdentityProviderUrl");function bs(e){let t=new URL(e);if(t.protocol!=="https:"||t.pathname==="/"||t.username||t.password||t.search||t.hash)throw g("invalid_request","CIMD client_id must be an HTTPS URL with a path and no credentials, query, or fragment.");if(Gl(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(bs,"validateCimdClientMetadataUrl");function FS(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(FS,"mergeAbortSignals");async function vU(e){try{await e.cancel()}catch{}}o(vU,"cancelReader");async function Rs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],a=0,i=await r.read();for(;!i.done;){let d=i.value;if(a+=d.byteLength,a>t.maxBytes)throw await vU(r),t.createLimitError();n.push(d),i=await r.read()}let s=new Uint8Array(a),c=0;for(let d of n)s.set(d,c),c+=d.byteLength;return s}o(Rs,"readBoundedByteStream");var bU=2,RU=1024*1024,CU=1e4,IU=new Set([301,302,303,307,308]),PU=["authorization","proxy-authorization","cookie","cookie2"];function Vl(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Vl,"readRequestUrl");function Kn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Kn,"readRequestMethod");function xU(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(xU,"assertContentLengthWithinLimit");async function AU(e,t,r){return xU(e,t,r),Rs(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(AU,"readBoundedResponseBody");function TU(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(TU,"responseFromBufferedBody");function kU(e,t){if(!IU.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(kU,"resolveRedirectUrl");function ZS(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(ZS,"validateOutboundUrl");function EU(e,t){throw he(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(EU,"normalizeFetchError");function ba(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&Oe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(ba,"logOutboundFailure");async function UU(e,t,r,n,a,i,s){let c=Kn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";ba(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:mt(i),error:d,extra:{abortReason:s()}}),EU(d,a)}}o(UU,"fetchWithNormalizedError");function OU(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(OU,"assertRedirectAllowed");function $U(e,t){let r=new Headers(e);for(let n of PU)r.delete(n);for(let n of t)r.delete(n);return r}o($U,"stripCrossOriginHeaders");function zU(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=$U(e.headers,a)),i}o(zU,"buildRedirectInit");function MU(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(MU,"buildInitialRequestInit");function qU(e){let t=Kn(e.currentInput,e.currentInit);OU({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ZS(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),a=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:zU(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(qU,"followRedirect");async function Fl(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??bU,i=r.maxResponseBytes??RU,s=r.timeoutMs??CU,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=FS(l,t.signal),h=!1,y=setTimeout(()=>{h=!0,l.abort()},s),_=e,S=MU(e,t,l.signal),w;try{w=ZS(Vl(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw ba(p,{event:"outbound_url_blocked",problemCode:n,method:Kn(e,t),host:mt(Vl(e)),error:b}),clearTimeout(y),m?.(),b}let v=0;try{for(;;){let b=await UU(p,c,_,S,n,w,()=>h?`timeout_after_${s}ms`:void 0),R=kU(b,w);if(R!==void 0)try{let q=qU({currentInput:_,currentInit:S,currentUrl:w,redirectUrl:R,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});_=q.currentInput,S=q.currentInit,w=q.currentUrl,v=q.redirects;continue}catch(q){throw ba(p,{event:"outbound_redirect_blocked",problemCode:n,method:Kn(_,S),host:mt(w),error:q,extra:{redirects:v,maxRedirects:a,redirectTargetHost:mt(R)}}),q}try{return TU(b,await AU(b,i,n))}catch(q){throw ba(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Kn(_,S),host:mt(w),error:q,extra:{maxResponseBytes:i,status:b.status}}),q}}}finally{clearTimeout(y),m?.()}}o(Fl,"runSafeOutboundExchange");async function Zl(e,t,r){let n=await Fl(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw ba(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Kn(e,t),host:mt(Vl(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(Zl,"runSafeOutboundJsonExchange");function Cs(e,t={},r={}){return Fl(e,t,{...r,validateUrl:GS})}o(Cs,"fetchConfiguredOutbound");function KS(e,t={},r={}){return Zl(e,t,{...r,validateUrl:VS})}o(KS,"fetchIdentityProviderJson");function WS(e,t={},r={}){return Zl(e,t,{...r,validateUrl:bs})}o(WS,"fetchCimdClientMetadataJson");ie();function Kl(e){return`Zuplo MCP Gateway - ${e}`}o(Kl,"buildGatewayOAuthClientName");function JS(e,t){let r=new URL(e,ce(t));return Le(r)&&gt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(JS,"buildGatewayOAuthRedirectUri");function Wl(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(Wl,"buildOAuthClientMetadataDocumentUrl");function YS(e){return ce(e)}o(YS,"requireOAuthClientMetadataOrigin");function QS(e,t,r){let n=rt(t),a=Qr(t,r);return{client_id:Wl({origin:e,upstreamServerId:t,authProfileId:r}),client_name:Kl(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(QS,"buildOAuthClientMetadataDocument");var NU=u.union([ua,zl]),jU=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:ws.optional(),authorizationServerMetadata:u.union([sa,vs]).optional()}).passthrough(),DU="Bearer";function HU(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(HU,"splitScopes");function LU(e){return rs.parse(e)}o(LU,"parsePkceCodeVerifier");function BU(e){if(typeof e.expires_in=="number")return ne(new Date(Date.now()+e.expires_in*1e3))}o(BU,"readTokenExpiry");async function XS(e){if(e!==void 0)return Xr(JSON.stringify(e))}o(XS,"encryptJson");async function e_(e,t){if(!e)return;let r=await Qt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(e_,"decryptJson");function GU(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}o(GU,"toOAuthDiscoveryState");function VU(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(VU,"clientInformationAllowsRedirectUri");function FU(e,t,r){let n=rt(e),a=Qr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:Kl(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(FU,"buildOAuthClientMetadata");function ZU(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return ua.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(ZU,"buildManualOAuthClientInformation");function KU(e,t,r){let n=Wl({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return Dl(n)?n:void 0}o(KU,"buildClientMetadataUrl");function t_(e){for(let t of e)if(t!==void 0)return t}o(t_,"firstDefined");function WU(e){let t=Qr(e.target.upstreamServerId,e.target.authProfileId),r=FU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:ZU({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=KU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(WU,"buildInitialOAuthClientSetup");function JU(e,t){if(t===void 0)return t_([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(JU,"readEncryptedClientInformation");function YU(e){return t_([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(YU,"readEncryptedDiscoveryState");var on=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=WU({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=JU(t,this.configuredClientInformation),this.encryptedDiscoveryState=YU(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return yS({id:t.id,...aa({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await XS(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await XS(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ca.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0;this.cachedTokens=r,this.tokensLoaded=!0;let a={id:this.connection?.id??ds(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Xr(r.access_token),encryptedRefreshToken:r.refresh_token?await Xr(r.refresh_token):void 0,scopes:HU(r.scope??this.clientMetadataValue.scope),expiresAt:BU(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await J().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:LU(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:sy(),...aa({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:ne(new Date(Date.now()+fS)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await J().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await e_(this.encryptedClientInformation,NU)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!VU(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=GU(await e_(this.encryptedDiscoveryState,jU))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection?.encryptedAccessToken||this.connection.status!=="active")return;let t=ca.parse({access_token:await Qt(this.connection.encryptedAccessToken),token_type:DU,refresh_token:this.connection.encryptedRefreshToken?await Qt(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await J().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var QU=1e4,XU=256*1024,eO=2;function tO(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(tO,"hasUsableAccessToken");var rO="does not support dynamic client registration";function nO(e){return e instanceof Error&&e.message.includes(rO)}o(nO,"isDynamicClientRegistrationUnsupported");function oO(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(oO,"readOAuthFetchRequest");function aO(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(aO,"responseLooksJson");function r_(e){return async(t,r)=>{let n=oO(t),a=await Cs(t,r,{maxRedirects:eO,maxResponseBytes:XU,problemCode:"upstream_token_exchange_failed",timeoutMs:QU}),i=await a.clone().text();if(!aO(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(r_,"createUpstreamOAuthFetch");async function n_(e,t){try{return await Ar(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:r_(t.upstreamServerId)})}catch(r){throw nO(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(n_,"runUpstreamOAuth");async function iO(e,t){return Ar(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:r_(t.upstreamServerId)})}o(iO,"exchangeUpstreamAuthorizationCode");async function o_(e,t){let r=await n_(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(o_,"requireUpstreamAuthorizationRedirect");async function a_(e){if(tO(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await n_(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await lO({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.target.virtualServerId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(a_,"authorizeUpstreamOAuthSession");async function sO(e){let t=await gs(e.stateToken),r=await J().consumeUpstreamOAuthState({id:t.id,now:ne(new Date)}),n=cO(r);return uO({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),dO(n),n}o(sO,"consumeStoredCallbackState");function cO(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(cO,"readConsumedCallbackState");function uO(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(uO,"assertStoredCallbackStateMatches");function dO(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(dO,"assertStoredCallbackStateFresh");async function lO(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),vS(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Vn(t)}o(lO,"buildOAuthConnectRequiredResponse");async function i_(e){let t=await sO({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ln(t),[n]=await J().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new on(a),s=await iO(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(i_,"finishUpstreamOAuthCallback");async function s_(e){let t=rt(e.upstreamServerId),r=Qr(e.upstreamServerId,e.authProfileId),n=JS(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:ce(e.request.url)}}}o(s_,"prepareUpstreamOAuthRequest");async function c_(e){let t=await s_(e),r=new on({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return o_(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(c_,"startUpstreamConnect");async function u_(e){let t=await s_(e),r=new on({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return a_({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(u_,"authorizeUpstreamRequest");function pO(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(pO,"resolveStaticSecretCredential");async function d_(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user_oauth":return u_({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"shared-secret":return xS({owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"static_secret":{let n=Ir({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static_secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:pO(n.secret,t.upstreamServerId)}}case"user-secret":return kS({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(d_,"resolveUpstreamCredentialForRoute");async function l_(e){let t=Cr(e.principal.subjectId),r=ht().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user-secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await _s({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(l_,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function p_(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,virtualServerId:e.connectRequest.virtualServerId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},n=$t(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await c_(r);break;case"user_secret_capture":t=await ES(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(p_,"startUpstreamConnectForRequest");async function m_(e){let r=(await gs(e.callbackRequest.state)).authProfileId,n=Ir({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if($t(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return i_({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:rt(e.callbackRequest.upstreamServerId)})}o(m_,"finishUpstreamCallbackForRequest");var Is=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=mr,n){let a=this._client,i={...n,task:n?.task??(a.isToolTask(t.name)?{}:void 0)},s=a.requestStream({method:"tools/call",params:t},r,i),c=a.getToolOutputValidator(t.name);for await(let d of s){if(d.type==="result"&&c){let p=d.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new A(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(p.structuredContent)try{let l=c(p.structuredContent);if(!l.valid){yield{type:"error",error:new A(U.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof A){yield{type:"error",error:l};return}yield{type:"error",error:new A(U.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield d}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Ps(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let a of Object.keys(n)){let i=n[a];r[a]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[a]=i.default),r[a]!==void 0&&Ps(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ps(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ps(r,t)}}o(Ps,"applyElicitationDefaults");function mO(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}o(mO,"getSupportedElicitationModes");var xs=class extends gn{static{o(this,"Client")}constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new On,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Tc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Pc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",yc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Is(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qa(this._capabilities,t)}setRequestHandler(t,r){let a=ln(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(cr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let c=o(async(d,p)=>{let l=Ge(Uc,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:y}=mO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new A(U.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new A(U.InvalidParams,"Client does not support URL-mode elicitation requests");let _=await Promise.resolve(r(d,p));if(m.task){let b=Ge(Lt,_);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new A(U.InvalidParams,`Invalid task creation result: ${R}`)}return b.data}let S=Ge(fr,_);if(!S.success){let b=S.error instanceof Error?S.error.message:String(S.error);throw new A(U.InvalidParams,`Invalid elicitation result: ${b}`)}let w=S.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&w.action==="accept"&&w.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Ps(v,w.content)}catch{}return w},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ge(Ec,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid sampling request: ${w}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let w=Ge(Lt,h);if(!w.success){let v=w.error instanceof Error?w.error.message:String(w.error);throw new A(U.InvalidParams,`Invalid task creation result: ${v}`)}return w.data}let _=m.tools||m.toolChoice?vo:zr,S=Ge(_,h);if(!S.success){let w=S.error instanceof Error?S.error.message:String(S.error);throw new A(U.InvalidParams,`Invalid sampling result: ${w}`)}return S.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:dr,capabilities:this._capabilities,clientInfo:this._clientInfo}},uc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!lr.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Mi(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&qi(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Ht,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Oc,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Ht,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Ic,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},_c,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},pc,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},mc,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},gc,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Ht,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Ht,r)}async callTool(t,r=mr,n){if(this.isToolTaskRequired(t.name))throw new A(U.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let a=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!a.structuredContent&&!a.isError)throw new A(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(a.structuredContent)try{let s=i(a.structuredContent);if(!s.valid)throw new A(U.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof A?s:new A(U.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return a}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let a=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},Ac,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=dm.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:c}=i.data,{onChanged:d}=n,p=o(async()=>{if(!s){d(null,null);return}try{let m=await a();d(null,m)}catch(m){let h=m instanceof Error?m:new Error(String(m));d(h,null)}},"refresh"),l=o(()=>{if(c){let m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);let h=setTimeout(p,c);this._listChangedDebounceTimers.set(t,h)}else p()},"handler");this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function As(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(As,"normalizeHeaders");function f_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...As(t.headers),...As(n.headers)}:t.headers};return e(r,a)}:e}o(f_,"createFetchWithInit");var Ts=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function Jl(e){}o(Jl,"noop");function h_(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Jl,onError:r=Jl,onRetry:n=Jl,onComment:a}=e,i="",s=!0,c,d="",p="";function l(S){let w=s?S.replace(/^\xEF\xBB\xBF/,""):S,[v,b]=fO(`${i}${w}`);for(let R of v)m(R);i=b,s=!1}o(l,"feed");function m(S){if(S===""){y();return}if(S.startsWith(":")){a&&a(S.slice(S.startsWith(": ")?2:1));return}let w=S.indexOf(":");if(w!==-1){let v=S.slice(0,w),b=S[w+1]===" "?2:1,R=S.slice(w+b);h(v,R,S);return}h(S,"",S)}o(m,"parseLine");function h(S,w,v){switch(S){case"event":p=w;break;case"data":d=`${d}${w}
48
+ `;break;case"id":c=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new Ts(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:v}));break;default:r(new Ts(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:w,line:v}));break}}o(h,"processField");function y(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
49
+ `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(y,"dispatchEvent");function _(S={}){i&&S.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(_,"reset"),{feed:l,reset:_}}o(h_,"createParser");function fO(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
50
+ `,n),s=-1;if(a!==-1&&i!==-1?s=Math.min(a,i):a!==-1?a===e.length-1?s=-1:s=a:i!==-1&&(s=i),s===-1){r=e.slice(n);break}else{let c=e.slice(n,s);t.push(c),n=s+1,e[n-1]==="\r"&&e[n]===`
51
+ `&&n++}}return[t,r]}o(fO,"splitLines");var ks=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=h_({onEvent:o(s=>{i.enqueue(s)},"onEvent"),onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:r,onComment:n})},transform(i){a.feed(i)}})}};var hO={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Tr=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Es=class{static{o(this,"StreamableHTTPClientTransport")}constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=f_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??hO}async _authThenStart(){if(!this._authProvider)throw new er("No auth provider");let t;try{t=await Ar(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new er;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=As(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let a=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Tr(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),a)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},a)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:a,replayMessageId:i}=r,s,c=!1,d=!1;o(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new ks({onRetry:o(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:_}=await l.read();if(_)break;if(y.id&&(s=y.id,c=!0,a?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let S=$r.parse(JSON.parse(y.data));St(S)&&(d=!0,i!==void 0&&(S.id=i)),this.onmessage?.(S)}catch(S){this.onerror?.(S)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}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 er("No auth provider");if(await Ar(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new er("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:It(t)?t.id:void 0}).catch(h=>this.onerror?.(h));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),d=c.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!c.ok){let h=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Tr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:_}=Hl(c);if(this._resourceMetadataUrl=y,this._scope=_,await Ar(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new er;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:_,error:S}=Hl(c);if(S==="insufficient_scope"){let w=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Tr(403,"Server returned 403 after trying upscoping");if(_&&(this._scope=_),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=w??void 0,await Ar(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new er;return this.send(t)}}throw new Tr(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),nm(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let l=(Array.isArray(t)?t:[t]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,m=c.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let h=await c.json(),y=Array.isArray(h)?h.map(_=>$r.parse(_)):[$r.parse(h)];for(let _ of y)this.onmessage?.(_)}else throw await c.body?.cancel(),new Tr(-1,`Unexpected content type: ${m}`);else await c.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Tr(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function g_(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(g_,"resolveNativeMcpRequestHeaders");var gO={name:"zuplo-mcp-gateway",version:"0.1.0"},yO=new zn({draft:"7",shortcircuit:!1}),SO=5,_O=500,__=3e4,wO=2*1024*1024,vO=2;function y_(){return performance.now()/1e3}o(y_,"nowSeconds");function bO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(bO,"readServerPort");function RO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:bO(e)}}o(RO,"buildNativeMcpOperationContext");function Wn(e){return Mg(e)}o(Wn,"withTraceMeta");function Yl(e){if(e>_O)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Yl,"assertImportedCapabilityBudget");function S_(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(S_,"buildRequestInit");function CO(e){return(t,r)=>Cs(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:vO,maxResponseBytes:wO,problemCode:"upstream_capability_invocation_failed",timeoutMs:__})}o(CO,"createNativeMcpFetch");function IO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},__);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(IO,"withNativeMcpRequestTimeout");function PO(e,t=[]){let r=g_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:CO(a)};if(!e)return{...i,...S_(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...S_(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(PO,"buildNativeMcpTransportOptions");async function Jn(e,t,r){let{transport:n}=rt(e),a=new URL(n.baseUrl),i=new Es(a,PO(r,n.requestHeaders)),s=new xs(gO,{capabilities:{},jsonSchemaValidator:yO});return IO((async()=>{let c=y_();await s.connect(i);let d=i.sessionId,p=RO(a,d);try{return await t(s,p)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&qg(p,y_()-c)}})())}o(Jn,"withNativeMcpClient");async function xO(e,t,r){let n=[],a,i=0;do{if(i>=SO)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(xO,"collectPaginatedSdkItems");async function Ql(e){return e.enabled?xO(e.label,e.fetchPage,e.readItems):[]}o(Ql,"listNativeMcpCapabilityItems");async function w_(e){return Jn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"tools/list",...r},()=>Ql({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(Wn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Yl(a.length),{tools:a}},e.credential)}o(w_,"listNativeMcpTools");async function v_(e){return Jn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"prompts/list",...r},()=>Ql({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(Wn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Yl(a.length),{prompts:a}},e.credential)}o(v_,"listNativeMcpPrompts");async function b_(e){return Jn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"resources/list",...r},()=>Ql({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(Wn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Yl(a.length),{resources:a}},e.credential)}o(b_,"listNativeMcpResources");async function R_(e){return Jn(e.upstreamServerId,(t,r)=>Zr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(Wn(e.params))),e.credential)}o(R_,"callNativeMcpTool");async function C_(e){return Jn(e.upstreamServerId,(t,r)=>Zr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(Wn(e.params))),e.credential)}o(C_,"getNativeMcpPrompt");async function I_(e){return Jn(e.upstreamServerId,(t,r)=>Zr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(Wn(e.params))),e.credential)}o(I_,"readNativeMcpResource");var Ra=class extends A{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(U.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function AO(e){return{content:[{type:"text",text:e}],isError:!0}}o(AO,"buildToolErrorResult");function TO(e){return e.authUrl?new ur([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new Ra(e)}o(TO,"toConnectRequiredError");function kO(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(kO,"buildCredentialResolvedAttributes");function EO(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:kO(e.credential)})}o(EO,"emitCredentialResolvedAnalyticsEvent");function UO(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}o(UO,"emitCredentialMissingAnalyticsEvent");function OO(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Jr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(OO,"readRouteBindingCredentialCacheKey");function x_(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(x_,"readOwnedRouteBindingLookup");async function $O(e){let t=bl(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=x_(s);c!==void 0&&r.set(Jr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await J().authorizeAndLoadConnections({accessTokenHash:await pe(t),resource:Wr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:ne(new Date)});if(a.kind!=="authorized")return new Map;let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(Jr(d),s.connection)}),i}o($O,"preloadCompositeAuthorizedConnections");function zO(e){let t=new Map;return r=>{let n=OO(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=x_(r),d=c===void 0?void 0:Jr(c),p=await d_({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw UO({context:e.context,payload:p.payload,routeBinding:r}),TO(p.payload);return EO({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(zO,"createCredentialResolver");var P_=500;function MO(e){return e.length<=P_?e:`${e.slice(0,P_)}...`}o(MO,"truncateAnalyticsDetail");function qO(e){tt(e.context,{eventType:K.MCP_GATEWAY_CAPABILITY_COMPLETED,outcome:e.result.isError===!0?"application_error":"success",routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",toolResultIsError:e.result.isError===!0,applicationError:e.result.isError===!0})}o(qO,"emitToolInvocationCompletedAnalyticsEvent");function NO(e){return e instanceof ur||e instanceof Ra?{eventType:K.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof A&&e.code===U.InvalidParams?{eventType:K.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:K.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(NO,"classifyToolInvocationFailure");function jO(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=NO(e.error);tt(e.context,{eventType:r.eventType,outcome:r.outcome,routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",reasonCode:r.reasonCode,reasonClass:r.reasonClass,errorType:r.errorType,mcpErrorType:r.mcpErrorType,attributes:{detail:MO(t)}})}o(jO,"emitToolInvocationFailedAnalyticsEvent");var DO=256*1024;function HO(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new A(U.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>DO)throw new A(U.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(HO,"assertToolArgumentsWithinLimit");function Xl(e){if(e.routeBindings.length===1)return e.routeBindings[0];let t=e.routeBindings.filter(r=>r.connectionPolicyName===e.upstreamPolicyName);if(t.length!==1)throw new A(U.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(Xl,"findBindingForPublishedCapability");function Yn(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new A(U.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(Yn,"requireSingleTransparentBinding");function LO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Yn(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Xl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(LO,"resolvePublishedToolRoute");function BO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Yn(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Xl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(BO,"resolvePublishedPromptRoute");function GO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Yn(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Xl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(GO,"resolvePublishedResourceRoute");function A_(e){let t=$O({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=zO({context:e.context,preloadedConnections:t,request:e.request});return{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{tools:e.publishedVirtualServer.catalog.tools.filter(a=>a.enabled!==!1).map(Wi)};let n=Yn(e);return w_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async callTool(n){let a=LO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:n.name});try{HO(n);let i=await r(a.binding),s=await R_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:i});return qO({context:e.context,routeBinding:a.binding,toolName:n.name,result:s}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,isError:s.isError===!0},"Upstream tool invocation completed"),s}catch(i){if(jO({context:e.context,routeBinding:a.binding,toolName:n.name,error:i}),i instanceof ur||i instanceof Ra)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:n.name,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,ownerMode:a.binding.ownerMode,hasAuthUrl:i instanceof ur},"Upstream tool invocation requires user to complete a connect flow"),i;let s={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId};return i instanceof A&&(s.mcpErrorCode=i.code),i instanceof Error?(s.errorName=i.name,s.errorMessage=i.message,i.cause instanceof Error&&(s.causeName=i.cause.name,s.causeMessage=i.cause.message)):s.errorMessage=String(i),e.context.log.warn(s,"Upstream tool invocation failed; returning generic gateway error to MCP client"),AO(Qe("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{prompts:e.publishedVirtualServer.catalog.prompts.filter(a=>a.enabled!==!1).map(Ji)};let n=Yn(e);return v_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async getPrompt(n){let a=BO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:n.name});return C_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:await r(a.binding)})},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resources:e.publishedVirtualServer.catalog.resources.filter(a=>a.enabled!==!1).map(Yi)};let n=Yn(e);return b_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async readResource(n){let a=GO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:n.uri});return I_({upstreamServerId:a.binding.upstreamServerId,params:{...n,uri:a.upstreamUri},credential:await r(a.binding)})}}}o(A_,"createCapabilityDispatcher");var VO="0.1.0",k_="POST",FO="POST, OPTIONS",ZO=new zn({draft:"7",shortcircuit:!1});function ep(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:k_}})}o(ep,"jsonRpcMethodNotAllowedResponse");function KO(e){let t={Allow:k_},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=FO;let a=e.headers.get("access-control-request-headers");a&&(t["Access-Control-Allow-Headers"]=a)}return new Response(null,{status:204,headers:t})}o(KO,"buildOptionsResponse");function Qn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(Qn,"readJsonRpcRequestId");function tp(e){return e&&typeof e=="object"?e.params:void 0}o(tp,"readMcpRequestParams");function T_(e,t){return e.headers.get(t)??void 0}o(T_,"readMcpHeader");function WO(e){return{mcpProtocolVersion:T_(e,"mcp-protocol-version")??Fr,mcpSessionId:T_(e,"mcp-session-id")}}o(WO,"buildServerTelemetryBase");function JO(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Fr),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(JO,"ensureProtocolVersionHeader");async function rp(e,t){if(e.method==="OPTIONS")return KO(e);if(e.method==="GET")return ep("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return ep("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return ep("Only POST is supported by this virtual MCP server.");let r=Nn(t),n=Rg(r.virtualServerId),a=jg(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=WO(e),s=A_({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=ce(e.url),d=new ji({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new Ni(n.catalog.serverInfo??{name:r.virtualServerId,version:VO},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:ZO});p.setRequestHandler(xc,async m=>Kr({methodName:"tools/list",params:tp(m),jsonRpcRequestId:Qn(m),...i},()=>s.listTools())),p.setRequestHandler(_o,async m=>Kr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Qn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(Sc,async m=>Kr({methodName:"prompts/list",params:tp(m),jsonRpcRequestId:Qn(m),...i},()=>s.listPrompts())),p.setRequestHandler(wc,async m=>Kr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Qn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(lc,async m=>Kr({methodName:"resources/list",params:tp(m),jsonRpcRequestId:Qn(m),...i},()=>s.listResources())),p.setRequestHandler(hc,async m=>Kr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:Qn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return JO(l)}o(rp,"virtualServerHandler");async function YO(e,t){return sr("handler.mcp-virtual-server"),rp(e,t)}o(YO,"McpVirtualServerHandler");var Xn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},QO="oauth-protected-resource-metadata",XO="/.well-known/oauth-protected-resource/";function e$(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(e$,"readRouteOperationId");function t$(e){return e.hasGatewayRouteContext?Xn.VIRTUAL_MCP_SERVER:e.routeOperationId===QO||e.routeOperationId===void 0&&e.routePath.startsWith(XO)?Xn.OAUTH_PROTECTED_RESOURCE_METADATA:Xn.OTHER}o(t$,"classifyAnalyticsRouteSurface");function r$(e){let t=e.route.path;return{routePath:t,routeSurface:t$({routePath:t,routeOperationId:e$(e),hasGatewayRouteContext:ea(e)!==void 0})}}o(r$,"readAnalyticsRequestContext");function n$(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Xn.VIRTUAL_MCP_SERVER}o(n$,"isIntentionalMethodRejection");function o$(e){return n$(e)||e.response.status===401&&e.routeSurface===Xn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(o$,"classifyRequestCompletedOutcome");async function np(e,t){let r=Date.now(),n=r$(t);return t.addResponseSendingFinalHook(a=>{let i=o$({response:a,routeSurface:n.routeSurface});tt(t,{eventType:K.MCP_GATEWAY_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(np,"analyticsContextInbound");function a$(e){return e instanceof Response}o(a$,"isResponse");var E_="/mcp/";function i$(e){let t=e.route.path;if(!t.startsWith(E_))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(E_.length);if(!r||r.includes("/"))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(i$,"readVirtualServerIdFromRoute");async function Ca(e,t){let n={virtualServerId:Pe.parse(i$(t))};Pg(t,n),ig(t,n);let a=await np(e,t);return a$(a)?a:Rl(a,t)}o(Ca,"mcpOAuthInboundPolicy");var s$=o(async(e,t,r,n)=>(sr("policy.inbound.mcp-auth0-oauth"),Ca(e,t)),"McpAuth0OAuthInboundPolicy");function c$(e){let t=`https://${e.auth0Domain}/`,r=`https://${e.auth0Domain}/.well-known/jwks.json`,n=`https://${e.auth0Domain}/authorize`,a=`https://${e.auth0Domain}/oauth/token`;return es({oidc:{issuer:t,jwksUrl:r,audience:e.audience},browserLogin:{url:n,tokenUrl:a,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",audience:e.audience,...e.browserLoginOverrides??{}},gateway:e.gateway})}o(c$,"buildAuth0McpOAuthRuntimeConfig");var u$={policyType:"mcp-auth0-oauth-inbound",displayName:"MCP OAuth (Auth0)",getConfig(e){return c$(e)}};Vi(u$);var d$=o(async(e,t,r,n)=>(sr("policy.inbound.mcp-oauth"),Ca(e,t)),"McpOAuthInboundPolicy"),l$={policyType:"mcp-oauth-inbound",displayName:"MCP OAuth",getConfig(e){return es(e)}};Vi(l$);function p$(e){let t=$t(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,virtualServerId:e.virtualServerId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.config.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}o(p$,"buildRouteAuthBaseFromConnection");function O_(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=$t(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:qn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(O_,"buildRouteAuthBaseFromPolicyOptions");function $_(e,t){let n=ht().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return p$({connection:a,virtualServerId:t})}o($_,"resolveRouteAuthBase");function U_(e,t){switch(e){case"user":return Cr(t.subjectId);case"shared":return us()}}o(U_,"buildOwnerForPrincipal");function Us(e,t){switch(e.ownerMode){case"shared":return{...e,owner:U_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:U_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Us,"resolveRouteAuthForPrincipal");function m$(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Bi.parse(r)}o(m$,"readSingleAuthMode");function z_(e){return Ot.parse(e)}o(z_,"buildToolNamePrefixFromConnectionId");async function op(e,t,r,n){let a=Ki(r,n),i=m$({policyName:n,connection:a}),s=Nn(t),c=O_({connection:a,virtualServerId:s.virtualServerId,authMode:i});if(c.ownerMode==="none")return Wd(t,{...c,connectionPolicyName:n,toolNamePrefix:z_(a.id)}),e;let d=Xg(t);return Wd(t,{...Us(c,d),connectionPolicyName:n,toolNamePrefix:z_(a.id)}),e}o(op,"mcpUpstreamConnectionPolicy");var f$=o(async(e,t,r,n)=>(sr("policy.inbound.mcp-upstream-connection"),op(e,t,r,n)),"McpUpstreamConnectionInboundPolicy");ie();ie();var M_="application/json",h$="application/x-www-form-urlencoded";function g$(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(g$,"normalizeContentType");function y$(e,t){return e===t?!0:t===M_&&e.endsWith("+json")}o(y$,"contentTypeMatches");function S$(e,t){if(!t||t.length===0)return;let r=g$(e.headers.get("content-type"));if(!t.some(n=>y$(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(S$,"assertExpectedContentType");function _$(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(_$,"assertContentLengthWithinLimit");async function q_(e,t){let r=t.label??"Request body";S$(e,t.expectedContentTypes),_$(e,t.maxBytes,r);let n=await Rs(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(q_,"readBoundedTextBody");async function N_(e,t){let r=await q_(e,{...t,expectedContentTypes:[M_]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(N_,"readBoundedJsonBody");async function Os(e,t){let r=await q_(e,{...t,expectedContentTypes:[h$]});return new URLSearchParams(r)}o(Os,"readBoundedFormUrlEncodedBody");var j_=Symbol("Html");function w$(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(w$,"escapeHtml");function v$(e){return e===null||typeof e!="object"?!1:e[j_]===!0}o(v$,"isHtml");function D_(e){return e==null||e===!1?"":Array.isArray(e)?e.map(D_).join(""):v$(e)?e.value:w$(String(e))}o(D_,"renderValue");function tr(e){return{[j_]:!0,value:e}}o(tr,"trustedHtml");var _e=tr("");function k(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=D_(t[n]),r+=e[n+1]??"";return tr(r)}o(k,"html");function rr(e){return e.value}o(rr,"renderHtml");var nr=tr('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;padding:9px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function or(e){return k`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" type="image/png" href="https://www.google.com/s2/favicons?domain=${e.host}&sz=64" /><style>
52
+ ${e.styles}
53
+ </style></head><body><main class="card"><header class="card__head"><img class="card__icon" src="https://www.google.com/s2/favicons?domain=${e.host}&sz=64" alt="" width="48" height="48" referrerpolicy="no-referrer" /><h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(or,"renderShell");function H_(e){return k`<form class="actions" method="post" action="/oauth/setup"><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(H_,"renderActions");var L_=tr('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function B_(){return k`<p>The API key could not be verified. Start the authorization flow again to try
54
+ once more.</p>`}o(B_,"renderApiKeyLoginFailure");function G_(e){return k`<form class="form" method="post" action="/oauth/api-key-login" autocomplete="off" ><input type="hidden" name="state" value="${e.state}" /><label class="form__label" for="apiKey">API key</label><input class="form__input" id="apiKey" name="apiKey" type="password" required autocomplete="off" /><button class="button button--primary button--block form__submit" type="submit" >Continue</button></form>`}o(G_,"renderApiKeyLoginForm");function V_(e){return k`<div class="banner banner--alert" role="alert"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">${e.title}</p><p class="banner__message">${e.message}</p></div></div>`}o(V_,"renderBannerAlert");function F_(e){return k`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(F_,"renderBannerWarning");function Z_(e){return k`<section class="capability-section"><h4 class="capability-section__title">${e.label} <span class="muted">(${e.total})</span></h4><ul class="capability-list">${e.rows}${e.moreLine}</ul></section>`}o(Z_,"renderCapabilitySection");var ap=tr('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),ip=tr('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');function K_(e){return k`${e.banner}<section class="upstreams"><header class="section-label">Upstream services <span class="section-label__count">${e.sectionCount}</span></header><ul class="upstream-list">${e.cards}</ul></section>${e.fineprint}`}o(K_,"renderSetupPage");function W_(e){return k`<article class="${e.cardClass}"><div class="upstream-card__head">${e.iconFrame}<div class="upstream-card__main"><div class="upstream-card__title-row"><h3 class="upstream-card__title">${e.upstreamDisplayName}</h3>${e.control}</div><div class="upstream-card__meta">${e.host}<span>${e.authModeLabel}</span><span class="upstream-card__sep" aria-hidden="true">·</span><span>${e.ownerModeLabel}</span></div>${e.description}</div></div>${e.capabilities} ${e.scopes}</article>`}o(W_,"renderUpstreamCard");var J_=tr('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var b$="text/html; charset=utf-8";function Y_(e,t=200){return new Response(rr(e),{status:t,headers:{"content-type":b$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Y_,"apiKeyLoginHtmlResponse");function sp(e,t=401){return Y_(or({title:"Sign-in failed",host:e,styles:nr,heading:"Sign-in failed",subhead:"",body:B_(),footer:""}),t)}o(sp,"apiKeyLoginFailureResponse");function Q_(e,t){return Y_(or({title:"Sign in",host:e,styles:nr,heading:"Sign in",subhead:k`<p class="card__subtitle">Enter your API key to continue.</p>`,body:G_({state:t}),footer:""}))}o(Q_,"renderApiKeyLoginForm");ie();ie();import{errors as uw,jwtVerify as dw,SignJWT as lw}from"jose";ie();import{errors as $$,jwtVerify as z$,SignJWT as M$}from"jose";function kr(e){let t=xe().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(kr,"requireBrowserLoginField");ie();import{createRemoteJWKSet as C$,errors as Ia,jwtVerify as I$}from"jose";var P$=u.object({id_token:u.string().min(1),token_type:u.string().min(1).optional(),expires_in:u.number().optional(),access_token:u.string().min(1).optional(),refresh_token:u.string().min(1).optional(),scope:u.string().min(1).optional()}),x$=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function A$(e){let t=x$.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(A$,"readIdpErrorFields");function T$(e){return e instanceof Ia.JWTExpired?"expired":e instanceof Ia.JWTClaimValidationFailed?"claim":e instanceof Ia.JWSSignatureVerificationFailed?"signature":e instanceof Ia.JWKSNoMatchingKey?"jwks_no_match":e instanceof Ia.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(T$,"readJwtFailureKind");var k$=u.object({sub:Se,nonce:u.string().min(1)}).catchall(u.unknown()),cp;function E$(e){return e instanceof Error&&"cause"in e?e.cause:e}o(E$,"readErrorCause");function U$(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(U$,"readRuntimeGatewayCode");function O$(){if(!cp){let e=xe();cp=C$(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return cp}o(O$,"readFederatedJwks");async function X_(e){let t=xe(),r=kr("tokenUrl"),n=kr("clientId"),a=kr("clientSecret"),i=new URL("/oauth/callback",Ct(e.requestUrl)).toString(),s=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:a});try{let{response:c,json:d}=await KS(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:s},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!c.ok){let h=A$(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:mt(r),idpStatus:c.status,...h},"Federated browser login token exchange returned non-2xx from the identity provider"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${h.idpError?` idp_error=${h.idpError}`:""}${h.idpErrorDescription?` idp_error_description=${h.idpErrorDescription}`:""})`)})}let p=P$.parse(d),l;try{({payload:l}=await I$(p.id_token,O$(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let y={};throw Oe(y,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:T$(h),idpHost:mt(r),expectedIssuer:t.oidc.issuer,...y},"Federated id_token failed jose verification"),h}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:mt(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=k$.parse(l);return jn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=he(c)??U$(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",E$(c))}}o(X_,"exchangeFederatedAuthorizationCode");var dp="zuplo_mcp_session",ew="HS256",tw="zuplo-mcp-gateway",rw="zuplo-mcp-gateway",q$=u.object({purpose:u.literal("gateway_browser_session"),sub:Se,browserLoginOrigin:u.string().min(1),roles:u.array(u.string().min(1)).optional(),exp:u.number().int().positive(),iat:u.number().int().positive().optional()});function N$(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let a=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}o(N$,"parseCookieHeader");async function nw(){return zt({purpose:"browser-session",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>Pr(e,"browser-session"),"derive")})}o(nw,"getBrowserSessionKey");function up(e){let t=new URL(ce(e)),r=[`${dp}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(up,"buildBrowserSessionEvictionCookie");function j$(e){let t=new URL(ce(e.requestUrl)),r=[`${dp}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(j$,"serializeSessionCookie");function ow(e={}){return new URL(kr("url")).origin}o(ow,"readBrowserLoginOrigin");function lp(){return xe().browserLogin.stateTtlSeconds}o(lp,"readBrowserLoginStateTtlSeconds");function aw(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return jn(e.user,e.url)}o(aw,"resolveCurrentRequestPrincipal");async function $s(e,t={}){let r=N$(e.headers.get("cookie")).get(dp);if(!r)return{};try{let{payload:n}=await z$(r,await nw(),{algorithms:[ew],issuer:tw,audience:rw}),a=q$.parse(n);if(a.browserLoginOrigin!==ow(t))return{evictCookie:up(e.url)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof $$.JWTExpired?{evictCookie:up(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:up(e.url)})}}o($s,"readBrowserSession");async function Pa(e){let t=xe().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:ow({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new M$(r).setProtectedHeader({alg:ew,typ:"JWT"}).setIssuer(tw).setAudience(rw).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await nw());return j$({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(Pa,"createBrowserSessionCookie");async function iw(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(iw,"resolveApiKeyBrowserLoginPrincipal");async function sw(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await $s(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return X_({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(sw,"resolveBrowserLoginCallbackPrincipal");function cw(e){let t=xe().browserLogin,r=new URL(kr("url")),n=new URL("/oauth/callback",Ct(e.requestUrl));return Vg(r)?(r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",kr("clientId")),r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}o(cw,"buildBrowserLoginUrl");var D$={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},G=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=D$[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var H$=5*60,zs="HS256",Ms="zuplo-mcp-gateway",qs="zuplo-mcp-gateway",L$=u.object({purpose:u.literal("gateway_browser_login"),transactionId:yt,stateId:os,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),B$=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:yt,stateId:os,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function pw(){return zt({purpose:"browser-login",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>Pr(e,"browser-login"),"derive")})}o(pw,"getBrowserLoginKey");async function mw(){return zt({purpose:"authorization-csrf",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>Pr(e,"authorization-csrf"),"derive")})}o(mw,"getCsrfKey");function fw(e){return{now:e.now??new Date,ttlSeconds:lp()}}o(fw,"readPendingTransactionDependencies");function G$(e,t){return e.subjectId===t.subjectId}o(G$,"principalsMatch");function hw(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(hw,"toPendingPrincipal");function gw(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:ne(e.now),expiresAt:ne(Jt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:hw(e.principal)}}o(gw,"createTransactionRecord");async function yw(e){let{id:t,...r}=e.record,n=await J().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new G("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new G("invalid_request","redirect_uri is not registered for the client.")}}o(yw,"startPendingTransaction");async function V$(e){return new lw({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:zs,typ:"JWT"}).setIssuer(Ms).setAudience(qs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await pw())}o(V$,"signBrowserLoginState");async function Sw(e){return new lw({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:nl()}).setProtectedHeader({alg:zs,typ:"JWT"}).setIssuer(Ms).setAudience(qs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await mw())}o(Sw,"signCsrfToken");async function Ns(e){try{let{payload:t}=await dw(e,await pw(),{algorithms:[zs],issuer:Ms,audience:qs}),r=L$.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof uw.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Ns,"verifyBrowserLoginStateToken");async function pp(e){try{let{payload:t}=await dw(e,await mw(),{algorithms:[zs],issuer:Ms,audience:qs});return{transactionId:B$.parse(t).transactionId}}catch(t){throw t instanceof uw.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(pp,"verifyCsrfToken");function js(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(js,"pendingStateErrorCode");function _w(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(_w,"toPendingAuthorizationGetResult");function F$(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(F$,"toPendingAuthorizationAdvanceResult");function ww(e){return e==="principal_mismatch"?"oauth_callback_mismatch":js(e==="consumed_already"?"consumed_already":e)}o(ww,"setupDecisionErrorCode");function Z$(e){if(e.kind!=="available")throw g(js(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(Z$,"requireAwaitingSetup");function K$(e){if(e.kind!=="available")throw g(js(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(K$,"requireAwaitingLogin");function W$(e){if(!G$(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(W$,"requireCurrentPrincipalMatches");async function vw(e){let t=e.now??new Date,r=lp(),n=rl(),a=nl(),i=await V$({transactionId:n,stateId:a,ttlSeconds:r}),s=gw({id:n,transaction:e.transaction,currentStateHash:await pe(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await yw({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:cw({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(vw,"startAwaitingLogin");async function bw(e){let{now:t,ttlSeconds:r}=fw(e),n=rl(),a=await Sw({transactionId:n,ttlSeconds:r}),i=gw({id:n,transaction:e.transaction,currentStateHash:await pe(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await yw({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(bw,"startAwaitingSetup");async function mp(e){let{now:t,ttlSeconds:r}=fw(e),n=await Ns(e.browserLoginStateToken),a=await Sw({transactionId:n.transactionId,ttlSeconds:r}),i=F$(await J().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await pe(e.browserLoginStateToken),nextStateHash:await pe(a),nextPhase:"awaiting_setup",principal:hw(e.principal),now:ne(t)}));if(i.kind!=="advanced")throw g(js(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(mp,"completeLogin");async function Rw(e){let t=e.now??new Date,r=await Ns(e.browserLoginStateToken);return K$(_w(await J().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await pe(e.browserLoginStateToken),now:ne(t)})))}o(Rw,"getAwaitingLogin");async function Cw(e){let t=await fp(e);return W$({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(Cw,"getSetup");async function fp(e){let t=e.now??new Date,r=await pp(e.csrfToken);return Z$(_w(await J().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await pe(e.csrfToken),now:ne(t)})))}o(fp,"getSetupTransaction");async function J$(e){let t=await pp(e.csrfToken),r=Yt(),n=ne(Jt(e.now,H$)),a=await J().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await pe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await pe(r),authorizationCodeExpiresAt:n,grantId:Bg(),now:ne(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":ww(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}o(J$,"createAuthorizationCodeRedirectWithDecision");async function Y$(e){let t=await pp(e.csrfToken),r=await J().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await pe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:ne(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":ww(r.kind),"Authorization setup state is invalid, expired, or already used.");return Q$({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(Y$,"createCancelRedirectWithDecision");function Q$(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}o(Q$,"buildClientCancelRedirect");async function Iw(e){let t=e.now??new Date;return J$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Iw,"approve");async function Pw(e){let t=e.now??new Date;return Y$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Pw,"cancel");ie();var X$=1e4,ez=5*1024,tz=2,rz=90*24*60*60,hp=["authorization_code","refresh_token"],gp=["code"],nz=u.object({client_name:u.string().min(1).optional(),redirect_uris:u.array(u.string().min(1)).min(1),grant_types:u.array(u.enum(hp)).min(1).max(2).optional(),response_types:u.array(u.enum(gp)).min(1).max(1).optional(),scope:u.literal(ye).optional(),token_endpoint_auth_method:Qd.default("client_secret_basic")});function oz(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(oz,"isCimdClientIdCandidate");function xa(e,t="invalid_request"){if(az(e))throw new G(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new G(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new G(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||Le(r)))throw new G(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(xa,"assertValidRedirectUri");function az(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(az,"hasForbiddenRawRedirectUriCharacter");async function iz(e){let{response:t,json:r}=await WS(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:tz,maxResponseBytes:ez,timeoutMs:X$});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=Lg.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");if(n.token_endpoint_auth_method!=="none")throw g("invalid_request","CIMD clients must use token_endpoint_auth_method none until private_key_jwt is implemented.");return n}o(iz,"fetchCimdMetadata");async function sz(e){let t=bs(e),r=await iz({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(sz,"resolveCimdClient");async function xw(e,t){let r=Be.parse(e);if(oz(r)){if(!xe().gateway.cimdEnabled)throw new G("invalid_client","OAuth client is not registered.");try{return await sz(r)}catch{throw new G("invalid_client","OAuth client is not registered.")}}let n=await J().readClient({clientId:r});if(n.kind==="found"){let a=n.client,i={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new G("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(xw,"resolveClient");function Aw(e,t){if(!e.metadata.redirect_uris.some(r=>Gg(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(Aw,"assertRedirectRegistered");function cz(e){let t=Tw(e.grant_types),r=e.response_types??[...gp];if(!uz(t))throw new G("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!dz(r))throw new G("invalid_client_metadata","response_types must be code.");if(!lz(e.scope))throw new G("invalid_client_metadata",`Only the ${ye} scope is supported.`)}o(cz,"assertSupportedDcrRequest");function Tw(e){return e===void 0?[...hp]:Array.from(new Set(e))}o(Tw,"normalizeGrantTypes");function uz(e){return e.length===0?!1:e.every(t=>hp.includes(t))}o(uz,"isSupportedGrantTypes");function dz(e){return e.length===gp.length&&e[0]==="code"}o(dz,"isSupportedResponseTypes");function lz(e){return e===void 0||e===ye}o(lz,"isSupportedDcrScope");function Aa(e){if(e===void 0||e===ye)return ye;throw new G("invalid_request",`Only the ${ye} scope is supported.`)}o(Aa,"assertSupportedOAuthScope");function eo(e,t){let r;try{r=new URL(t)}catch{throw new G("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new G("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Le(r))throw new G("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ce(e),a=Cg(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new G("invalid_target","resource must match a published virtual MCP server.");return i}o(eo,"resolveResource");async function kw(e){let t;try{t=nz.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new G(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}cz(t);for(let l of t.redirect_uris)xa(l,"invalid_redirect_uri");let r=new Date,n=Be.parse(`dcr:${crypto.randomUUID()}`),a=Jt(r,rz),i=Math.floor(r.getTime()/1e3),s=Math.floor(a.getTime()/1e3),c={client_id:n,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:Tw(t.grant_types),response_types:["code"],scope:ye,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:i},d={clientId:n,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:ne(r),clientExpiresAt:ne(a)};if(t.token_endpoint_auth_method!=="none"){let l=Yt();d.hashedClientSecret=await pe(l),d.clientSecretExpiresAt=ne(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await J().registerClient(d)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}o(kw,"registerDownstreamClient");function pz(e){try{return new URL(e).host}catch{return""}}o(pz,"safeHostFromOrigin");var mz=8;function Sp(e){let t=e.trim();try{let r=new URL(t);if(r.protocol==="https:")return r.toString()}catch{}if(/^data:image\/(?:png|jpe?g|webp);/i.test(t))return t}o(Sp,"safeIconSrc");function fz(e,t){if(e)try{let r=new URL(t).origin,n=new URL(e,r);return n.origin!==r||!n.pathname.startsWith("/auth/connections/")?void 0:n.toString()}catch{return}}o(fz,"safeGatewayConnectHref");function hz(e){if(e==="any")return Number.POSITIVE_INFINITY;let t=/^(\d+)x(\d+)$/.exec(e);return t?Math.max(Number(t[1]),Number(t[2])):0}o(hz,"parseIconSize");function gz(e,t){let r=e.filter(a=>a.theme===t);if(r.length>0)return r;let n=e.filter(a=>a.theme===void 0);return n.length>0?n:e}o(gz,"selectIconCandidates");function yz(e){return Sp(e.src)?e.sizes&&e.sizes.length>0?Math.max(...e.sizes.map(hz)):0:-1}o(yz,"readIconScore");function Ew(e,t){if(!e||e.length===0)return;let r=gz(e,t),n,a=-1;for(let i of r){let s=yz(i);s>a&&(n=i,a=s)}return n}o(Ew,"pickIcon");function Sz(e,t){let r=Ew(e,"light");if(!r)return k`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ip}</span>`;let n=Sp(r.src);return n?k`<span class="icon-frame"><img src="${n}" alt="${t}" loading="lazy" decoding="async"></span>`:k`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ip}</span>`}o(Sz,"renderIconFrame");function Hs(e,t){let r=Ew(e,"light");if(!r)return _e;let n=Sp(r.src);return n?k`<img class="inline-icon" src="${n}" alt="${t}" loading="lazy" decoding="async">`:_e}o(Hs,"renderInlineIcon");function _z(e){switch(e){case"user":return"your account";case"shared":return"shared by your team";case"none":return"gateway-managed"}}o(_z,"ownerModeLabel");function wz(e){return e.endsWith("_oauth")||e==="oauth"?"OAuth":e.includes("static_secret")?"static credential":e.replaceAll("_"," ")}o(wz,"authModeLabel");function vz(e){switch(e){case"active":return k`<span class="status-badge status-badge--success">Connected</span>`;case"not_connected":return k`<span class="status-badge status-badge--neutral">Not connected</span>`;case"reconsent_required":return k`<span class="status-badge status-badge--warning">Reconnect required</span>`}}o(vz,"statusBadge");function bz(e){if(!e)return _e;let t=[];return e.destructiveHint&&t.push(k`<span class="badge badge--destructive" title="This tool may modify or delete data on your behalf.">destructive</span>`),e.readOnlyHint&&t.push(k`<span class="badge badge--muted" title="This tool only reads data and does not modify state.">read-only</span>`),e.openWorldHint&&t.push(k`<span class="badge badge--muted" title="This tool can access arbitrary URIs supplied at call time.">open-world</span>`),t.length>0?k`<span class="badge-row">${t}</span>`:_e}o(bz,"annotationBadges");function Uw(e){let t=0,r=0;for(let n of e.tools)n.annotations?.destructiveHint===!0&&(t+=1),n.annotations?.readOnlyHint===!0&&(r+=1);return{tools:e.tools.length,prompts:e.prompts.length,resources:e.resources.length,destructiveTools:t,readOnlyTools:r}}o(Uw,"summarizeCapabilities");function Rz(e){let t=e.annotations?.title??e.title??e.name,r=e.description?k`<span class="capability-row__description">${e.description}</span>`:_e;return k`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${bz(e.annotations)}${r}</li>`}o(Rz,"renderToolRow");function Cz(e){let t=e.title??e.name,r=e.description?k`<span class="capability-row__description">${e.description}</span>`:_e;return k`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${r}</li>`}o(Cz,"renderPromptRow");function Iz(e){let t=e.title??e.name,r=e.mimeType===void 0?_e:k` · ${e.mimeType}`,n=e.description===void 0?_e:k` — ${e.description}`,a=k`<span class="capability-row__description"><code>${e.uri}</code>${r}${n}</span>`;return k`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${a}</li>`}o(Iz,"renderResourceRow");function yp(e,t,r,n){if(t===0)return _e;let a=r.slice(0,mz),i=t-a.length,s=i>0?k`<li class="capability-row capability-row--more">+ ${i} more</li>`:_e;return Z_({label:e,total:t,rows:k`${a.map(n)}`,moreLine:s})}o(yp,"renderCapabilitySection");function Ds(e,t,r=!1){return r?k`<span class="count-pill count-pill--destructive"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`:k`<span class="count-pill"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`}o(Ds,"countPill");function Pz(e){let t=Uw(e);if(t.tools+t.prompts+t.resources===0)return k`<div class="upstream-card__capabilities upstream-card__capabilities--empty">No tools, prompts, or resources advertised.</div>`;let n=[];t.tools>0&&n.push(Ds(t.tools===1?"tool":"tools",t.tools)),t.prompts>0&&n.push(Ds(t.prompts===1?"prompt":"prompts",t.prompts)),t.resources>0&&n.push(Ds(t.resources===1?"resource":"resources",t.resources)),t.destructiveTools>0&&n.push(Ds("destructive",t.destructiveTools,!0));let a=[yp("Tools",t.tools,e.tools,Rz),yp("Prompts",t.prompts,e.prompts,Cz),yp("Resources",t.resources,e.resources,Iz)];return k`<details class="upstream-card__capabilities"><summary class="capabilities-summary"><span class="capabilities-summary__counts">${n}</span><span class="capabilities-summary__chevron" aria-hidden="true">${ap}</span></summary><div class="capabilities-detail">${a}</div></details>`}o(Pz,"renderUpstreamCapabilities");function xz(e){if(!e||e.length===0)return _e;let t=e.map(n=>k`<code class="scope-chip">${n}</code>`),r=e.length===1?"scope":"scopes";return k`<details class="upstream-card__scopes"><summary class="scopes-summary"><span>Requested ${r} <span class="muted">(${e.length})</span></span><span class="capabilities-summary__chevron" aria-hidden="true">${ap}</span></summary><div class="scopes-list">${t}</div></details>`}o(xz,"renderUpstreamScopes");function Az(e,t){if(e.ownerMode!=="user")return _e;let r=fz(e.connectUrl,t);if(!r)return _e;let n=e.status==="active"?"Redo auth":e.status==="reconsent_required"?"Reconnect":"Connect",a=e.status==="active"?"Reconnect this upstream account or approve updated scopes.":void 0;return k`<a class="button button--secondary button--small" href="${r}"${a===void 0?_e:k` title="${a}"`}>${n}</a>`}o(Az,"renderActionButton");function Tz(e,t){let r=Az(e,t);return rr(r)!==""?r:vz(e.status)}o(Tz,"renderUpstreamControl");function kz(e,t){let n=e.ownerMode==="user"&&e.status!=="active"?"upstream-card upstream-card--needs-action":"upstream-card",a=e.description?k`<p class="upstream-card__description">${e.description}</p>`:_e,i=e.transportHost?k`<code class="upstream-card__host">${e.transportHost}</code><span class="upstream-card__sep" aria-hidden="true">·</span>`:_e;return W_({cardClass:n,iconFrame:Sz(e.serverIcons,e.upstreamDisplayName),upstreamDisplayName:e.upstreamDisplayName,control:Tz(e,t),host:i,authModeLabel:wz(e.authMode),ownerModeLabel:_z(e.ownerMode),description:a,capabilities:Pz(e.capabilities),scopes:xz(e.scopesRequested)})}o(kz,"renderUpstreamCard");function Ez(e){return e.reduce((t,r)=>{let n=Uw(r.capabilities);return t.tools+=n.tools,t.prompts+=n.prompts,t.resources+=n.resources,t.destructiveTools+=n.destructiveTools,t.readOnlyTools+=n.readOnlyTools,t},{tools:0,prompts:0,resources:0,destructiveTools:0,readOnlyTools:0})}o(Ez,"aggregateCapabilities");function Uz(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Uz,"deriveMode");function Oz(e){if(e.mode==="setup"){let n=e.upstreams.filter(c=>c.ownerMode==="user"&&c.status!=="active"),a=n.length>0&&n.every(c=>c.status==="reconsent_required"),i=n.length===1?"the service":`the ${n.length} services`,s=a?k`Re-authorize ${i} below to refresh access. Authorization will continue automatically once each is ready.`:k`Connect ${i} below before continuing. Authorization will continue automatically once each is ready.`;return F_({icon:J_,message:s})}let t=Ez(e.upstreams);if(t.destructiveTools===0)return _e;let r=t.destructiveTools===1?"tool can":"tools can";return V_({icon:L_,title:k`${t.destructiveTools} ${r} modify or delete data`,message:k`Review the destructive tools below before authorizing <strong>${e.clientDisplayName}</strong>.`})}o(Oz,"renderBanner");function $z(e){let t=e.mode==="setup"?k`disabled aria-disabled="true" title="Connect the required upstream services first"`:_e;return H_({state:e.state,authorizeAttrs:t})}o($z,"renderActions");function _p(e){let t=Uz(e.upstreams),r=[...e.upstreams].sort((h,y)=>{let _=o(w=>w.ownerMode!=="user"?2:w.status==="active"?1:0,"blockedRank"),S=_(h)-_(y);return S!==0?S:h.upstreamDisplayName.localeCompare(y.upstreamDisplayName)}),n=Hs(e.virtualServerIcons,e.virtualServerDisplayName),a=Oz({mode:t,upstreams:r,clientDisplayName:e.clientDisplayName}),i=r.length===0?k`<li class="empty">This virtual server does not declare any upstream services.</li>`:k`${r.map(h=>k`<li>${kz(h,e.gatewayOrigin)}</li>`)}`,s=$z({mode:t,state:e.state}),c=t==="grant"?k`<p class="card__fineprint"><strong>${e.clientDisplayName}</strong> will receive a token scoped to <strong>${e.virtualServerDisplayName}</strong>. You can revoke access at any time.</p>`:k`<p class="card__fineprint">Authorization continues automatically once every required service is connected.</p>`,d=r.length>0?k`(${r.length})`:_e,p=k`<p class="card__subtitle"><strong>${e.clientDisplayName}</strong> wants to access <strong>${n}${e.virtualServerDisplayName}</strong></p>${e.virtualServerDescription?k`<p class="card__description">${e.virtualServerDescription}</p>`:_e}${e.principalLabel?k`<span class="card__principal" title="Signed in as ${e.principalLabel}">${e.principalLabel}</span>`:_e}`,l=K_({banner:a,sectionCount:d,cards:i,fineprint:c}),m=k`<footer class="card__footer">${s}</footer>`;return rr(or({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,host:pz(e.gatewayOrigin),styles:nr,heading:"Authorize access",subhead:p,body:l,footer:m}))}o(_p,"renderConsentPage");function zz(e){try{return new URL(e).host}catch{return}}o(zz,"safeUrlHost");function Mz(e){if(e.mode==="user_oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(Mz,"readOAuthScopes");function wp(e){return e!==void 0&&e.length>0}o(wp,"hasItems");function qz(e){let t=e.registeredConnection.config.serverInfo?.icons;if(wp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&wp(r)?r:void 0}o(qz,"readServerIcons");async function Nz(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Pl({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(Nz,"readConnectUrl");function an(e,t){return t===void 0?{}:{[e]:t}}o(an,"optionalRequirementField");function jz(e){return e.isUserOwned?iy(e.connection):{connected:!0,status:"active"}}o(jz,"readSetupConnectionStatus");function Dz(e){let t=Mz(e);return wp(t)?t:void 0}o(Dz,"readScopesRequested");function Hz(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(Hz,"readUpdatedAt");function Lz(e){if(e.virtualServer.catalog.catalogSource!=="openapi")return{tools:[],prompts:[],resources:[]};let t=o(r=>r.upstreamPolicyName===e.registeredConnection.policyName,"ownsCapability");return{tools:e.virtualServer.catalog.tools.filter(r=>r.enabled!==!1&&t(r)).map(Wi),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(Ji),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Yi)}}o(Lz,"readVirtualServerCapabilities");async function Bz(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=ps(r),c=s==="user",d=jz({connection:e.connection,isUserOwned:c}),p=await Nz({...e,connected:d.connected,isUserOwned:c});return{upstreamServerId:a,authProfileId:i,authMode:r,ownerMode:s,upstreamDisplayName:n.displayName,status:d.status,connected:d.connected,capabilities:Lz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...an("description",n.description),...an("transportHost",zz(n.transport.baseUrl)),...an("scopesRequested",Dz(t)),...an("serverIcons",qz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...an("connectUrl",p),...an("updatedAt",Hz({connectionStatus:d,isUserOwned:c})),...an("expiresAt",e.connection?.expiresAt)}}o(Bz,"buildSetupRequirement");function Ow(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(Ow,"requireVirtualServer");async function vp(e){let t=Ow(e.transaction.virtualServerId),r=Cr(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)ps(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await J().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=ps(c.authMode)==="user",p=a.get(c);s.push(await Bz({connection:d&&p!==void 0?i[p]:void 0,registeredConnection:c,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(vp,"requirementsForSetup");function Gz(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(Gz,"readVirtualServerDisplayName");async function bp(e){let t=Ow(e.transaction.virtualServerId),r=Gz({virtualServer:t}),n=await J().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:ce(e.requestUrl),virtualServerDisplayName:r,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.serverInfo?.title;return s!==void 0&&s!==r&&(i.virtualServerDescription=s),i}o(bp,"consentContext");function $w(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o($w,"hasUnresolvedUserUpstream");var Vz=["mcp_user"],Fz="dev-browser-user",Zz=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/mcp/{virtualServerId} or add resource={protected resource URI from protected-resource metadata}."].join(" "),Kz=u.object({response_type:u.literal("code"),client_id:u.string().min(1),redirect_uri:u.string().min(1),resource:u.url(),code_challenge:u.string().min(43),code_challenge_method:ts,state:u.string().min(1).optional(),scope:u.literal(ye).default(ye)}),Wz=u.enum(["continue","approve","cancel"]).default("continue"),Jz=u.object({state:u.string().min(1),decision:Wz}),Yz=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),sn=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function zw(e){return typeof e=="string"&&e.length>0?e:void 0}o(zw,"readQueryString");function Qz(e,t){let r=zw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new G("invalid_target",Zz)}let n=Wr(t,e.url);if(r===void 0||r===n)return n;throw new G("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(Qz,"requireAuthorizeResource");async function Xz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await $s(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=aw(e);return{principal:i,setCookie:await Pa({principal:i,requestUrl:e.url,virtualServerId:t})}}o(Xz,"resolveBrowserPrincipal");async function eM(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await $s(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(eM,"requireSetupPrincipal");async function Mw(e){let t=await vp({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await bp({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:_p({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(Mw,"renderSetup");function tM(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new G("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(tM,"toAuthorizationTransactionClient");async function Rp(e,t={}){let r=Kz.parse({...e.query,resource:Qz(e,t.virtualServerId),state:zw(e.query.state)}),n=Aa(r.scope);xa(r.redirect_uri);let a=new Date,i=Be.parse(r.client_id),s=await xw(r.client_id,a);Aw(s,r.redirect_uri);try{let c=eo(e.url,r.resource),d=tM(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,virtualServerId:c.virtualServerId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved");let p={clientId:s?.clientId??i,...d===void 0?{}:{client:d},redirectUri:r.redirect_uri,resource:r.resource,virtualServerId:c.virtualServerId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:l,setCookie:m}=await Xz(e,c.virtualServerId,t.context);if(!l){let y=await vw({transaction:p,requestUrl:e.url,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,virtualServerId:c.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let _={kind:"redirect",location:y.browserLoginUrl};return m!==void 0&&(_.setCookie=m),_}let h=await bw({transaction:p,principal:l,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,virtualServerId:c.virtualServerId,subjectId:l.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),Mw({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw rM({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Rp,"authorizeDownstreamClient");function rM(e){if(e.cause instanceof sn)return e.cause;let t=nM(e.cause);return t?new sn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(rM,"toDownstreamAuthorizeRedirectError");function nM(e){if(e instanceof G)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof u.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(nM,"mapToOAuthRedirectError");async function qw(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,l=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...l===void 0?{}:{idpErrorUri:l}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",p??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await Ns(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await sw(i),c=await mp({browserLoginStateToken:n,principal:s}),d=await Mw({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await Pa({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(qw,"completeBrowserLoginCallback");async function Nw(e){let t=xe(),r=new URL(e.url);if(!Le(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",ce(e.url)),i=new URL(ce(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:Se.parse(Fz),roles:Vz};return{kind:"redirect",location:a,setCookie:await Pa({principal:s,requestUrl:e.url})}}o(Nw,"completeLocalDevBrowserLogin");async function jw(e){let t=Yz.parse(e.body),r=await Rw({browserLoginStateToken:t.state}),n=await iw({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await mp({browserLoginStateToken:t.state,principal:n});await l_({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",Ct(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await Pa({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(jw,"completeApiKeyBrowserLogin");function oM(e){let t=e.method==="POST"?e.body:e.query;return Jz.parse(t)}o(oM,"readSetupContinueRequest");async function Dw(e){let{state:t,decision:r}=oM({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await fp({csrfToken:t,now:n}),i=await eM(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await Pw({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await Cw({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await vp({transaction:s,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||$w(c)){let d=await bp({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:_p({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await Iw({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(Dw,"continueDownstreamAuthorizeSetup");ie();var aM=new Set(["authorization_code","refresh_token"]),iM=u.discriminatedUnion("grant_type",[u.object({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),client_id:u.string().min(1).optional(),code_verifier:rs,resource:u.url(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()}),u.object({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),client_id:u.string().min(1).optional(),resource:u.url(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()})]);function sM(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!aM.has(t)))throw new G("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(sM,"assertSupportedGrantType");var cM=u.object({token:u.string().min(1),client_id:u.string().min(1).optional(),token_type_hint:u.string().optional(),client_secret:u.string().min(1).optional()});function Hw(){return xe().gateway.accessTokenTtlSeconds}o(Hw,"readAccessTokenTtlSeconds");function uM(){return xe().gateway.refreshTokenTtlSeconds}o(uM,"readRefreshTokenTtlSeconds");function dM(e,t){let r=Hw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:ne(Jt(e,a)),expiresIn:a}}o(dM,"calculateAccessTokenExpiresAt");function Lw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new G("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new G("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new G("invalid_client","Malformed HTTP Basic client authentication.")}}o(Lw,"readBasicClientSecret");function Bw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new G("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new G("invalid_client","Client authentication or client_id is required.");return t}o(Bw,"resolveAuthenticatedClientId");function Gw(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new G("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(Gw,"resolveClientSecretInput");async function Vw(e){let t=Be.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await pe(e.clientSecret)}}o(Vw,"buildRuntimeHttpClientAuth");async function Fw(e){sM(e.body);let t=iM.parse(e.body),r=Lw(e.authorizationHeader),n=Bw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=new Date,i=Gw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});return lM({parsed:t,clientId:n,clientSecretInput:i,now:a,requestUrl:e.requestUrl})}o(Fw,"exchangeDownstreamToken");async function lM(e){let t=await Vw({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){xa(e.parsed.redirect_uri),Aa(e.parsed.scope),e.parsed.resource!==void 0&&eo(e.requestUrl??e.parsed.resource,e.parsed.resource);let c=Yt(),d=Yt(),p=ne(Jt(e.now,uM())),l=dM(e.now,p),m=await J().exchangeAuthorizationCode({clientAuth:t,codeHash:await pe(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Jg(e.parsed.code_verifier),currentRefreshTokenHash:await pe(c),accessTokenHash:await pe(d),grantExpiresAt:p,accessTokenExpiresAt:l.expiresAt,now:ne(e.now)});if(m.kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new G("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new G("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return{access_token:d,token_type:"Bearer",expires_in:l.expiresIn,refresh_token:c,scope:m.grant.scope,resource:m.grant.resource}}Aa(e.parsed.scope),e.parsed.resource!==void 0&&eo(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=Yt(),n=Yt(),a=ne(Jt(e.now,Hw())),i=await J().refreshToken({clientAuth:t,currentRefreshTokenHash:await pe(e.parsed.refresh_token),nextRefreshTokenHash:await pe(r),accessTokenHash:await pe(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:ne(e.now)});if(i.kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new G("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new G("invalid_grant","Refresh token is invalid, expired, or revoked.");eo(e.requestUrl??i.grant.resource,i.grant.resource);let s=i.accessToken.expiresAt;return{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(lM,"exchangeDownstreamTokenWithRuntimeHttp");async function Zw(e){let t=cM.parse(e.body),r=Lw(e.authorizationHeader),n=Bw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=Gw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret}),i=new Date;if((await J().revokeOAuthToken({clientAuth:await Vw({clientId:n,...a}),tokenHash:await pe(t.token),now:ne(i)})).kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed")}o(Zw,"revokeDownstreamToken");var pM=64*1024,mM=16*1024,fM="text/html; charset=utf-8";function hM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(hM,"formDataToObject");async function gM(e){return N_(e,{maxBytes:pM,label:"Request body"})}o(gM,"readJsonBody");async function Ls(e){return hM(await Os(e,{maxBytes:mM,label:"Request body"}))}o(Ls,"readFormBody");async function Bs(e,t,r){let n=he(r),a=r instanceof u.ZodError?Kw(r):r instanceof Error?r.message:void 0,i={code:n??"invalid_request"};return a!==void 0&&(i.detail=a),ft(e,t,i)}o(Bs,"handleProblem");function Ta(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Ta,"oauthErrorResponse");function yM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(yM,"readOAuthProtocolHeaders");function SM(e,t){let r=Qe("internal_server_error");return Ta({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:yM(e,t)})}o(SM,"oauthProtocolErrorResponse");function _M(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(_M,"readZodOAuthErrorCode");function wM(e){let t={error:_M(e)},r=Kw(e);return r!==void 0&&(t.errorDescription=r),Ta(t)}o(wM,"oauthZodErrorResponse");function vM(e){let t=he(e);if(t===void 0)return;let r=Qe(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:RM(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ta(n)}o(vM,"oauthGatewayProblemResponse");function bM(){let t={error:"server_error",status:500,errorDescription:Qe("internal_server_error").publicDetail};return Ta(t)}o(bM,"oauthFallbackErrorResponse");function RM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(RM,"readOAuthStatus");function to(e,t={}){return e instanceof sn?CM(e):e instanceof G?SM(e,t):e instanceof u.ZodError?wM(e):vM(e)??bM()}o(to,"oauthProblemResponse");function Mt(e,t,r){let n={event:t},a=!1;if(r instanceof G)n.oauthError=r.errorCode,n.status=r.status,Oe(n,"error",r);else if(r instanceof sn)n.oauthError=r.errorCode,Oe(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Oe(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=he(r);if(i!==void 0){let s=Qe(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Oe(n,"error",r)}else a=!0,Oe(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Mt,"logUnexpectedOAuthHandlerError");function CM(e){let t;try{t=new URL(e.redirectUri)}catch{return Ta({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(CM,"downstreamAuthorizeRedirectErrorResponse");function Kw(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Kw,"formatZodErrorDetail");function IM(e,t){let r={event:"browser_login_callback_failed",code:he(t)??"invalid_request"};Oe(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(IM,"logBrowserLoginCallbackFailure");function Cp(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}o(Cp,"redirectResultResponse");function Gs(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":fM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Cp(e)}o(Gs,"authorizeResultResponse");async function Ww(e,t){try{return Response.json(al(e.url))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Bs(e,t,r)}}o(Ww,"authorizationServerMetadataHandler");async function Jw(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=Xo(r);return Response.json(Fg({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Bs(e,t,r)}}o(Jw,"scopedAuthorizationServerMetadataHandler");async function Yw(e,t){try{let r=await kw(await gM(e)),n=r;return t.log.info({event:"oauth_dcr_client_registered",clientId:typeof n.client_id=="string"?n.client_id:void 0,clientName:typeof n.client_name=="string"?n.client_name:void 0,redirectUriCount:Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,tokenEndpointAuthMethod:typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0},"OAuth Dynamic Client Registration completed"),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_register_failed",r),to(r)}}o(Yw,"registerHandler");async function Qw(e,t){try{return Gs(await Rp(e,{context:t}))}catch(r){return Mt(t,"oauth_authorize_failed",r),to(r,{includeInvalidClientChallenge:!1})}}o(Qw,"authorizeHandler");async function Xw(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=Xo(r);return Gs(await Rp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Mt(t,"oauth_authorize_scoped_failed",r),to(r,{includeInvalidClientChallenge:!1})}}o(Xw,"scopedAuthorizeHandler");async function ev(e,t){try{let r=await qw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Gs(r)}catch(r){return IM(t,r),Bs(e,t,r)}}o(ev,"callbackHandler");async function tv(e,t){try{return Cp(await Nw(e))}catch(r){return Mt(t,"oauth_dev_login_failed",r),to(r)}}o(tv,"devLoginHandler");async function rv(e,t){let r=(()=>{try{return new URL(e.url).host}catch{return""}})();try{if(e.method==="GET"){let n=typeof e.query.state=="string"?e.query.state:void 0;return n?Q_(r,n):sp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Cp(await jw({request:e,body:await Ls(e)}))}catch(n){return Mt(t,"oauth_api_key_login_failed",n),sp(r)}}o(rv,"apiKeyLoginHandler");async function nv(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Dw({request:e,body:e.method==="POST"?await Ls(e):void 0,context:t});return Gs(r)}catch(r){return Mt(t,"oauth_setup_failed",r),Bs(e,t,r)}}o(nv,"setupHandler");async function ov(e,t){try{return Response.json(await Fw({body:await Ls(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Mt(t,"oauth_token_failed",r),to(r)}}o(ov,"tokenHandler");async function av(e,t){try{return await Zw({body:await Ls(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_revoke_failed",r),to(r)}}o(av,"revokeHandler");var PM={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},iv=new Dt("upstream-request");function xM(e){let t=iv.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(xM,"readUpstreamRequestContext");function AM(e,t){return t.some(r=>r===e)}o(AM,"requestContextMatchesKind");function TM(e){return typeof e=="string"?[e]:e}o(TM,"toExpectedKinds");function cn(e,t){iv.set(e,t)}o(cn,"setUpstreamRequestContext");function un(e,t){let r=xM(e),n=TM(t);if(!AM(r.kind,n)){let a=PM[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(un,"requireUpstreamRequestContext");function sv(e){return k`<form class="form" method="post" action="${e.action}" autocomplete="off"><input type="hidden" name="browserTicket" value="${e.browserTicket}" />${e.fields}<p class="form__note">The gateway stores this encrypted and keeps it out of MCP client
55
+ configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(sv,"renderAppPassword");function cv(e){return k`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(cv,"renderBrowserResult");var kM="text/html; charset=utf-8",EM="none";function uv(e){return or({title:e.title,host:e.host,styles:nr,heading:e.title,subhead:"",body:cv({body:e.body,code:e.code??EM}),footer:""})}o(uv,"browserResultHtml");function dv(e,t=200){return new Response(rr(e),{status:t,headers:{"content-type":kM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(dv,"browserResultResponse");function Vs(e){return dv(uv(e))}o(Vs,"browserConnectionSuccessResponse");function ro(e,t){let r=ug(t);return dv(uv({host:e,title:r.title,body:r.body,code:t}),400)}o(ro,"browserConnectionFailureResponse");function Ip(e){try{return new URL(e).host}catch{return""}}o(Ip,"safeHostFromUrl");var UM="text/html; charset=utf-8",OM=16*1024;function $M(e,t=200){return new Response(rr(e),{status:t,headers:{"content-type":UM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o($M,"htmlResponse");function zM(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(zM,"safeRedirect");function MM(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(MM,"requireBrowserTicket");function qM(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(qM,"appPasswordTicketMatchesTarget");async function lv(e){let t=MM(e.browserTicket),r=await ys(t);if(!qM(r,e))throw g("oauth_callback_mismatch","App password capture ticket did not match the requested upstream flow.");return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(lv,"readAppPasswordTarget");function NM(e,t){let r=Ul(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=r.kind==="basic_auth_app_password"?k`<label class="form__label" for="username">${r.usernameLabel}</label><input class="form__input" id="username" name="username" required autocomplete="username"><label class="form__label" for="appPassword">${r.passwordLabel}</label><input class="form__input" id="appPassword" name="appPassword" type="password" required autocomplete="current-password">`:k`<label class="form__label" for="token">${r.label}</label><input class="form__input" id="token" name="token" type="password" required autocomplete="off">`;return $M(or({title:"Connect upstream",host:t,styles:nr,heading:"Connect upstream",subhead:k`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:sv({action:n,browserTicket:e.browserTicket,fields:a}),footer:""}))}o(NM,"renderCaptureForm");function Fs(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw g("invalid_request",`Missing form field: ${t}`);return r}o(Fs,"readRequiredFormValue");function jM(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(jM,"readCaptureFormTargetInput");async function DM(e,t){return NM(await lv(jM(e)),t)}o(DM,"handleCaptureFormRequest");async function HM(e){let t=await Os(e.request,{maxBytes:OM,label:"App password request body"});return{form:t,target:await lv({upstreamServerId:e.upstreamServerId,browserTicket:Fs(t,"browserTicket")})}}o(HM,"readSubmittedAppPasswordTarget");async function LM(e){let t=Ln(e.target.ticket);if(await Ss(e.target.ticket),Ul(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await _s({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:Fs(e.form,"token")});return}await TS({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:Fs(e.form,"username"),appPassword:Fs(e.form,"appPassword")})}o(LM,"saveSubmittedAppPasswordCredential");function BM(e,t){return t.ticket.returnTo?zM(e,t.ticket.returnTo):Vs({host:Ip(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(BM,"appPasswordSuccessResponse");async function GM(e){let t=await HM({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await LM(t),BM(e.request.url,t.target)}o(GM,"handleAppPasswordSubmission");function VM(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(VM,"methodNotAllowedResponse");function FM(e,t){let r=he(t);return ro(e,Hi(r)?r:"oauth_state_invalid")}o(FM,"appPasswordFailureResponse");async function ZM(e){let t=Ip(e.request.url);switch(e.request.method){case"GET":return DM(e.appPasswordRequest,t);case"POST":return GM(e);default:return VM()}}o(ZM,"handleAppPasswordMethod");async function Pp(e,t){let r=un(t,"app_password");try{return await ZM({request:e,appPasswordRequest:r})}catch(n){return FM(Ip(e.url),n)}}o(Pp,"appPasswordHandler");var KM=["callback_authorization_code","callback_provider_error","callback_invalid"];function WM(e){return"cause"in e?e.cause:void 0}o(WM,"readErrorCause");function JM(e){return e.stack?.split(`
56
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(JM,"readFirstStackFrame");function pv(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=JM(r))}o(pv,"addErrorAttributes");function mv(e){try{return new URL(e).host}catch{return""}}o(mv,"safeHostFromUrl");function YM(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),ro(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),ro(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(YM,"requireAuthorizationCallbackRequest");function QM(e,t){tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(QM,"emitCallbackReceivedAnalyticsEvent");function XM(e,t){tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(XM,"emitTokenExchangeSucceededAnalyticsEvent");function eq(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Vs({host:mv(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(eq,"buildSuccessfulCallbackResponse");function tq(e){let t={detail:e instanceof Error?e.message:void 0};return pv(t,"error",e),e instanceof Error&&pv(t,"cause",WM(e)),t}o(tq,"buildTokenExchangeFailureAttributes");function rq(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:he(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:tq(e.error)})}o(rq,"emitTokenExchangeFailedAnalyticsEvent");function nq(e,t){let r=he(t);return ro(e,Hi(r)?r:"upstream_token_exchange_failed")}o(nq,"tokenExchangeFailureResponse");async function xp(e,t){let r=un(t,KM),n=mv(e.url),a=YM(t,r,n);if(a instanceof Response)return a;QM(t,a);try{let i=await m_({request:e,callbackRequest:a});return XM(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,virtualServerId:i.virtualServerId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),eq(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:he(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Oe(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),rq({context:t,callbackRequest:a,error:i}),nq(n,i)}}o(xp,"callbackHandler");function oq(e){let t=he(e);return t==="unknown_upstream_server"?t:"not_found"}o(oq,"clientMetadataProblemCode");function aq(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(aq,"clientMetadataProblemDetail");async function fv(e,t){let r=un(t,"connect"),n=await p_({request:e,connectRequest:r});if(tt(t,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:n.virtualServerId,upstreamServerTitle:n.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,virtualServerId:n.virtualServerId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(n.authUrl,302);let a=await Vn({requestUrl:e.url,owner:n.owner,initiatedBySubjectId:n.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,upstreamDisplayName:n.upstreamDisplayName,virtualServerId:n.virtualServerId,subject:"virtual server",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}o(fv,"connectHandler");async function hv(e,t){let r=un(t,"client_metadata");try{let n=YS(e.url),a=QS(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=oq(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),ft(e,t,{code:a,detail:aq(n)})}}o(hv,"oauthClientMetadataHandler");function ar(e){if(typeof e=="string"&&e.length!==0)return e}o(ar,"readOptionalQueryString");function iq(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(iq,"requirePathString");function gv(e){let t=ar(e);return t?Pe.parse(t):void 0}o(gv,"readOptionalVirtualServerId");function sq(e,t){let r=ar(e);return r?et.parse(r):qn(t,"user_oauth")}o(sq,"readOptionalAuthProfileId");function cq(e){let t=gv(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(cq,"readRequiredVirtualServerId");function uq(e){let t=ar(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(uq,"readOptionalBrowserTicket");function dq(e){let t=cs(ar(e));return t===void 0?{}:{returnTo:t}}o(dq,"readOptionalReturnTo");function lq(e){let t=gv(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(lq,"readOptionalVirtualServerIdContext");function pq(e){let t=ar(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(pq,"readOptionalProviderErrorDescription");function mq(e){let t=$t(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(mq,"requireConnectableRouteAuth");function fq(e,t,r,n){let a=Us(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(fq,"buildConnectContextForPrincipal");function hq(e,t,r){let n=Ln(t),a=$t(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(hq,"buildConnectContextForTicket");async function gq(e,t){let r=mq($_(t,cq(e.query.virtualServerId))),n=e.query.redirect==="true",a=ar(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=jn(e.user,e.url);return fq(r,s,n,dq(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await ys(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await Ss(i),hq(r,i,n)}o(gq,"resolveConnectContext");async function yq(e,t,r){let n=Xe.parse(iq(e,"connection"));switch(r){case"connect":cn(t,await gq(e,n));return;case"app_password":cn(t,{kind:"app_password",upstreamServerId:n,...lq(e),...uq(e)});return;case"callback":{let a=ar(e.query.error);if(a){cn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...pq(e)});return}let i=ar(e.query.code),s=ar(e.query.state);if(i&&s){cn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}cn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":cn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:sq(e.query.authProfileId,n)});return}}o(yq,"resolveUpstreamRequestInbound");async function Sq(e,t,r){try{await yq(e,t,r);return}catch(n){let a=he(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return ft(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(Sq,"applyUpstreamRequestContext");function ka(e,t){return o(async(n,a)=>{let i=await Sq(n,a,e);return i||t(n,a)},"wrapped")}o(ka,"withUpstreamRequestContext");var _q={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function wq(){return new Response(null,{status:204,headers:_q})}o(wq,"buildWellKnownPreflightResponse");function vq(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(vq,"withWellKnownCorsHeaders");function Ap(e){return async(t,r)=>t.method==="OPTIONS"?wq():vq(await e(t,r))}o(Ap,"wrapWellKnownHandler");var bq=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Ap(Ww)},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Ap(Jw)},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Ap(Zg)},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:Yw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:Qw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:Xw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:ev},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:tv},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:rv},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:nv},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:ov},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:av},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ka("client_metadata",hv)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ka("connect",fv)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ka("callback",xp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:ka("app_password",Pp)}];function yv(e){if(e)return e.find(t=>Fi(t.policyType))}o(yv,"findMcpOAuthPolicy");function Sv(e){return yv(e)!==void 0}o(Sv,"shouldRegisterMcpGatewayInternalRoutes");function Rq(e){let t=Md(e.policyType);if(!t){let r=qd();throw new jt(`MCP gateway: unknown MCP authorization policy type '${String(e.policyType)}'. Registered policy types: ${r.length>0?r.join(", "):"<none>"}.`)}try{return t.getConfig(e.handler.options)}catch(r){throw r instanceof u.ZodError?new jt(Cq(e.name??e.policyType,r),{cause:r}):r}}o(Rq,"resolveOAuthConfigFromPolicy");function Cq(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
1409
57
  `);return`MCP OAuth policy "${e}" is misconfigured. Missing/invalid options:
1410
- ${r}`}o(UM,"formatPolicyConfigError");function Lv(e){let t=Mv(e.policies);if(!t){let r=Qd(),n=r.length>0?`Add one of [${r.map(a=>`\`${a}\``).join(", ")}] and reference it on your MCP routes.`:"Register an MCP authorization policy descriptor and reference it on your MCP routes.";throw new Ft(`MCP gateway: could not find an MCP authorization policy in policies.json. ${n}`)}n_(OM(t)),Mg(Dg({routes:e.routes,policies:e.policies}))}o(Lv,"initializeMcpGatewayState");function NM(e,t){return async(r,n)=>{let a=n,i=r.method==="OPTIONS",s=Date.now();i||a.log.info({event:`${e}_received`,method:r.method},`MCP gateway: ${e} received`);try{let u=await t(r,n);return i||a.log.info({event:`${e}_responded`,status:u.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),u}catch(u){let d={event:`${e}_threw`,durationMs:Date.now()-s};throw ze(d,"err",u),a.log.error(d,`MCP gateway: ${e} threw`),u}}}o(NM,"wrapInternalHandler");function jv(e){for(let t of PM){let r=NM(t.routeName,t.handler),n=o((a,i)=>r(a,i),"handler");e.addPluginRoute({path:t.path,methods:t.methods,handler:n,processors:[_c],corsPolicy:"none"})}}o(jv,"registerMcpGatewayInternalRoutes");var Wp=class extends im{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;r&&qv(r.policies)&&(Lv({routes:r.routes,policies:r.policies}),jv(t.router))}};export{dz as McpAuth0OAuthInboundPolicy,Wp as McpGatewayPlugin,mz as McpOAuthInboundPolicy,_z as McpUpstreamConnectionInboundPolicy,ez as McpVirtualServerHandler};
58
+ ${r}`}o(Cq,"formatPolicyConfigError");function _v(e){let t=yv(e.policies);if(!t){let r=qd(),n=r.length>0?`Add one of [${r.map(a=>`\`${a}\``).join(", ")}] and reference it on your MCP routes.`:"Register an MCP authorization policy descriptor and reference it on your MCP routes.";throw new jt(`MCP gateway: could not find an MCP authorization policy in policies.json. ${n}`)}Hg(Rq(t)),bg(vg({routes:e.routes,policies:e.policies}))}o(_v,"initializeMcpGatewayState");function Iq(e,t){return async(r,n)=>{let a=n,i=r.method==="OPTIONS",s=Date.now();i||a.log.info({event:`${e}_received`,method:r.method},`MCP gateway: ${e} received`);try{let c=await t(r,n);return i||a.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}catch(c){let d={event:`${e}_threw`,durationMs:Date.now()-s};throw Oe(d,"err",c),a.log.error(d,`MCP gateway: ${e} threw`),c}}}o(Iq,"wrapInternalHandler");function wv(e){for(let t of bq){let r=Iq(t.routeName,t.handler),n=o((a,i)=>r(a,i),"handler");e.addPluginRoute({path:t.path,methods:t.methods,handler:n,processors:[ec],corsPolicy:"none"})}}o(wv,"registerMcpGatewayInternalRoutes");var Tp=class extends Dp{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;r&&Sv(r.policies)&&(_v({routes:r.routes,policies:r.policies}),wv(t.router))}};export{s$ as McpAuth0OAuthInboundPolicy,Tp as McpGatewayPlugin,d$ as McpOAuthInboundPolicy,f$ as McpUpstreamConnectionInboundPolicy,YO as McpVirtualServerHandler};
1411
59
  //# sourceMappingURL=index.js.map