@zuplo/cli 6.70.9 → 6.70.10

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,37 +22,37 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as Zl,G as Hl,H as vi,I as xw,J as Gl,K as f,L as Bl,M as V,N as Y,O as Vl,P as Fl,Q as ue,R,S as I,T as fe,U as ne,V as bi,W as Ri,X as ee,Y as Ve,Z as P,_ as se,a as Ht,aa as Ii,ba as Kl,ca as Wl,da as u,ea as W,i as Nn,j as jl,p as wi,y as Ct}from"../chunk-YYF572GK.js";import{d as Si}from"../chunk-BHMDFTZV.js";import{a as L}from"../chunk-ZJ5LRHNO.js";import{U as ra,V as Tt,a as o,c as C,e as Ll}from"../chunk-FFHHHNST.js";var Kn=C(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.regexpCode=F.getEsmExportName=F.getProperty=F.safeStringify=F.stringify=F.strConcat=F.addCodeArg=F.str=F._=F.nil=F._Code=F.Name=F.IDENTIFIER=F._CodeOrName=void 0;var Fn=class{static{o(this,"_CodeOrName")}};F._CodeOrName=Fn;F.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var _r=class extends Fn{static{o(this,"Name")}constructor(t){if(super(),!F.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}}};F.Name=_r;var Je=class extends Fn{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 _r&&(r[n.str]=(r[n.str]||0)+1),r),{})}};F._Code=Je;F.nil=new Je("");function mp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)oc(r,t[n]),r.push(e[++n]);return new Je(r)}o(mp,"_");F._=mp;var nc=new Je("+");function fp(e,...t){let r=[Zn(e[0])],n=0;for(;n<t.length;)r.push(nc),oc(r,t[n]),r.push(nc,Zn(e[++n]));return tv(r),new Je(r)}o(fp,"str");F.str=fp;function oc(e,t){t instanceof Je?e.push(...t._items):t instanceof _r?e.push(t):e.push(ov(t))}o(oc,"addCodeArg");F.addCodeArg=oc;function tv(e){let t=1;for(;t<e.length-1;){if(e[t]===nc){let r=rv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(tv,"optimize");function rv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof _r||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 _r))return`"${e}${t.slice(1)}`}o(rv,"mergeExprItems");function nv(e,t){return t.emptyStr()?e:e.emptyStr()?t:fp`${e}${t}`}o(nv,"strConcat");F.strConcat=nv;function ov(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zn(Array.isArray(e)?e.join(","):e)}o(ov,"interpolate");function av(e){return new Je(Zn(e))}o(av,"stringify");F.stringify=av;function Zn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(Zn,"safeStringify");F.safeStringify=Zn;function sv(e){return typeof e=="string"&&F.IDENTIFIER.test(e)?new Je(`.${e}`):mp`[${e}]`}o(sv,"getProperty");F.getProperty=sv;function iv(e){if(typeof e=="string"&&F.IDENTIFIER.test(e))return new Je(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(iv,"getEsmExportName");F.getEsmExportName=iv;function cv(e){return new Je(e.toString())}o(cv,"regexpCode");F.regexpCode=cv});var ic=C(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.ValueScope=Me.ValueScopeName=Me.Scope=Me.varKinds=Me.UsedValueState=void 0;var ze=Kn(),ac=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},ya;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(ya||(Me.UsedValueState=ya={}));Me.varKinds={const:new ze.Name("const"),let:new ze.Name("let"),var:new ze.Name("var")};var wa=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof ze.Name?t:this.name(t)}name(t){return new ze.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}}};Me.Scope=wa;var Sa=class extends ze.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,ze._)`.${new ze.Name(r)}[${n}]`}};Me.ValueScopeName=Sa;var uv=(0,ze._)`\n`,sc=class extends wa{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?uv:ze.nil}}get(){return this._scope}name(t){return new Sa(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:s}=a,i=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[s];if(c){let l=c.get(i);if(l)return l}else c=this._values[s]=new Map;c.set(i,a);let d=this._scope[s]||(this._scope[s]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:s,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,ze._)`${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 s=ze.nil;for(let i in t){let c=t[i];if(!c)continue;let d=n[i]=n[i]||new Map;c.forEach(p=>{if(d.has(p))return;d.set(p,ya.Started);let l=r(p);if(l){let m=this.opts.es5?Me.varKinds.var:Me.varKinds.const;s=(0,ze._)`${s}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))s=(0,ze._)`${s}${l}${this.opts._n}`;else throw new ac(p);d.set(p,ya.Completed)})}return s}};Me.ValueScope=sc});var D=C(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.or=q.and=q.not=q.CodeGen=q.operators=q.varKinds=q.ValueScopeName=q.ValueScope=q.Scope=q.Name=q.regexpCode=q.stringify=q.getProperty=q.nil=q.strConcat=q.str=q._=void 0;var G=Kn(),ot=ic(),Yt=Kn();Object.defineProperty(q,"_",{enumerable:!0,get:o(function(){return Yt._},"get")});Object.defineProperty(q,"str",{enumerable:!0,get:o(function(){return Yt.str},"get")});Object.defineProperty(q,"strConcat",{enumerable:!0,get:o(function(){return Yt.strConcat},"get")});Object.defineProperty(q,"nil",{enumerable:!0,get:o(function(){return Yt.nil},"get")});Object.defineProperty(q,"getProperty",{enumerable:!0,get:o(function(){return Yt.getProperty},"get")});Object.defineProperty(q,"stringify",{enumerable:!0,get:o(function(){return Yt.stringify},"get")});Object.defineProperty(q,"regexpCode",{enumerable:!0,get:o(function(){return Yt.regexpCode},"get")});Object.defineProperty(q,"Name",{enumerable:!0,get:o(function(){return Yt.Name},"get")});var Ia=ic();Object.defineProperty(q,"Scope",{enumerable:!0,get:o(function(){return Ia.Scope},"get")});Object.defineProperty(q,"ValueScope",{enumerable:!0,get:o(function(){return Ia.ValueScope},"get")});Object.defineProperty(q,"ValueScopeName",{enumerable:!0,get:o(function(){return Ia.ValueScopeName},"get")});Object.defineProperty(q,"varKinds",{enumerable:!0,get:o(function(){return Ia.varKinds},"get")});q.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var xt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},cc=class extends xt{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?ot.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=Kr(this.rhs,t,r)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},va=class extends xt{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 G.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Kr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof G.Name?{}:{...this.lhs.names};return Ra(t,this.rhs)}},uc=class extends va{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}},dc=class extends xt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},lc=class extends xt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},pc=class extends xt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},mc=class extends xt{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=Kr(this.code,t,r),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},Wn=class extends xt{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 s=n[a];s.optimizeNames(t,r)||(dv(t,s.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Sr(t,r.names),{})}},kt=class extends Wn{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},fc=class extends Wn{static{o(this,"Root")}},Zr=class extends kt{static{o(this,"Else")}};Zr.kind="else";var yr=class e extends kt{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 Zr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(hp(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=Kr(this.condition,t,r),this}get names(){let t=super.names;return Ra(t,this.condition),this.else&&Sr(t,this.else.names),t}};yr.kind="if";var wr=class extends kt{static{o(this,"For")}};wr.kind="for";var hc=class extends wr{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=Kr(this.iteration,t,r),this}get names(){return Sr(super.names,this.iteration.names)}},gc=class extends wr{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?ot.varKinds.var:this.varKind,{name:n,from:a,to:s}=this;return`for(${r} ${n}=${a}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=Ra(super.names,this.from);return Ra(t,this.to)}},ba=class extends wr{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=Kr(this.iterable,t,r),this}get names(){return Sr(super.names,this.iterable.names)}},Jn=class extends kt{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)}};Jn.kind="func";var Yn=class extends Wn{static{o(this,"Return")}render(t){return"return "+super.render(t)}};Yn.kind="return";var _c=class extends kt{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&&Sr(t,this.catch.names),this.finally&&Sr(t,this.finally.names),t}},Xn=class extends kt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Xn.kind="catch";var Qn=class extends kt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};Qn.kind="finally";var yc=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 ot.Scope({parent:t}),this._nodes=[new fc]}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 s=this._scope.toName(r);return n!==void 0&&a&&(this._constants[s.str]=n),this._leafNode(new cc(t,s,n)),s}const(t,r,n){return this._def(ot.varKinds.const,t,r,n)}let(t,r,n){return this._def(ot.varKinds.let,t,r,n)}var(t,r,n){return this._def(ot.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new va(t,r,n))}add(t,r){return this._leafNode(new uc(t,q.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==G.nil&&this._leafNode(new mc(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,G.addCodeArg)(r,a));return r.push("}"),new G._Code(r)}if(t,r,n){if(this._blockNode(new yr(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 yr(t))}else(){return this._elseNode(new Zr)}endIf(){return this._endBlockNode(yr,Zr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new hc(t),r)}forRange(t,r,n,a,s=this.opts.es5?ot.varKinds.var:ot.varKinds.let){let i=this._scope.toName(t);return this._for(new gc(s,i,r,n),()=>a(i))}forOf(t,r,n,a=ot.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof G.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,G._)`${i}.length`,c=>{this.var(s,(0,G._)`${i}[${c}]`),n(s)})}return this._for(new ba("of",a,s,r),()=>n(s))}forIn(t,r,n,a=this.opts.es5?ot.varKinds.var:ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,G._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new ba("in",a,s,r),()=>n(s))}endFor(){return this._endBlockNode(wr)}label(t){return this._leafNode(new dc(t))}break(t){return this._leafNode(new lc(t))}return(t){let r=new Yn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Yn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new _c;if(this._blockNode(a),this.code(t),r){let s=this.name("e");this._currNode=a.catch=new Xn(s),r(s)}return n&&(this._currNode=a.finally=new Qn,this.code(n)),this._endBlockNode(Xn,Qn)}throw(t){return this._leafNode(new pc(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=G.nil,n,a){return this._blockNode(new Jn(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(Jn)}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 yr))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}};q.CodeGen=yc;function Sr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Sr,"addNames");function Ra(e,t){return t instanceof G._CodeOrName?Sr(e,t.names):e}o(Ra,"addExprNames");function Kr(e,t,r){if(e instanceof G.Name)return n(e);if(!a(e))return e;return new G._Code(e._items.reduce((s,i)=>(i instanceof G.Name&&(i=n(i)),i instanceof G._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function a(s){return s instanceof G._Code&&s._items.some(i=>i instanceof G.Name&&t[i.str]===1&&r[i.str]!==void 0)}}o(Kr,"optimizeExpr");function dv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(dv,"subtractNames");function hp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,G._)`!${wc(e)}`}o(hp,"not");q.not=hp;var lv=gp(q.operators.AND);function pv(...e){return e.reduce(lv)}o(pv,"and");q.and=pv;var mv=gp(q.operators.OR);function fv(...e){return e.reduce(mv)}o(fv,"or");q.or=fv;function gp(e){return(t,r)=>t===G.nil?r:r===G.nil?t:(0,G._)`${wc(t)} ${e} ${wc(r)}`}o(gp,"mappend");function wc(e){return e instanceof G.Name?e:(0,G._)`(${e})`}o(wc,"par")});var Z=C(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var X=D(),hv=Kn();function gv(e){let t={};for(let r of e)t[r]=!0;return t}o(gv,"toHash");j.toHash=gv;function _v(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(wp(e,t),!Sp(t,e.self.RULES.all))}o(_v,"alwaysValidSchema");j.alwaysValidSchema=_v;function wp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let s in t)a[s]||Rp(e,`unknown keyword: "${s}"`)}o(wp,"checkUnknownRules");j.checkUnknownRules=wp;function Sp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(Sp,"schemaHasRules");j.schemaHasRules=Sp;function yv(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(yv,"schemaHasRulesButRef");j.schemaHasRulesButRef=yv;function wv({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,X._)`${r}`}return(0,X._)`${e}${t}${(0,X.getProperty)(n)}`}o(wv,"schemaRefOrVal");j.schemaRefOrVal=wv;function Sv(e){return vp(decodeURIComponent(e))}o(Sv,"unescapeFragment");j.unescapeFragment=Sv;function vv(e){return encodeURIComponent(vc(e))}o(vv,"escapeFragment");j.escapeFragment=vv;function vc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(vc,"escapeJsonPointer");j.escapeJsonPointer=vc;function vp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(vp,"unescapeJsonPointer");j.unescapeJsonPointer=vp;function bv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(bv,"eachItem");j.eachItem=bv;function _p({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,s,i,c)=>{let d=i===void 0?s:i instanceof X.Name?(s instanceof X.Name?e(a,s,i):t(a,s,i),i):s instanceof X.Name?(t(a,i,s),s):r(s,i);return c===X.Name&&!(d instanceof X.Name)?n(a,d):d}}o(_p,"makeMergeEvaluated");j.mergeEvaluated={props:_p({mergeNames:o((e,t,r)=>e.if((0,X._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,X._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,X._)`${r} || {}`).code((0,X._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,X._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,X._)`${r} || {}`),bc(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:bp}),items:_p({mergeNames:o((e,t,r)=>e.if((0,X._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,X._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,X._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,X._)`${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 bp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,X._)`{}`);return t!==void 0&&bc(e,r,t),r}o(bp,"evaluatedPropsToName");j.evaluatedPropsToName=bp;function bc(e,t,r){Object.keys(r).forEach(n=>e.assign((0,X._)`${t}${(0,X.getProperty)(n)}`,!0))}o(bc,"setEvaluated");j.setEvaluated=bc;var yp={};function Rv(e,t){return e.scopeValue("func",{ref:t,code:yp[t.code]||(yp[t.code]=new hv._Code(t.code))})}o(Rv,"useFunc");j.useFunc=Rv;var Sc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Sc||(j.Type=Sc={}));function Iv(e,t,r){if(e instanceof X.Name){let n=t===Sc.Num;return r?n?(0,X._)`"[" + ${e} + "]"`:(0,X._)`"['" + ${e} + "']"`:n?(0,X._)`"/" + ${e}`:(0,X._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,X.getProperty)(e).toString():"/"+vc(e)}o(Iv,"getErrorPath");j.getErrorPath=Iv;function Rp(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(Rp,"checkStrictMode");j.checkStrictMode=Rp});var Ot=C(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Ce=D(),Tv={data:new Ce.Name("data"),valCxt:new Ce.Name("valCxt"),instancePath:new Ce.Name("instancePath"),parentData:new Ce.Name("parentData"),parentDataProperty:new Ce.Name("parentDataProperty"),rootData:new Ce.Name("rootData"),dynamicAnchors:new Ce.Name("dynamicAnchors"),vErrors:new Ce.Name("vErrors"),errors:new Ce.Name("errors"),this:new Ce.Name("this"),self:new Ce.Name("self"),scope:new Ce.Name("scope"),json:new Ce.Name("json"),jsonPos:new Ce.Name("jsonPos"),jsonLen:new Ce.Name("jsonLen"),jsonPart:new Ce.Name("jsonPart")};Rc.default=Tv});var eo=C(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.extendErrors=Ee.resetErrorsCount=Ee.reportExtraError=Ee.reportError=Ee.keyword$DataError=Ee.keywordError=void 0;var B=D(),Ta=Z(),ke=Ot();Ee.keywordError={message:o(({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`,"message")};Ee.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`,"message")};function Cv(e,t=Ee.keywordError,r,n){let{it:a}=e,{gen:s,compositeRule:i,allErrors:c}=a,d=Cp(e,t,r);n??(i||c)?Ip(s,d):Tp(a,(0,B._)`[${d}]`)}o(Cv,"reportError");Ee.reportError=Cv;function Ev(e,t=Ee.keywordError,r){let{it:n}=e,{gen:a,compositeRule:s,allErrors:i}=n,c=Cp(e,t,r);Ip(a,c),s||i||Tp(n,ke.default.vErrors)}o(Ev,"reportExtraError");Ee.reportExtraError=Ev;function Av(e,t){e.assign(ke.default.errors,t),e.if((0,B._)`${ke.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${ke.default.vErrors}.length`,t),()=>e.assign(ke.default.vErrors,null)))}o(Av,"resetErrorsCount");Ee.resetErrorsCount=Av;function Pv({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:s}){if(a===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",a,ke.default.errors,c=>{e.const(i,(0,B._)`${ke.default.vErrors}[${c}]`),e.if((0,B._)`${i}.instancePath === undefined`,()=>e.assign((0,B._)`${i}.instancePath`,(0,B.strConcat)(ke.default.instancePath,s.errorPath))),e.assign((0,B._)`${i}.schemaPath`,(0,B.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,B._)`${i}.schema`,r),e.assign((0,B._)`${i}.data`,n))})}o(Pv,"extendErrors");Ee.extendErrors=Pv;function Ip(e,t){let r=e.const("err",t);e.if((0,B._)`${ke.default.vErrors} === null`,()=>e.assign(ke.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${ke.default.vErrors}.push(${r})`),e.code((0,B._)`${ke.default.errors}++`)}o(Ip,"addError");function Tp(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}o(Tp,"returnErrors");var vr={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Cp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:xv(e,t,r)}o(Cp,"errorObjectCode");function xv(e,t,r={}){let{gen:n,it:a}=e,s=[kv(a,r),Ov(e,r)];return Uv(e,t,s),n.object(...s)}o(xv,"errorObject");function kv({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,Ta.getErrorPath)(t,Ta.Type.Str)}`:e;return[ke.default.instancePath,(0,B.strConcat)(ke.default.instancePath,r)]}o(kv,"errorInstancePath");function Ov({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,B.str)`${t}/${e}`;return r&&(a=(0,B.str)`${a}${(0,Ta.getErrorPath)(r,Ta.Type.Str)}`),[vr.schemaPath,a]}o(Ov,"errorSchemaPath");function Uv(e,{params:t,message:r},n){let{keyword:a,data:s,schemaValue:i,it:c}=e,{opts:d,propertyName:p,topSchemaRef:l,schemaPath:m}=c;n.push([vr.keyword,a],[vr.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),d.messages&&n.push([vr.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([vr.schema,i],[vr.parentSchema,(0,B._)`${l}${m}`],[ke.default.data,s]),p&&n.push([vr.propertyName,p])}o(Uv,"extraErrorProps")});var Ap=C(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.boolOrEmptySchema=Wr.topBoolOrEmptySchema=void 0;var Nv=eo(),$v=D(),zv=Ot(),Mv={message:"boolean schema is false"};function Dv(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Ep(e,!1):typeof r=="object"&&r.$async===!0?t.return(zv.default.data):(t.assign((0,$v._)`${n}.errors`,null),t.return(!0))}o(Dv,"topBoolOrEmptySchema");Wr.topBoolOrEmptySchema=Dv;function qv(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Ep(e)):r.var(t,!0)}o(qv,"boolOrEmptySchema");Wr.boolOrEmptySchema=qv;function Ep(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,Nv.reportError)(a,Mv,void 0,t)}o(Ep,"falseSchemaError")});var Ic=C(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.getRules=Jr.isJSONType=void 0;var Lv=["string","number","integer","boolean","null","object","array"],jv=new Set(Lv);function Hv(e){return typeof e=="string"&&jv.has(e)}o(Hv,"isJSONType");Jr.isJSONType=Hv;function Gv(){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(Gv,"getRules");Jr.getRules=Gv});var Tc=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.shouldUseRule=Xt.shouldUseGroup=Xt.schemaHasRulesForType=void 0;function Bv({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pp(e,n)}o(Bv,"schemaHasRulesForType");Xt.schemaHasRulesForType=Bv;function Pp(e,t){return t.rules.some(r=>xp(e,r))}o(Pp,"shouldUseGroup");Xt.shouldUseGroup=Pp;function xp(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(xp,"shouldUseRule");Xt.shouldUseRule=xp});var to=C(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reportTypeError=Ae.checkDataTypes=Ae.checkDataType=Ae.coerceAndCheckDataType=Ae.getJSONTypes=Ae.getSchemaTypes=Ae.DataType=void 0;var Vv=Ic(),Fv=Tc(),Zv=eo(),M=D(),kp=Z(),Yr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Yr||(Ae.DataType=Yr={}));function Kv(e){let t=Op(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(Kv,"getSchemaTypes");Ae.getSchemaTypes=Kv;function Op(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Vv.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Op,"getJSONTypes");Ae.getJSONTypes=Op;function Wv(e,t){let{gen:r,data:n,opts:a}=e,s=Jv(t,a.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Fv.schemaHasRulesForType)(e,t[0]));if(i){let c=Ec(t,n,a.strictNumbers,Yr.Wrong);r.if(c,()=>{s.length?Yv(e,t,s):Ac(e)})}return i}o(Wv,"coerceAndCheckDataType");Ae.coerceAndCheckDataType=Wv;var Up=new Set(["string","number","integer","boolean","null"]);function Jv(e,t){return t?e.filter(r=>Up.has(r)||t==="array"&&r==="array"):[]}o(Jv,"coerceToTypes");function Yv(e,t,r){let{gen:n,data:a,opts:s}=e,i=n.let("dataType",(0,M._)`typeof ${a}`),c=n.let("coerced",(0,M._)`undefined`);s.coerceTypes==="array"&&n.if((0,M._)`${i} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,M._)`${a}[0]`).assign(i,(0,M._)`typeof ${a}`).if(Ec(t,a,s.strictNumbers),()=>n.assign(c,a))),n.if((0,M._)`${c} !== undefined`);for(let p of r)(Up.has(p)||p==="array"&&s.coerceTypes==="array")&&d(p);n.else(),Ac(e),n.endIf(),n.if((0,M._)`${c} !== undefined`,()=>{n.assign(a,c),Xv(e,c)});function d(p){switch(p){case"string":n.elseIf((0,M._)`${i} == "number" || ${i} == "boolean"`).assign(c,(0,M._)`"" + ${a}`).elseIf((0,M._)`${a} === null`).assign(c,(0,M._)`""`);return;case"number":n.elseIf((0,M._)`${i} == "boolean" || ${a} === null
27
- || (${i} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,M._)`+${a}`);return;case"integer":n.elseIf((0,M._)`${i} === "boolean" || ${a} === null
28
- || (${i} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,M._)`+${a}`);return;case"boolean":n.elseIf((0,M._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,M._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,M._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,M._)`${i} === "string" || ${i} === "number"
29
- || ${i} === "boolean" || ${a} === null`).assign(c,(0,M._)`[${a}]`)}}o(d,"coerceSpecificType")}o(Yv,"coerceData");function Xv({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,M._)`${t} !== undefined`,()=>e.assign((0,M._)`${t}[${r}]`,n))}o(Xv,"assignParentData");function Cc(e,t,r,n=Yr.Correct){let a=n===Yr.Correct?M.operators.EQ:M.operators.NEQ,s;switch(e){case"null":return(0,M._)`${t} ${a} null`;case"array":s=(0,M._)`Array.isArray(${t})`;break;case"object":s=(0,M._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,M._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,M._)`typeof ${t} ${a} ${e}`}return n===Yr.Correct?s:(0,M.not)(s);function i(c=M.nil){return(0,M.and)((0,M._)`typeof ${t} == "number"`,c,r?(0,M._)`isFinite(${t})`:M.nil)}}o(Cc,"checkDataType");Ae.checkDataType=Cc;function Ec(e,t,r,n){if(e.length===1)return Cc(e[0],t,r,n);let a,s=(0,kp.toHash)(e);if(s.array&&s.object){let i=(0,M._)`typeof ${t} != "object"`;a=s.null?i:(0,M._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else a=M.nil;s.number&&delete s.integer;for(let i in s)a=(0,M.and)(a,Cc(i,t,r,n));return a}o(Ec,"checkDataTypes");Ae.checkDataTypes=Ec;var Qv={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,M._)`{type: ${e}}`:(0,M._)`{type: ${t}}`,"params")};function Ac(e){let t=eb(e);(0,Zv.reportError)(t,Qv)}o(Ac,"reportTypeError");Ae.reportTypeError=Ac;function eb(e){let{gen:t,data:r,schema:n}=e,a=(0,kp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(eb,"getTypeErrorContext")});var $p=C(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.assignDefaults=void 0;var Xr=D(),tb=Z();function rb(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Np(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,s)=>Np(e,s,a.default))}o(rb,"assignDefaults");Ca.assignDefaults=rb;function Np(e,t,r){let{gen:n,compositeRule:a,data:s,opts:i}=e;if(r===void 0)return;let c=(0,Xr._)`${s}${(0,Xr.getProperty)(t)}`;if(a){(0,tb.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,Xr._)`${c} === undefined`;i.useDefaults==="empty"&&(d=(0,Xr._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,Xr._)`${c} = ${(0,Xr.stringify)(r)}`)}o(Np,"assignDefault")});var Ye=C(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.validateUnion=J.validateArray=J.usePattern=J.callValidateCode=J.schemaProperties=J.allSchemaProperties=J.noPropertyInData=J.propertyInData=J.isOwnProperty=J.hasPropFunc=J.reportMissingProp=J.checkMissingProp=J.checkReportMissingProp=void 0;var te=D(),Pc=Z(),Qt=Ot(),nb=Z();function ob(e,t){let{gen:r,data:n,it:a}=e;r.if(kc(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,te._)`${t}`},!0),e.error()})}o(ob,"checkReportMissingProp");J.checkReportMissingProp=ob;function ab({gen:e,data:t,it:{opts:r}},n,a){return(0,te.or)(...n.map(s=>(0,te.and)(kc(e,t,s,r.ownProperties),(0,te._)`${a} = ${s}`)))}o(ab,"checkMissingProp");J.checkMissingProp=ab;function sb(e,t){e.setParams({missingProperty:t},!0),e.error()}o(sb,"reportMissingProp");J.reportMissingProp=sb;function zp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,te._)`Object.prototype.hasOwnProperty`})}o(zp,"hasPropFunc");J.hasPropFunc=zp;function xc(e,t,r){return(0,te._)`${zp(e)}.call(${t}, ${r})`}o(xc,"isOwnProperty");J.isOwnProperty=xc;function ib(e,t,r,n){let a=(0,te._)`${t}${(0,te.getProperty)(r)} !== undefined`;return n?(0,te._)`${a} && ${xc(e,t,r)}`:a}o(ib,"propertyInData");J.propertyInData=ib;function kc(e,t,r,n){let a=(0,te._)`${t}${(0,te.getProperty)(r)} === undefined`;return n?(0,te.or)(a,(0,te.not)(xc(e,t,r))):a}o(kc,"noPropertyInData");J.noPropertyInData=kc;function Mp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(Mp,"allSchemaProperties");J.allSchemaProperties=Mp;function cb(e,t){return Mp(t).filter(r=>!(0,Pc.alwaysValidSchema)(e,t[r]))}o(cb,"schemaProperties");J.schemaProperties=cb;function ub({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:s},it:i},c,d,p){let l=p?(0,te._)`${e}, ${t}, ${n}${a}`:t,m=[[Qt.default.instancePath,(0,te.strConcat)(Qt.default.instancePath,s)],[Qt.default.parentData,i.parentData],[Qt.default.parentDataProperty,i.parentDataProperty],[Qt.default.rootData,Qt.default.rootData]];i.opts.dynamicRef&&m.push([Qt.default.dynamicAnchors,Qt.default.dynamicAnchors]);let h=(0,te._)`${l}, ${r.object(...m)}`;return d!==te.nil?(0,te._)`${c}.call(${d}, ${h})`:(0,te._)`${c}(${h})`}o(ub,"callValidateCode");J.callValidateCode=ub;var db=(0,te._)`new RegExp`;function lb({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,s=a(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,te._)`${a.code==="new RegExp"?db:(0,nb.useFunc)(e,a)}(${r}, ${n})`})}o(lb,"usePattern");J.usePattern=lb;function pb(e){let{gen:t,data:r,keyword:n,it:a}=e,s=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return i(()=>t.assign(c,!1)),c}return t.var(s,!0),i(()=>t.break()),s;function i(c){let d=t.const("len",(0,te._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:Pc.Type.Num},s),t.if((0,te.not)(s),c)})}o(i,"validateItems")}o(pb,"validateArray");J.validateArray=pb;function mb(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,Pc.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let i=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(i,(0,te._)`${i} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,te.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}o(mb,"validateUnion");J.validateUnion=mb});var Lp=C(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Oe=D(),br=Ot(),fb=Ye(),hb=eo();function gb(e,t){let{gen:r,keyword:n,schema:a,parentSchema:s,it:i}=e,c=t.macro.call(i.self,a,s,i),d=qp(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Oe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(gb,"macroKeywordCode");ft.macroKeywordCode=gb;function _b(e,t){var r;let{gen:n,keyword:a,schema:s,parentSchema:i,$data:c,it:d}=e;wb(d,t);let p=!c&&t.compile?t.compile.call(d.self,s,i,d):t.validate,l=qp(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)y(),t.modifying&&Dp(e),S(()=>e.error());else{let v=t.async?_():w();t.modifying&&Dp(e),S(()=>yb(e,v))}}o(h,"validateKeyword");function _(){let v=n.let("ruleErrs",null);return n.try(()=>y((0,Oe._)`await `),b=>n.assign(m,!1).if((0,Oe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Oe._)`${b}.errors`),()=>n.throw(b))),v}o(_,"validateAsync");function w(){let v=(0,Oe._)`${l}.errors`;return n.assign(v,null),y(Oe.nil),v}o(w,"validateSync");function y(v=t.async?(0,Oe._)`await `:Oe.nil){let b=d.opts.passContext?br.default.this:br.default.self,T=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Oe._)`${v}${(0,fb.callValidateCode)(e,l,b,T)}`,t.modifying)}o(y,"assignValid");function S(v){var b;n.if((0,Oe.not)((b=t.valid)!==null&&b!==void 0?b:m),v)}o(S,"reportErrs")}o(_b,"funcKeywordCode");ft.funcKeywordCode=_b;function Dp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Oe._)`${n.parentData}[${n.parentDataProperty}]`))}o(Dp,"modifyData");function yb(e,t){let{gen:r}=e;r.if((0,Oe._)`Array.isArray(${t})`,()=>{r.assign(br.default.vErrors,(0,Oe._)`${br.default.vErrors} === null ? ${t} : ${br.default.vErrors}.concat(${t})`).assign(br.default.errors,(0,Oe._)`${br.default.vErrors}.length`),(0,hb.extendErrors)(e)},()=>e.error())}o(yb,"addErrs");function wb({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(wb,"checkAsyncKeyword");function qp(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,Oe.stringify)(r)})}o(qp,"useKeyword");function Sb(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(Sb,"validSchemaType");ft.validSchemaType=Sb;function vb({schema:e,opts:t,self:r,errSchemaPath:n},a,s){if(Array.isArray(a.keyword)?!a.keyword.includes(s):a.keyword!==s)throw new Error("ajv implementation error");let i=a.dependencies;if(i?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[s])){let d=`keyword "${s}" 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(vb,"validateKeywordUsage");ft.validateKeywordUsage=vb});var Hp=C(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.extendSubschemaMode=er.extendSubschemaData=er.getSubschema=void 0;var ht=D(),jp=Z();function bb(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:s,topSchemaRef:i}){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,ht._)`${e.schemaPath}${(0,ht.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,ht._)`${e.schemaPath}${(0,ht.getProperty)(t)}${(0,ht.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,jp.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}o(bb,"getSubschema");er.getSubschema=bb;function Rb(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:s,propertyName:i}){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,ht._)`${t.data}${(0,ht.getProperty)(r)}`,!0);d(h),e.errorPath=(0,ht.str)`${p}${(0,jp.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,ht._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof ht.Name?a:c.let("data",a,!0);d(p),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);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(Rb,"extendSubschemaData");er.extendSubschemaData=Rb;function Ib(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:s}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}o(Ib,"extendSubschemaMode");er.extendSubschemaMode=Ib});var Oc=C((pL,Gp)=>{"use strict";Gp.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,s;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(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[a]))return!1;for(a=n;a--!==0;){var i=s[a];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r},"equal")});var Vp=C((fL,Bp)=>{"use strict";var tr=Bp.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(){};Ea(t,n,a,e,"",e)};tr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};tr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};tr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};tr.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 Ea(e,t,r,n,a,s,i,c,d,p){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,s,i,c,d,p);for(var l in n){var m=n[l];if(Array.isArray(m)){if(l in tr.arrayKeywords)for(var h=0;h<m.length;h++)Ea(e,t,r,m[h],a+"/"+l+"/"+h,s,a,l,n,h)}else if(l in tr.propsKeywords){if(m&&typeof m=="object")for(var _ in m)Ea(e,t,r,m[_],a+"/"+l+"/"+Tb(_),s,a,l,n,_)}else(l in tr.keywords||e.allKeys&&!(l in tr.skipKeywords))&&Ea(e,t,r,m,a+"/"+l,s,a,l,n)}r(n,a,s,i,c,d,p)}}o(Ea,"_traverse");function Tb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Tb,"escapeJsonPtr")});var ro=C(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.getSchemaRefs=De.resolveUrl=De.normalizeId=De._getFullPath=De.getFullPath=De.inlineRef=void 0;var Cb=Z(),Eb=Oc(),Ab=Vp(),Pb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function xb(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Uc(e):t?Fp(e)<=t:!1}o(xb,"inlineRef");De.inlineRef=xb;var kb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Uc(e){for(let t in e){if(kb.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Uc)||typeof r=="object"&&Uc(r))return!0}return!1}o(Uc,"hasRef");function Fp(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Pb.has(r)&&(typeof e[r]=="object"&&(0,Cb.eachItem)(e[r],n=>t+=Fp(n)),t===1/0))return 1/0}return t}o(Fp,"countKeys");function Zp(e,t="",r){r!==!1&&(t=Qr(t));let n=e.parse(t);return Kp(e,n)}o(Zp,"getFullPath");De.getFullPath=Zp;function Kp(e,t){return e.serialize(t).split("#")[0]+"#"}o(Kp,"_getFullPath");De._getFullPath=Kp;var Ob=/#\/?$/;function Qr(e){return e?e.replace(Ob,""):""}o(Qr,"normalizeId");De.normalizeId=Qr;function Ub(e,t,r){return r=Qr(r),e.resolve(t,r)}o(Ub,"resolveUrl");De.resolveUrl=Ub;var Nb=/^[a-z_][-a-z0-9._]*$/i;function $b(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Qr(e[r]||t),s={"":a},i=Zp(n,a,!1),c={},d=new Set;return Ab(e,{allKeys:!0},(m,h,_,w)=>{if(w===void 0)return;let y=i+h,S=s[w];typeof m[r]=="string"&&(S=v.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),s[h]=S;function v(T){let U=this.opts.uriResolver.resolve;if(T=Qr(S?U(S,T):T),d.has(T))throw l(T);d.add(T);let $=this.refs[T];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?p(m,$.schema,T):T!==Qr(y)&&(T[0]==="#"?(p(m,c[T],T),c[T]=m):this.refs[T]=y),T}o(v,"addRef");function b(T){if(typeof T=="string"){if(!Nb.test(T))throw new Error(`invalid anchor "${T}"`);v.call(this,`#${T}`)}}o(b,"addAnchor")}),c;function p(m,h,_){if(h!==void 0&&!Eb(m,h))throw l(_)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o($b,"getSchemaRefs");De.getSchemaRefs=$b});var ao=C(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.getData=rr.KeywordCxt=rr.validateFunctionCode=void 0;var Qp=Ap(),Wp=to(),$c=Tc(),Aa=to(),zb=$p(),oo=Lp(),Nc=Hp(),x=D(),N=Ot(),Mb=ro(),Ut=Z(),no=eo();function Db(e){if(rm(e)&&(nm(e),tm(e))){jb(e);return}em(e,()=>(0,Qp.topBoolOrEmptySchema)(e))}o(Db,"validateFunctionCode");rr.validateFunctionCode=Db;function em({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},s){a.code.es5?e.func(t,(0,x._)`${N.default.data}, ${N.default.valCxt}`,n.$async,()=>{e.code((0,x._)`"use strict"; ${Jp(r,a)}`),Lb(e,a),e.code(s)}):e.func(t,(0,x._)`${N.default.data}, ${qb(a)}`,n.$async,()=>e.code(Jp(r,a)).code(s))}o(em,"validateFunction");function qb(e){return(0,x._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${e.dynamicRef?(0,x._)`, ${N.default.dynamicAnchors}={}`:x.nil}}={}`}o(qb,"destructureValCxt");function Lb(e,t){e.if(N.default.valCxt,()=>{e.var(N.default.instancePath,(0,x._)`${N.default.valCxt}.${N.default.instancePath}`),e.var(N.default.parentData,(0,x._)`${N.default.valCxt}.${N.default.parentData}`),e.var(N.default.parentDataProperty,(0,x._)`${N.default.valCxt}.${N.default.parentDataProperty}`),e.var(N.default.rootData,(0,x._)`${N.default.valCxt}.${N.default.rootData}`),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,x._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{e.var(N.default.instancePath,(0,x._)`""`),e.var(N.default.parentData,(0,x._)`undefined`),e.var(N.default.parentDataProperty,(0,x._)`undefined`),e.var(N.default.rootData,N.default.data),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,x._)`{}`)})}o(Lb,"destructureValCxtES5");function jb(e){let{schema:t,opts:r,gen:n}=e;em(e,()=>{r.$comment&&t.$comment&&am(e),Fb(e),n.let(N.default.vErrors,null),n.let(N.default.errors,0),r.unevaluated&&Hb(e),om(e),Wb(e)})}o(jb,"topSchemaObjCode");function Hb(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,x._)`${r}.evaluated`),t.if((0,x._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,x._)`${e.evaluated}.props`,(0,x._)`undefined`)),t.if((0,x._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,x._)`${e.evaluated}.items`,(0,x._)`undefined`))}o(Hb,"resetEvaluated");function Jp(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,x._)`/*# sourceURL=${r} */`:x.nil}o(Jp,"funcSourceUrl");function Gb(e,t){if(rm(e)&&(nm(e),tm(e))){Bb(e,t);return}(0,Qp.boolOrEmptySchema)(e,t)}o(Gb,"subschemaCode");function tm({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(tm,"schemaCxtHasRules");function rm(e){return typeof e.schema!="boolean"}o(rm,"isSchemaObj");function Bb(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&am(e),Zb(e),Kb(e);let s=n.const("_errs",N.default.errors);om(e,s),n.var(t,(0,x._)`${s} === ${N.default.errors}`)}o(Bb,"subSchemaObjCode");function nm(e){(0,Ut.checkUnknownRules)(e),Vb(e)}o(nm,"checkKeywords");function om(e,t){if(e.opts.jtd)return Yp(e,[],!1,t);let r=(0,Wp.getSchemaTypes)(e.schema),n=(0,Wp.coerceAndCheckDataType)(e,r);Yp(e,r,!n,t)}o(om,"typeAndKeywords");function Vb(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Ut.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(Vb,"checkRefsAndKeywords");function Fb(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ut.checkStrictMode)(e,"default is ignored in the schema root")}o(Fb,"checkNoDefault");function Zb(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Mb.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(Zb,"updateContext");function Kb(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(Kb,"checkAsyncSchema");function am({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let s=r.$comment;if(a.$comment===!0)e.code((0,x._)`${N.default.self}.logger.log(${s})`);else if(typeof a.$comment=="function"){let i=(0,x.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,x._)`${N.default.self}.opts.$comment(${s}, ${i}, ${c}.schema)`)}}o(am,"commentKeyword");function Wb(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:s}=e;r.$async?t.if((0,x._)`${N.default.errors} === 0`,()=>t.return(N.default.data),()=>t.throw((0,x._)`new ${a}(${N.default.vErrors})`)):(t.assign((0,x._)`${n}.errors`,N.default.vErrors),s.unevaluated&&Jb(e),t.return((0,x._)`${N.default.errors} === 0`))}o(Wb,"returnResults");function Jb({gen:e,evaluated:t,props:r,items:n}){r instanceof x.Name&&e.assign((0,x._)`${t}.props`,r),n instanceof x.Name&&e.assign((0,x._)`${t}.items`,n)}o(Jb,"assignEvaluated");function Yp(e,t,r,n){let{gen:a,schema:s,data:i,allErrors:c,opts:d,self:p}=e,{RULES:l}=p;if(s.$ref&&(d.ignoreKeywordsWithRef||!(0,Ut.schemaHasRulesButRef)(s,l))){a.block(()=>im(e,"$ref",l.all.$ref.definition));return}d.jtd||Yb(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,$c.shouldUseGroup)(s,h)&&(h.type?(a.if((0,Aa.checkDataType)(h.type,i,d.strictNumbers)),Xp(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,Aa.reportTypeError)(e)),a.endIf()):Xp(e,h),c||a.if((0,x._)`${N.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(Yp,"schemaKeywords");function Xp(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,zb.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,$c.shouldUseRule)(n,s)&&im(e,s.keyword,s.definition,t.type)})}o(Xp,"iterateKeywords");function Yb(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Xb(e,t),e.opts.allowUnionTypes||Qb(e,t),eR(e,e.dataTypes))}o(Yb,"checkStrictTypes");function Xb(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{sm(e.dataTypes,r)||zc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),rR(e,t)}}o(Xb,"checkContextTypes");function Qb(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&zc(e,"use allowUnionTypes to allow union type keyword")}o(Qb,"checkMultipleTypes");function eR(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,$c.shouldUseRule)(e.schema,a)){let{type:s}=a.definition;s.length&&!s.some(i=>tR(t,i))&&zc(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}o(eR,"checkKeywordTypes");function tR(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(tR,"hasApplicableType");function sm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(sm,"includesType");function rR(e,t){let r=[];for(let n of e.dataTypes)sm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(rR,"narrowSchemaTypes");function zc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Ut.checkStrictMode)(e,t,e.opts.strictTypes)}o(zc,"strictTypesError");var Pa=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,oo.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,Ut.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",cm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,oo.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",N.default.errors))}result(t,r,n){this.failResult((0,x.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,x.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,x._)`${r} !== undefined && (${(0,x.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?no.reportExtraError:no.reportError)(this,this.def.error,r)}$dataError(){(0,no.reportError)(this,this.def.$dataError||no.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,no.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=x.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=x.nil,r=x.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:s,def:i}=this;n.if((0,x.or)((0,x._)`${a} === undefined`,r)),t!==x.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==x.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:s}=this;return(0,x.or)(i(),c());function i(){if(n.length){if(!(r instanceof x.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,x._)`${(0,Aa.checkDataTypes)(d,r,s.opts.strictNumbers,Aa.DataType.Wrong)}`}return x.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,x._)`!${d}(${r})`}return x.nil}}subschema(t,r){let n=(0,Nc.getSubschema)(this.it,t);(0,Nc.extendSubschemaData)(n,this.it,t),(0,Nc.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return Gb(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Ut.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Ut.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,x.Name)),!0}};rr.KeywordCxt=Pa;function im(e,t,r,n){let a=new Pa(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,oo.funcKeywordCode)(a,r):"macro"in r?(0,oo.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,oo.funcKeywordCode)(a,r)}o(im,"keywordCode");var nR=/^\/(?:[^~]|~0|~1)*$/,oR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!nR.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,s=N.default.rootData}else{let p=oR.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(s=r[t-l],!a)return s}let i=s,c=a.split("/");for(let p of c)p&&(s=(0,x._)`${s}${(0,x.getProperty)((0,Ut.unescapeJsonPointer)(p))}`,i=(0,x._)`${i} && ${s}`);return i;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(cm,"getData");rr.getData=cm});var xa=C(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Mc=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Dc.default=Mc});var so=C(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var qc=ro(),Lc=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,qc.resolveUrl)(t,r,n),this.missingSchema=(0,qc.normalizeId)((0,qc.getFullPath)(t,this.missingRef))}};jc.default=Lc});var Oa=C(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.resolveSchema=Xe.getCompilingSchema=Xe.resolveRef=Xe.compileSchema=Xe.SchemaEnv=void 0;var at=D(),aR=xa(),Rr=Ot(),st=ro(),um=Z(),sR=ao(),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,st.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Xe.SchemaEnv=en;function Gc(e){let t=dm.call(this,e);if(t)return t;let r=(0,st.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:s}=this.opts,i=new at.CodeGen(this.scope,{es5:n,lines:a,ownProperties:s}),c;e.$async&&(c=i.scopeValue("Error",{ref:aR.default,code:(0,at._)`require("ajv/dist/runtime/validation_error").default`}));let d=i.scopeName("validate");e.validateName=d;let p={gen:i,allErrors:this.opts.allErrors,data:Rr.default.data,parentData:Rr.default.parentData,parentDataProperty:Rr.default.parentDataProperty,dataNames:[Rr.default.data],dataPathArr:[at.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,at.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:at.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,at._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,sR.validateFunctionCode)(p),i.optimize(this.opts.code.optimize);let m=i.toString();l=`${i.scopeRefs(Rr.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let _=new Function(`${Rr.default.self}`,`${Rr.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:i._values}),this.opts.unevaluated){let{props:w,items:y}=p;_.evaluated={props:w instanceof at.Name?void 0:w,items:y instanceof at.Name?void 0:y,dynamicProps:w instanceof at.Name,dynamicItems:y instanceof at.Name},_.source&&(_.source.evaluated=(0,at.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(Gc,"compileSchema");Xe.compileSchema=Gc;function iR(e,t,r){var n;r=(0,st.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let s=dR.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;i&&(s=new en({schema:i,schemaId:c,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=cR.call(this,s)}o(iR,"resolveRef");Xe.resolveRef=iR;function cR(e){return(0,st.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Gc.call(this,e)}o(cR,"inlineOrCompile");function dm(e){for(let t of this._compilations)if(uR(t,e))return t}o(dm,"getCompilingSchema");Xe.getCompilingSchema=dm;function uR(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(uR,"sameSchemaEnv");function dR(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ka.call(this,e,t)}o(dR,"resolve");function ka(e,t){let r=this.opts.uriResolver.parse(t),n=(0,st._getFullPath)(this.opts.uriResolver,r),a=(0,st.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Hc.call(this,r,e);let s=(0,st.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let c=ka.call(this,e,i);return typeof c?.schema!="object"?void 0:Hc.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||Gc.call(this,i),s===(0,st.normalizeId)(t)){let{schema:c}=i,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,st.resolveUrl)(this.opts.uriResolver,a,p)),new en({schema:c,schemaId:d,root:e,baseId:a})}return Hc.call(this,r,i)}}o(ka,"resolveSchema");Xe.resolveSchema=ka;var lR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Hc(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,um.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!lR.has(c)&&p&&(t=(0,st.resolveUrl)(this.opts.uriResolver,t,p))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,um.schemaHasRulesButRef)(r,this.RULES)){let c=(0,st.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=ka.call(this,n,c)}let{schemaId:i}=this.opts;if(s=s||new en({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}o(Hc,"getJsonPointer")});var lm=C((CL,pR)=>{pR.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 Vc=C((EL,hm)=>{"use strict";var mR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mm=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 Bc(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(Bc,"stringArrayToHexStripped");var fR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pm(e){return e.length=0,!0}o(pm,"consumeIsZone");function hR(e,t,r){if(e.length){let n=Bc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(hR,"consumeHextets");function gR(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],s=!1,i=!1,c=hR;for(let d=0;d<e.length;d++){let p=e[d];if(!(p==="["||p==="]"))if(p===":"){if(s===!0&&(i=!0),!c(a,n,r))break;if(++t>7){r.error=!0;break}d>0&&e[d-1]===":"&&(s=!0),n.push(":");continue}else if(p==="%"){if(!c(a,n,r))break;c=pm}else{a.push(p);continue}}return a.length&&(c===pm?r.zone=a.join(""):i?n.push(a.join("")):n.push(Bc(a))),r.address=n.join(""),r}o(gR,"getIPV6");function fm(e){if(_R(e,":")<2)return{host:e,isIPV6:!1};let t=gR(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(fm,"normalizeIPv6");function _R(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(_R,"findToken");function yR(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(yR,"removeDotSegments");function wR(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(wR,"normalizeComponentEncoding");function SR(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!mm(r)){let n=fm(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(SR,"recomposeAuthority");hm.exports={nonSimpleDomain:fR,recomposeAuthority:SR,normalizeComponentEncoding:wR,removeDotSegments:yR,isIPv4:mm,isUUID:mR,normalizeIPv6:fm,stringArrayToHexStripped:Bc}});var Sm=C((PL,wm)=>{"use strict";var{isUUID:vR}=Vc(),bR=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,RR=["http","https","ws","wss","urn","urn:uuid"];function IR(e){return RR.indexOf(e)!==-1}o(IR,"isValidSchemeName");function Fc(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(Fc,"wsIsSecure");function gm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(gm,"httpParse");function _m(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(_m,"httpSerialize");function TR(e){return e.secure=Fc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(TR,"wsParse");function CR(e){if((e.port===(Fc(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(CR,"wsSerialize");function ER(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(bR);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}`,s=Zc(a);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(ER,"urnParse");function AR(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}`,s=Zc(a);s&&(e=s.serialize(e,t));let i=e,c=e.nss;return i.path=`${n||t.nid}:${c}`,t.skipEscape=!0,i}o(AR,"urnSerialize");function PR(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!vR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(PR,"urnuuidParse");function xR(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(xR,"urnuuidSerialize");var ym={scheme:"http",domainHost:!0,parse:gm,serialize:_m},kR={scheme:"https",domainHost:ym.domainHost,parse:gm,serialize:_m},Ua={scheme:"ws",domainHost:!0,parse:TR,serialize:CR},OR={scheme:"wss",domainHost:Ua.domainHost,parse:Ua.parse,serialize:Ua.serialize},UR={scheme:"urn",parse:ER,serialize:AR,skipNormalize:!0},NR={scheme:"urn:uuid",parse:PR,serialize:xR,skipNormalize:!0},Na={http:ym,https:kR,ws:Ua,wss:OR,urn:UR,"urn:uuid":NR};Object.setPrototypeOf(Na,null);function Zc(e){return e&&(Na[e]||Na[e.toLowerCase()])||void 0}o(Zc,"getSchemeHandler");wm.exports={wsIsSecure:Fc,SCHEMES:Na,isValidSchemeName:IR,getSchemeHandler:Zc}});var Rm=C((kL,za)=>{"use strict";var{normalizeIPv6:$R,removeDotSegments:io,recomposeAuthority:zR,normalizeComponentEncoding:$a,isIPv4:MR,nonSimpleDomain:DR}=Vc(),{SCHEMES:qR,getSchemeHandler:vm}=Sm();function LR(e,t){return typeof e=="string"?e=gt(Nt(e,t),t):typeof e=="object"&&(e=Nt(gt(e,t),t)),e}o(LR,"normalize");function jR(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=bm(Nt(e,n),Nt(t,n),n,!0);return n.skipEscape=!0,gt(a,n)}o(jR,"resolve");function bm(e,t,r,n){let a={};return n||(e=Nt(gt(e,r),r),t=Nt(gt(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=io(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=io(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=io(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=io(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(bm,"resolveComponent");function HR(e,t,r){return typeof e=="string"?(e=unescape(e),e=gt($a(Nt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=gt($a(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=gt($a(Nt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=gt($a(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(HR,"equal");function gt(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=[],s=vm(n.scheme||r.scheme);s&&s.serialize&&s.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 i=zR(r);if(i!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(i),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(c=io(c)),i===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(gt,"serialize");var GR=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nt(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 s=e.match(GR);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(MR(n.host)===!1){let d=$R(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 i=vm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&a===!1&&DR(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}(!i||i&&!i.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)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(Nt,"parse");var Kc={SCHEMES:qR,normalize:LR,resolve:jR,resolveComponent:bm,equal:HR,serialize:gt,parse:Nt};za.exports=Kc;za.exports.default=Kc;za.exports.fastUri=Kc});var Tm=C(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Im=Rm();Im.code='require("ajv/dist/runtime/uri").default';Wc.default=Im});var Um=C(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=void 0;var BR=ao();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:o(function(){return BR.KeywordCxt},"get")});var tn=D();Object.defineProperty(ve,"_",{enumerable:!0,get:o(function(){return tn._},"get")});Object.defineProperty(ve,"str",{enumerable:!0,get:o(function(){return tn.str},"get")});Object.defineProperty(ve,"stringify",{enumerable:!0,get:o(function(){return tn.stringify},"get")});Object.defineProperty(ve,"nil",{enumerable:!0,get:o(function(){return tn.nil},"get")});Object.defineProperty(ve,"Name",{enumerable:!0,get:o(function(){return tn.Name},"get")});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:o(function(){return tn.CodeGen},"get")});var VR=xa(),xm=so(),FR=Ic(),co=Oa(),ZR=D(),uo=ro(),Ma=to(),Yc=Z(),Cm=lm(),KR=Tm(),km=o((e,t)=>new RegExp(e,t),"defaultRegExp");km.code="new RegExp";var WR=["removeAdditional","useDefaults","coerceTypes"],JR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),YR={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."},XR={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Em=200;function QR(e){var t,r,n,a,s,i,c,d,p,l,m,h,_,w,y,S,v,b,T,U,$,Be,It,gi,_i;let Un=e.strict,yi=(t=e.code)===null||t===void 0?void 0:t.optimize,Dl=yi===!0||yi===void 0?1:yi||0,ql=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:km,Pw=(a=e.uriResolver)!==null&&a!==void 0?a:KR.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:Un)!==null&&i!==void 0?i:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:Un)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:Un)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:Un)!==null&&h!==void 0?h:"log",strictRequired:(w=(_=e.strictRequired)!==null&&_!==void 0?_:Un)!==null&&w!==void 0?w:!1,code:e.code?{...e.code,optimize:Dl,regExp:ql}:{optimize:Dl,regExp:ql},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:Em,loopEnum:(S=e.loopEnum)!==null&&S!==void 0?S:Em,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(T=e.inlineRefs)!==null&&T!==void 0?T:!0,schemaId:(U=e.schemaId)!==null&&U!==void 0?U:"$id",addUsedSchema:($=e.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(Be=e.validateSchema)!==null&&Be!==void 0?Be:!0,validateFormats:(It=e.validateFormats)!==null&&It!==void 0?It:!0,unicodeRegExp:(gi=e.unicodeRegExp)!==null&&gi!==void 0?gi:!0,int32range:(_i=e.int32range)!==null&&_i!==void 0?_i:!0,uriResolver:Pw}}o(QR,"requiredOptions");var lo=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,...QR(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new ZR.ValueScope({scope:{},prefixes:JR,es5:r,lines:n}),this.logger=aI(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,FR.getRules)(),Am.call(this,YR,t,"NOT SUPPORTED"),Am.call(this,XR,t,"DEPRECATED","warn"),this._metaOpts=nI.call(this),t.formats&&tI.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&rI.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),eI.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Cm;n==="id"&&(a={...Cm},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 s.call(this,l.$schema);let h=this._addSchema(l,m);return h.validate||i.call(this,h)}async function s(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(m){if(!(m instanceof xm.default))throw m;return c.call(this,m),await d.call(this,m.missingSchema),i.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 s.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 i of t)this.addSchema(i,void 0,n,a);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,uo.normalizeId)(r||s),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 s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return a}getSchema(t){let r;for(;typeof(r=Pm.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new co.SchemaEnv({schema:{},schemaId:n});if(r=co.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=Pm.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,uo.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(iI.call(this,n,r),!r)return(0,Yc.eachItem)(n,s=>Jc.call(this,s)),this;uI.call(this,r);let a={...r,type:(0,Ma.getJSONTypes)(r.type),schemaType:(0,Ma.getJSONTypes)(r.schemaType)};return(0,Yc.eachItem)(n,a.type.length===0?s=>Jc.call(this,s,a):s=>a.type.forEach(i=>Jc.call(this,s,a,i))),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(s=>s.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,s)=>a+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let s=a.split("/").slice(1),i=t;for(let c of s)i=i[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=i[c];p&&l&&(i[c]=Om(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,s=this.opts.addUsedSchema){let i,{schemaId:c}=this.opts;if(typeof t=="object")i=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,uo.normalizeId)(i||n);let p=uo.getSchemaRefs.call(this,t,n);return d=new co.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),s&&!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):co.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{co.compileSchema.call(this,t)}finally{this.opts=r}}};lo.ValidationError=VR.default;lo.MissingRefError=xm.default;ve.default=lo;function Am(e,t,r,n="error"){for(let a in e){let s=a;s in t&&this.logger[n](`${r}: option ${a}. ${e[s]}`)}}o(Am,"checkOptions");function Pm(e){return e=(0,uo.normalizeId)(e),this.schemas[e]||this.refs[e]}o(Pm,"getSchEnv");function eI(){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(eI,"addInitialSchemas");function tI(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(tI,"addInitialFormats");function rI(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(rI,"addInitialKeywords");function nI(){let e={...this.opts};for(let t of WR)delete e[t];return e}o(nI,"getMetaSchemaOptions");var oI={log(){},warn(){},error(){}};function aI(e){if(e===!1)return oI;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(aI,"getLogger");var sI=/^[a-z_$][a-z0-9_$:-]*$/i;function iI(e,t){let{RULES:r}=this;if((0,Yc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!sI.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(iI,"checkKeyword");function Jc(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=a?s.post:s.rules.find(({type:d})=>d===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Ma.getJSONTypes)(t.type),schemaType:(0,Ma.getJSONTypes)(t.schemaType)}};t.before?cI.call(this,i,c,t.before):i.rules.push(c),s.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(Jc,"addRule");function cI(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(cI,"addBeforeRule");function uI(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Om(t)),e.validateSchema=this.compile(t,!0))}o(uI,"keywordMetaschema");var dI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Om(e){return{anyOf:[e,dI]}}o(Om,"schemaOrData")});var Nm=C(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var lI={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xc.default=lI});var Dm=C(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.callRef=Ir.getValidate=void 0;var pI=so(),$m=Ye(),qe=D(),rn=Ot(),zm=Oa(),Da=Z(),mI={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:s,validateName:i,opts:c,self:d}=n,{root:p}=s;if((r==="#"||r==="#/")&&a===p.baseId)return m();let l=zm.resolveRef.call(d,p,a,r);if(l===void 0)throw new pI.default(n.opts.uriResolver,a,r);if(l instanceof zm.SchemaEnv)return h(l);return _(l);function m(){if(s===p)return qa(e,i,s,s.$async);let w=t.scopeValue("root",{ref:p});return qa(e,(0,qe._)`${w}.validate`,p,p.$async)}function h(w){let y=Mm(e,w);qa(e,y,w,w.$async)}function _(w){let y=t.scopeValue("schema",c.code.source===!0?{ref:w,code:(0,qe.stringify)(w)}:{ref:w}),S=t.name("valid"),v=e.subschema({schema:w,dataTypes:[],schemaPath:qe.nil,topSchemaRef:y,errSchemaPath:r},S);e.mergeEvaluated(v),e.ok(S)}}};function Mm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,qe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(Mm,"getValidate");Ir.getValidate=Mm;function qa(e,t,r,n){let{gen:a,it:s}=e,{allErrors:i,schemaEnv:c,opts:d}=s,p=d.passContext?rn.default.this:qe.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let w=a.let("valid");a.try(()=>{a.code((0,qe._)`await ${(0,$m.callValidateCode)(e,t,p)}`),_(t),i||a.assign(w,!0)},y=>{a.if((0,qe._)`!(${y} instanceof ${s.ValidationError})`,()=>a.throw(y)),h(y),i||a.assign(w,!1)}),e.ok(w)}o(l,"callAsyncRef");function m(){e.result((0,$m.callValidateCode)(e,t,p),()=>_(t),()=>h(t))}o(m,"callSyncRef");function h(w){let y=(0,qe._)`${w}.errors`;a.assign(rn.default.vErrors,(0,qe._)`${rn.default.vErrors} === null ? ${y} : ${rn.default.vErrors}.concat(${y})`),a.assign(rn.default.errors,(0,qe._)`${rn.default.vErrors}.length`)}o(h,"addErrorsFrom");function _(w){var y;if(!s.opts.unevaluated)return;let S=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=Da.mergeEvaluated.props(a,S.props,s.props));else{let v=a.var("props",(0,qe._)`${w}.evaluated.props`);s.props=Da.mergeEvaluated.props(a,v,s.props,qe.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=Da.mergeEvaluated.items(a,S.items,s.items));else{let v=a.var("items",(0,qe._)`${w}.evaluated.items`);s.items=Da.mergeEvaluated.items(a,v,s.items,qe.Name)}}o(_,"addEvaluatedFrom")}o(qa,"callRef");Ir.callRef=qa;Ir.default=mI});var qm=C(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var fI=Nm(),hI=Dm(),gI=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fI.default,hI.default];Qc.default=gI});var Lm=C(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var La=D(),nr=La.operators,ja={maximum:{okStr:"<=",ok:nr.LTE,fail:nr.GT},minimum:{okStr:">=",ok:nr.GTE,fail:nr.LT},exclusiveMaximum:{okStr:"<",ok:nr.LT,fail:nr.GTE},exclusiveMinimum:{okStr:">",ok:nr.GT,fail:nr.LTE}},_I={message:o(({keyword:e,schemaCode:t})=>(0,La.str)`must be ${ja[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,La._)`{comparison: ${ja[e].okStr}, limit: ${t}}`,"params")},yI={keyword:Object.keys(ja),type:"number",schemaType:"number",$data:!0,error:_I,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,La._)`${r} ${ja[t].fail} ${n} || isNaN(${r})`)}};eu.default=yI});var jm=C(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var po=D(),wI={message:o(({schemaCode:e})=>(0,po.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,po._)`{multipleOf: ${e}}`,"params")},SI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wI,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,s=a.opts.multipleOfPrecision,i=t.let("res"),c=s?(0,po._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,po._)`${i} !== parseInt(${i})`;e.fail$data((0,po._)`(${n} === 0 || (${i} = ${r}/${n}, ${c}))`)}};tu.default=SI});var Gm=C(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});function Hm(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(Hm,"ucs2length");ru.default=Hm;Hm.code='require("ajv/dist/runtime/ucs2length").default'});var Bm=C(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Tr=D(),vI=Z(),bI=Gm(),RI={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Tr.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,Tr._)`{limit: ${e}}`,"params")},II={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:RI,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,s=t==="maxLength"?Tr.operators.GT:Tr.operators.LT,i=a.opts.unicode===!1?(0,Tr._)`${r}.length`:(0,Tr._)`${(0,vI.useFunc)(e.gen,bI.default)}(${r})`;e.fail$data((0,Tr._)`${i} ${s} ${n}`)}};nu.default=II});var Vm=C(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var TI=Ye(),Ha=D(),CI={message:o(({schemaCode:e})=>(0,Ha.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ha._)`{pattern: ${e}}`,"params")},EI={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:CI,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:s}=e,i=s.opts.unicodeRegExp?"u":"",c=r?(0,Ha._)`(new RegExp(${a}, ${i}))`:(0,TI.usePattern)(e,n);e.fail$data((0,Ha._)`!${c}.test(${t})`)}};ou.default=EI});var Fm=C(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var mo=D(),AI={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,mo.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,mo._)`{limit: ${e}}`,"params")},PI={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:AI,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?mo.operators.GT:mo.operators.LT;e.fail$data((0,mo._)`Object.keys(${r}).length ${a} ${n}`)}};au.default=PI});var Zm=C(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var fo=Ye(),ho=D(),xI=Z(),kI={message:o(({params:{missingProperty:e}})=>(0,ho.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,ho._)`{missingProperty: ${e}}`,"params")},OI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kI,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:s,it:i}=e,{opts:c}=i;if(!s&&r.length===0)return;let d=r.length>=c.loopRequired;if(i.allErrors?p():l(),c.strictRequired){let _=e.parentSchema.properties,{definedProperties:w}=e.it;for(let y of r)if(_?.[y]===void 0&&!w.has(y)){let S=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${y}" is not defined at "${S}" (strictRequired)`;(0,xI.checkStrictMode)(i,v,i.opts.strictRequired)}}function p(){if(d||s)e.block$data(ho.nil,m);else for(let _ of r)(0,fo.checkReportMissingProp)(e,_)}o(p,"allErrorsMode");function l(){let _=t.let("missing");if(d||s){let w=t.let("valid",!0);e.block$data(w,()=>h(_,w)),e.ok(w)}else t.if((0,fo.checkMissingProp)(e,r,_)),(0,fo.reportMissingProp)(e,_),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,_=>{e.setParams({missingProperty:_}),t.if((0,fo.noPropertyInData)(t,a,_,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(_,w){e.setParams({missingProperty:_}),t.forOf(_,n,()=>{t.assign(w,(0,fo.propertyInData)(t,a,_,c.ownProperties)),t.if((0,ho.not)(w),()=>{e.error(),t.break()})},ho.nil)}o(h,"loopUntilMissing")}};su.default=OI});var Km=C(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var go=D(),UI={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,go.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,go._)`{limit: ${e}}`,"params")},NI={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UI,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?go.operators.GT:go.operators.LT;e.fail$data((0,go._)`${r}.length ${a} ${n}`)}};iu.default=NI});var Ga=C(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var Wm=Oc();Wm.code='require("ajv/dist/runtime/equal").default';cu.default=Wm});var Jm=C(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var uu=to(),be=D(),$I=Z(),zI=Ga(),MI={message:o(({params:{i:e,j:t}})=>(0,be.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,be._)`{i: ${e}, j: ${t}}`,"params")},DI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:MI,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:s,schemaCode:i,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=s.items?(0,uu.getSchemaTypes)(s.items):[];e.block$data(d,l,(0,be._)`${i} === false`),e.ok(d);function l(){let w=t.let("i",(0,be._)`${r}.length`),y=t.let("j");e.setParams({i:w,j:y}),t.assign(d,!0),t.if((0,be._)`${w} > 1`,()=>(m()?h:_)(w,y))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(w=>w==="object"||w==="array")}o(m,"canOptimize");function h(w,y){let S=t.name("item"),v=(0,uu.checkDataTypes)(p,S,c.opts.strictNumbers,uu.DataType.Wrong),b=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${w}--;`,()=>{t.let(S,(0,be._)`${r}[${w}]`),t.if(v,(0,be._)`continue`),p.length>1&&t.if((0,be._)`typeof ${S} == "string"`,(0,be._)`${S} += "_"`),t.if((0,be._)`typeof ${b}[${S}] == "number"`,()=>{t.assign(y,(0,be._)`${b}[${S}]`),e.error(),t.assign(d,!1).break()}).code((0,be._)`${b}[${S}] = ${w}`)})}o(h,"loopN");function _(w,y){let S=(0,$I.useFunc)(t,zI.default),v=t.name("outer");t.label(v).for((0,be._)`;${w}--;`,()=>t.for((0,be._)`${y} = ${w}; ${y}--;`,()=>t.if((0,be._)`${S}(${r}[${w}], ${r}[${y}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(_,"loopN2")}};du.default=DI});var Ym=C(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var lu=D(),qI=Z(),LI=Ga(),jI={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,lu._)`{allowedValue: ${e}}`,"params")},HI={keyword:"const",$data:!0,error:jI,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,lu._)`!${(0,qI.useFunc)(t,LI.default)}(${r}, ${a})`):e.fail((0,lu._)`${s} !== ${r}`)}};pu.default=HI});var Xm=C(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var _o=D(),GI=Z(),BI=Ga(),VI={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,_o._)`{allowedValues: ${e}}`,"params")},FI={keyword:"enum",schemaType:"array",$data:!0,error:VI,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:s,it:i}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let c=a.length>=i.opts.loopEnum,d,p=o(()=>d??(d=(0,GI.useFunc)(t,BI.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 _=t.const("vSchema",s);l=(0,_o.or)(...a.map((w,y)=>h(_,y)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",s,_=>t.if((0,_o._)`${p()}(${r}, ${_})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(_,w){let y=a[w];return typeof y=="object"&&y!==null?(0,_o._)`${p()}(${r}, ${_}[${w}])`:(0,_o._)`${r} === ${y}`}o(h,"equalCode")}};mu.default=FI});var Qm=C(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var ZI=Lm(),KI=jm(),WI=Bm(),JI=Vm(),YI=Fm(),XI=Zm(),QI=Km(),eT=Jm(),tT=Ym(),rT=Xm(),nT=[ZI.default,KI.default,WI.default,JI.default,YI.default,XI.default,QI.default,eT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},tT.default,rT.default];fu.default=nT});var gu=C(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.validateAdditionalItems=void 0;var Cr=D(),hu=Z(),oT={message:o(({params:{len:e}})=>(0,Cr.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Cr._)`{limit: ${e}}`,"params")},aT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oT,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,hu.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ef(e,n)}};function ef(e,t){let{gen:r,schema:n,data:a,keyword:s,it:i}=e;i.items=!0;let c=r.const("len",(0,Cr._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Cr._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,hu.alwaysValidSchema)(i,n)){let p=r.var("valid",(0,Cr._)`${c} <= ${t.length}`);r.if((0,Cr.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:hu.Type.Num},p),i.allErrors||r.if((0,Cr.not)(p),()=>r.break())})}o(d,"validateItems")}o(ef,"validateAdditionalItems");yo.validateAdditionalItems=ef;yo.default=aT});var _u=C(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateTuple=void 0;var tf=D(),Ba=Z(),sT=Ye(),iT={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,Ba.alwaysValidSchema)(r,t)&&e.ok((0,sT.validateArray)(e))}};function rf(e,t,r=e.schema){let{gen:n,parentSchema:a,data:s,keyword:i,it:c}=e;l(a),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Ba.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,tf._)`${s}.length`);r.forEach((m,h)=>{(0,Ba.alwaysValidSchema)(c,m)||(n.if((0,tf._)`${p} > ${h}`,()=>e.subschema({keyword:i,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:_}=c,w=r.length,y=w===m.minItems&&(w===m.maxItems||m[t]===!1);if(h.strictTuples&&!y){let S=`"${i}" is ${w}-tuple, but minItems or maxItems/${t} are not specified or different at path "${_}"`;(0,Ba.checkStrictMode)(c,S,h.strictTuples)}}o(l,"checkStrictTuple")}o(rf,"validateTuple");wo.validateTuple=rf;wo.default=iT});var nf=C(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var cT=_u(),uT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,cT.validateTuple)(e,"items"),"code")};yu.default=uT});var af=C(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var of=D(),dT=Z(),lT=Ye(),pT=gu(),mT={message:o(({params:{len:e}})=>(0,of.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,of._)`{limit: ${e}}`,"params")},fT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mT,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,dT.alwaysValidSchema)(n,t)&&(a?(0,pT.validateAdditionalItems)(e,a):e.ok((0,lT.validateArray)(e)))}};wu.default=fT});var sf=C(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var Qe=D(),Va=Z(),hT={message:o(({params:{min:e,max:t}})=>t===void 0?(0,Qe.str)`must contain at least ${e} valid item(s)`:(0,Qe.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,Qe._)`{minContains: ${e}}`:(0,Qe._)`{minContains: ${e}, maxContains: ${t}}`,"params")},gT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:hT,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:s}=e,i,c,{minContains:d,maxContains:p}=n;s.opts.next?(i=d===void 0?1:d,c=p):i=1;let l=t.const("len",(0,Qe._)`${a}.length`);if(e.setParams({min:i,max:c}),c===void 0&&i===0){(0,Va.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,Va.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Va.alwaysValidSchema)(s,r)){let y=(0,Qe._)`${l} >= ${i}`;c!==void 0&&(y=(0,Qe._)`${y} && ${l} <= ${c}`),e.pass(y);return}s.items=!0;let m=t.name("valid");c===void 0&&i===1?_(m,()=>t.if(m,()=>t.break())):i===0?(t.let(m,!0),c!==void 0&&t.if((0,Qe._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let y=t.name("_valid"),S=t.let("count",0);_(y,()=>t.if(y,()=>w(S)))}o(h,"validateItemsWithCount");function _(y,S){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Va.Type.Num,compositeRule:!0},y),S()})}o(_,"validateItems");function w(y){t.code((0,Qe._)`${y}++`),c===void 0?t.if((0,Qe._)`${y} >= ${i}`,()=>t.assign(m,!0).break()):(t.if((0,Qe._)`${y} > ${c}`,()=>t.assign(m,!1).break()),i===1?t.assign(m,!0):t.if((0,Qe._)`${y} >= ${i}`,()=>t.assign(m,!0)))}o(w,"checkLimits")}};Su.default=gT});var df=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.validateSchemaDeps=_t.validatePropertyDeps=_t.error=void 0;var vu=D(),_T=Z(),So=Ye();_t.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,vu.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,vu._)`{property: ${e},
25
+ import{$ as pe,H as Sp,I as Ms,J as Jw,K as wp,L as h,M as vp,N as K,O as te,P as Rp,Q as bp,R as fe,S as b,T as I,U as we,V as ce,W as qs,X as $s,Y as oe,Z as Xe,_ as E,a as Wt,aa as Ip,b as _p,ba as Ls,ca as Cp,da as Tp,ea as c,fa as X,j as Vn,k as yp,q as Ds,z as Ut}from"../chunk-PG5BJ2JU.js";import{d as Fn}from"../chunk-BHMDFTZV.js";import{a as H}from"../chunk-ZJ5LRHNO.js";import{U as ya,V as et,W as gp,a as o,c as T,e as fp}from"../chunk-FFHHHNST.js";var io=T(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var oo=class{static{o(this,"_CodeOrName")}};W._CodeOrName=oo;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Rr=class extends oo{static{o(this,"Name")}constructor(t){if(super(),!W.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}}};W.Name=Rr;var nt=class extends oo{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 Rr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};W._Code=nt;W.nil=new nt("");function Bp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)wc(r,t[n]),r.push(e[++n]);return new nt(r)}o(Bp,"_");W._=Bp;var Sc=new nt("+");function Vp(e,...t){let r=[ao(e[0])],n=0;for(;n<t.length;)r.push(Sc),wc(r,t[n]),r.push(Sc,ao(e[++n]));return vR(r),new nt(r)}o(Vp,"str");W.str=Vp;function wc(e,t){t instanceof nt?e.push(...t._items):t instanceof Rr?e.push(t):e.push(IR(t))}o(wc,"addCodeArg");W.addCodeArg=wc;function vR(e){let t=1;for(;t<e.length-1;){if(e[t]===Sc){let r=RR(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(vR,"optimize");function RR(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Rr||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 Rr))return`"${e}${t.slice(1)}`}o(RR,"mergeExprItems");function bR(e,t){return t.emptyStr()?e:e.emptyStr()?t:Vp`${e}${t}`}o(bR,"strConcat");W.strConcat=bR;function IR(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:ao(Array.isArray(e)?e.join(","):e)}o(IR,"interpolate");function CR(e){return new nt(ao(e))}o(CR,"stringify");W.stringify=CR;function ao(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(ao,"safeStringify");W.safeStringify=ao;function TR(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new nt(`.${e}`):Bp`[${e}]`}o(TR,"getProperty");W.getProperty=TR;function AR(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new nt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(AR,"getEsmExportName");W.getEsmExportName=AR;function kR(e){return new nt(e.toString())}o(kR,"regexpCode");W.regexpCode=kR});var bc=T(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var He=io(),vc=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},za;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(za||(Ge.UsedValueState=za={}));Ge.varKinds={const:new He.Name("const"),let:new He.Name("let"),var:new He.Name("var")};var Na=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof He.Name?t:this.name(t)}name(t){return new He.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}}};Ge.Scope=Na;var Da=class extends He.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,He._)`.${new He.Name(r)}[${n}]`}};Ge.ValueScopeName=Da;var ER=(0,He._)`\n`,Rc=class extends Na{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?ER:He.nil}}get(){return this._scope}name(t){return new Da(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 p=u.get(s);if(p)return p}else u=this._values[i]=new Map;u.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),l=d.length;return d[l]=r.ref,a.setValue(r,{property:i,itemIndex:l}),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,He._)`${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=He.nil;for(let s in t){let u=t[s];if(!u)continue;let d=n[s]=n[s]||new Map;u.forEach(l=>{if(d.has(l))return;d.set(l,za.Started);let p=r(l);if(p){let m=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;i=(0,He._)`${i}${m} ${l} = ${p};${this.opts._n}`}else if(p=a?.(l))i=(0,He._)`${i}${p}${this.opts._n}`;else throw new vc(l);d.set(l,za.Completed)})}return i}};Ge.ValueScope=Rc});var L=T(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.or=j.and=j.not=j.CodeGen=j.operators=j.varKinds=j.ValueScopeName=j.ValueScope=j.Scope=j.Name=j.regexpCode=j.stringify=j.getProperty=j.nil=j.strConcat=j.str=j._=void 0;var B=io(),lt=bc(),or=io();Object.defineProperty(j,"_",{enumerable:!0,get:o(function(){return or._},"get")});Object.defineProperty(j,"str",{enumerable:!0,get:o(function(){return or.str},"get")});Object.defineProperty(j,"strConcat",{enumerable:!0,get:o(function(){return or.strConcat},"get")});Object.defineProperty(j,"nil",{enumerable:!0,get:o(function(){return or.nil},"get")});Object.defineProperty(j,"getProperty",{enumerable:!0,get:o(function(){return or.getProperty},"get")});Object.defineProperty(j,"stringify",{enumerable:!0,get:o(function(){return or.stringify},"get")});Object.defineProperty(j,"regexpCode",{enumerable:!0,get:o(function(){return or.regexpCode},"get")});Object.defineProperty(j,"Name",{enumerable:!0,get:o(function(){return or.Name},"get")});var La=bc();Object.defineProperty(j,"Scope",{enumerable:!0,get:o(function(){return La.Scope},"get")});Object.defineProperty(j,"ValueScope",{enumerable:!0,get:o(function(){return La.ValueScope},"get")});Object.defineProperty(j,"ValueScopeName",{enumerable:!0,get:o(function(){return La.ValueScopeName},"get")});Object.defineProperty(j,"varKinds",{enumerable:!0,get:o(function(){return La.varKinds},"get")});j.operators={GT:new B._Code(">"),GTE:new B._Code(">="),LT:new B._Code("<"),LTE:new B._Code("<="),EQ:new B._Code("==="),NEQ:new B._Code("!=="),NOT:new B._Code("!"),OR:new B._Code("||"),AND:new B._Code("&&"),ADD:new B._Code("+")};var Mt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},Ic=class extends Mt{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?lt.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=nn(this.rhs,t,r)),this}get names(){return this.rhs instanceof B._CodeOrName?this.rhs.names:{}}},Ma=class extends Mt{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 B.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=nn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof B.Name?{}:{...this.lhs.names};return $a(t,this.rhs)}},Cc=class extends Ma{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}},Tc=class extends Mt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ac=class extends Mt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},kc=class extends Mt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ec=class extends Mt{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=nn(this.code,t,r),this}get names(){return this.code instanceof B._CodeOrName?this.code.names:{}}},so=class extends Mt{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)||(PR(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Cr(t,r.names),{})}},qt=class extends so{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Pc=class extends so{static{o(this,"Root")}},rn=class extends qt{static{o(this,"Else")}};rn.kind="else";var br=class e extends qt{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(Fp(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=nn(this.condition,t,r),this}get names(){let t=super.names;return $a(t,this.condition),this.else&&Cr(t,this.else.names),t}};br.kind="if";var Ir=class extends qt{static{o(this,"For")}};Ir.kind="for";var xc=class extends Ir{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=nn(this.iteration,t,r),this}get names(){return Cr(super.names,this.iteration.names)}},Oc=class extends Ir{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?lt.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=$a(super.names,this.from);return $a(t,this.to)}},qa=class extends Ir{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=nn(this.iterable,t,r),this}get names(){return Cr(super.names,this.iterable.names)}},co=class extends qt{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)}};co.kind="func";var uo=class extends so{static{o(this,"Return")}render(t){return"return "+super.render(t)}};uo.kind="return";var Uc=class extends qt{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&&Cr(t,this.catch.names),this.finally&&Cr(t,this.finally.names),t}},lo=class extends qt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};lo.kind="catch";var po=class extends qt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};po.kind="finally";var zc=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 lt.Scope({parent:t}),this._nodes=[new Pc]}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 Ic(t,i,n)),i}const(t,r,n){return this._def(lt.varKinds.const,t,r,n)}let(t,r,n){return this._def(lt.varKinds.let,t,r,n)}var(t,r,n){return this._def(lt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Ma(t,r,n))}add(t,r){return this._leafNode(new Cc(t,j.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==B.nil&&this._leafNode(new Ec(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,B.addCodeArg)(r,a));return r.push("}"),new B._Code(r)}if(t,r,n){if(this._blockNode(new br(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 br(t))}else(){return this._elseNode(new rn)}endIf(){return this._endBlockNode(br,rn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new xc(t),r)}forRange(t,r,n,a,i=this.opts.es5?lt.varKinds.var:lt.varKinds.let){let s=this._scope.toName(t);return this._for(new Oc(i,s,r,n),()=>a(s))}forOf(t,r,n,a=lt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof B.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,B._)`${s}.length`,u=>{this.var(i,(0,B._)`${s}[${u}]`),n(i)})}return this._for(new qa("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?lt.varKinds.var:lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,B._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new qa("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Ir)}label(t){return this._leafNode(new Tc(t))}break(t){return this._leafNode(new Ac(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 Uc;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new lo(i),r(i)}return n&&(this._currNode=a.finally=new po,this.code(n)),this._endBlockNode(lo,po)}throw(t){return this._leafNode(new kc(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=B.nil,n,a){return this._blockNode(new co(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(co)}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 br))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}};j.CodeGen=zc;function Cr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Cr,"addNames");function $a(e,t){return t instanceof B._CodeOrName?Cr(e,t.names):e}o($a,"addExprNames");function nn(e,t,r){if(e instanceof B.Name)return n(e);if(!a(e))return e;return new B._Code(e._items.reduce((i,s)=>(s instanceof B.Name&&(s=n(s)),s instanceof B._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 B._Code&&i._items.some(s=>s instanceof B.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(nn,"optimizeExpr");function PR(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(PR,"subtractNames");function Fp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,B._)`!${Nc(e)}`}o(Fp,"not");j.not=Fp;var xR=Zp(j.operators.AND);function OR(...e){return e.reduce(xR)}o(OR,"and");j.and=OR;var UR=Zp(j.operators.OR);function zR(...e){return e.reduce(UR)}o(zR,"or");j.or=zR;function Zp(e){return(t,r)=>t===B.nil?r:r===B.nil?t:(0,B._)`${Nc(t)} ${e} ${Nc(r)}`}o(Zp,"mappend");function Nc(e){return e instanceof B.Name?e:(0,B._)`(${e})`}o(Nc,"par")});var J=T(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var re=L(),NR=io();function DR(e){let t={};for(let r of e)t[r]=!0;return t}o(DR,"toHash");G.toHash=DR;function MR(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Jp(e,t),!Yp(t,e.self.RULES.all))}o(MR,"alwaysValidSchema");G.alwaysValidSchema=MR;function Jp(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]||em(e,`unknown keyword: "${i}"`)}o(Jp,"checkUnknownRules");G.checkUnknownRules=Jp;function Yp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(Yp,"schemaHasRules");G.schemaHasRules=Yp;function qR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(qR,"schemaHasRulesButRef");G.schemaHasRulesButRef=qR;function $R({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,re._)`${r}`}return(0,re._)`${e}${t}${(0,re.getProperty)(n)}`}o($R,"schemaRefOrVal");G.schemaRefOrVal=$R;function LR(e){return Xp(decodeURIComponent(e))}o(LR,"unescapeFragment");G.unescapeFragment=LR;function jR(e){return encodeURIComponent(Mc(e))}o(jR,"escapeFragment");G.escapeFragment=jR;function Mc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Mc,"escapeJsonPointer");G.escapeJsonPointer=Mc;function Xp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(Xp,"unescapeJsonPointer");G.unescapeJsonPointer=Xp;function HR(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(HR,"eachItem");G.eachItem=HR;function Kp({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,u)=>{let d=s===void 0?i:s instanceof re.Name?(i instanceof re.Name?e(a,i,s):t(a,i,s),s):i instanceof re.Name?(t(a,s,i),i):r(i,s);return u===re.Name&&!(d instanceof re.Name)?n(a,d):d}}o(Kp,"makeMergeEvaluated");G.mergeEvaluated={props:Kp({mergeNames:o((e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,re._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,re._)`${r} || {}`).code((0,re._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,re._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,re._)`${r} || {}`),qc(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:Qp}),items:Kp({mergeNames:o((e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,re._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,re._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,re._)`${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 Qp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,re._)`{}`);return t!==void 0&&qc(e,r,t),r}o(Qp,"evaluatedPropsToName");G.evaluatedPropsToName=Qp;function qc(e,t,r){Object.keys(r).forEach(n=>e.assign((0,re._)`${t}${(0,re.getProperty)(n)}`,!0))}o(qc,"setEvaluated");G.setEvaluated=qc;var Wp={};function GR(e,t){return e.scopeValue("func",{ref:t,code:Wp[t.code]||(Wp[t.code]=new NR._Code(t.code))})}o(GR,"useFunc");G.useFunc=GR;var Dc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Dc||(G.Type=Dc={}));function BR(e,t,r){if(e instanceof re.Name){let n=t===Dc.Num;return r?n?(0,re._)`"[" + ${e} + "]"`:(0,re._)`"['" + ${e} + "']"`:n?(0,re._)`"/" + ${e}`:(0,re._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,re.getProperty)(e).toString():"/"+Mc(e)}o(BR,"getErrorPath");G.getErrorPath=BR;function em(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(em,"checkStrictMode");G.checkStrictMode=em});var $t=T($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Ue=L(),VR={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};$c.default=VR});var mo=T(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var Z=L(),ja=J(),qe=$t();ze.keywordError={message:o(({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`,"message")};ze.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`,"message")};function FR(e,t=ze.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:u}=a,d=nm(e,t,r);n??(s||u)?tm(i,d):rm(a,(0,Z._)`[${d}]`)}o(FR,"reportError");ze.reportError=FR;function ZR(e,t=ze.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,u=nm(e,t,r);tm(a,u),i||s||rm(n,qe.default.vErrors)}o(ZR,"reportExtraError");ze.reportExtraError=ZR;function KR(e,t){e.assign(qe.default.errors,t),e.if((0,Z._)`${qe.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${qe.default.vErrors}.length`,t),()=>e.assign(qe.default.vErrors,null)))}o(KR,"resetErrorsCount");ze.resetErrorsCount=KR;function WR({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,qe.default.errors,u=>{e.const(s,(0,Z._)`${qe.default.vErrors}[${u}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(qe.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}o(WR,"extendErrors");ze.extendErrors=WR;function tm(e,t){let r=e.const("err",t);e.if((0,Z._)`${qe.default.vErrors} === null`,()=>e.assign(qe.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${qe.default.vErrors}.push(${r})`),e.code((0,Z._)`${qe.default.errors}++`)}o(tm,"addError");function rm(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}o(rm,"returnErrors");var Tr={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function nm(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:JR(e,t,r)}o(nm,"errorObjectCode");function JR(e,t,r={}){let{gen:n,it:a}=e,i=[YR(a,r),XR(e,r)];return QR(e,t,i),n.object(...i)}o(JR,"errorObject");function YR({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,ja.getErrorPath)(t,ja.Type.Str)}`:e;return[qe.default.instancePath,(0,Z.strConcat)(qe.default.instancePath,r)]}o(YR,"errorInstancePath");function XR({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,Z.str)`${t}/${e}`;return r&&(a=(0,Z.str)`${a}${(0,ja.getErrorPath)(r,ja.Type.Str)}`),[Tr.schemaPath,a]}o(XR,"errorSchemaPath");function QR(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:s,it:u}=e,{opts:d,propertyName:l,topSchemaRef:p,schemaPath:m}=u;n.push([Tr.keyword,a],[Tr.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),d.messages&&n.push([Tr.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([Tr.schema,s],[Tr.parentSchema,(0,Z._)`${p}${m}`],[qe.default.data,i]),l&&n.push([Tr.propertyName,l])}o(QR,"extraErrorProps")});var am=T(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.boolOrEmptySchema=on.topBoolOrEmptySchema=void 0;var eb=mo(),tb=L(),rb=$t(),nb={message:"boolean schema is false"};function ob(e){let{gen:t,schema:r,validateName:n}=e;r===!1?om(e,!1):typeof r=="object"&&r.$async===!0?t.return(rb.default.data):(t.assign((0,tb._)`${n}.errors`,null),t.return(!0))}o(ob,"topBoolOrEmptySchema");on.topBoolOrEmptySchema=ob;function ab(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),om(e)):r.var(t,!0)}o(ab,"boolOrEmptySchema");on.boolOrEmptySchema=ab;function om(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,eb.reportError)(a,nb,void 0,t)}o(om,"falseSchemaError")});var Lc=T(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.getRules=an.isJSONType=void 0;var ib=["string","number","integer","boolean","null","object","array"],sb=new Set(ib);function cb(e){return typeof e=="string"&&sb.has(e)}o(cb,"isJSONType");an.isJSONType=cb;function ub(){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(ub,"getRules");an.getRules=ub});var jc=T(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.shouldUseRule=ar.shouldUseGroup=ar.schemaHasRulesForType=void 0;function db({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&im(e,n)}o(db,"schemaHasRulesForType");ar.schemaHasRulesForType=db;function im(e,t){return t.rules.some(r=>sm(e,r))}o(im,"shouldUseGroup");ar.shouldUseGroup=im;function sm(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(sm,"shouldUseRule");ar.shouldUseRule=sm});var ho=T(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.reportTypeError=Ne.checkDataTypes=Ne.checkDataType=Ne.coerceAndCheckDataType=Ne.getJSONTypes=Ne.getSchemaTypes=Ne.DataType=void 0;var lb=Lc(),pb=jc(),mb=mo(),$=L(),cm=J(),sn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(sn||(Ne.DataType=sn={}));function hb(e){let t=um(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(hb,"getSchemaTypes");Ne.getSchemaTypes=hb;function um(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(lb.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(um,"getJSONTypes");Ne.getJSONTypes=um;function fb(e,t){let{gen:r,data:n,opts:a}=e,i=gb(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,pb.schemaHasRulesForType)(e,t[0]));if(s){let u=Gc(t,n,a.strictNumbers,sn.Wrong);r.if(u,()=>{i.length?_b(e,t,i):Bc(e)})}return s}o(fb,"coerceAndCheckDataType");Ne.coerceAndCheckDataType=fb;var dm=new Set(["string","number","integer","boolean","null"]);function gb(e,t){return t?e.filter(r=>dm.has(r)||t==="array"&&r==="array"):[]}o(gb,"coerceToTypes");function _b(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,$._)`typeof ${a}`),u=n.let("coerced",(0,$._)`undefined`);i.coerceTypes==="array"&&n.if((0,$._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,$._)`${a}[0]`).assign(s,(0,$._)`typeof ${a}`).if(Gc(t,a,i.strictNumbers),()=>n.assign(u,a))),n.if((0,$._)`${u} !== undefined`);for(let l of r)(dm.has(l)||l==="array"&&i.coerceTypes==="array")&&d(l);n.else(),Bc(e),n.endIf(),n.if((0,$._)`${u} !== undefined`,()=>{n.assign(a,u),yb(e,u)});function d(l){switch(l){case"string":n.elseIf((0,$._)`${s} == "number" || ${s} == "boolean"`).assign(u,(0,$._)`"" + ${a}`).elseIf((0,$._)`${a} === null`).assign(u,(0,$._)`""`);return;case"number":n.elseIf((0,$._)`${s} == "boolean" || ${a} === null
27
+ || (${s} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,$._)`+${a}`);return;case"integer":n.elseIf((0,$._)`${s} === "boolean" || ${a} === null
28
+ || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(u,(0,$._)`+${a}`);return;case"boolean":n.elseIf((0,$._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(u,!1).elseIf((0,$._)`${a} === "true" || ${a} === 1`).assign(u,!0);return;case"null":n.elseIf((0,$._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(u,null);return;case"array":n.elseIf((0,$._)`${s} === "string" || ${s} === "number"
29
+ || ${s} === "boolean" || ${a} === null`).assign(u,(0,$._)`[${a}]`)}}o(d,"coerceSpecificType")}o(_b,"coerceData");function yb({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,$._)`${t} !== undefined`,()=>e.assign((0,$._)`${t}[${r}]`,n))}o(yb,"assignParentData");function Hc(e,t,r,n=sn.Correct){let a=n===sn.Correct?$.operators.EQ:$.operators.NEQ,i;switch(e){case"null":return(0,$._)`${t} ${a} null`;case"array":i=(0,$._)`Array.isArray(${t})`;break;case"object":i=(0,$._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,$._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,$._)`typeof ${t} ${a} ${e}`}return n===sn.Correct?i:(0,$.not)(i);function s(u=$.nil){return(0,$.and)((0,$._)`typeof ${t} == "number"`,u,r?(0,$._)`isFinite(${t})`:$.nil)}}o(Hc,"checkDataType");Ne.checkDataType=Hc;function Gc(e,t,r,n){if(e.length===1)return Hc(e[0],t,r,n);let a,i=(0,cm.toHash)(e);if(i.array&&i.object){let s=(0,$._)`typeof ${t} != "object"`;a=i.null?s:(0,$._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=$.nil;i.number&&delete i.integer;for(let s in i)a=(0,$.and)(a,Hc(s,t,r,n));return a}o(Gc,"checkDataTypes");Ne.checkDataTypes=Gc;var Sb={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,$._)`{type: ${e}}`:(0,$._)`{type: ${t}}`,"params")};function Bc(e){let t=wb(e);(0,mb.reportError)(t,Sb)}o(Bc,"reportTypeError");Ne.reportTypeError=Bc;function wb(e){let{gen:t,data:r,schema:n}=e,a=(0,cm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(wb,"getTypeErrorContext")});var pm=T(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.assignDefaults=void 0;var cn=L(),vb=J();function Rb(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)lm(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>lm(e,i,a.default))}o(Rb,"assignDefaults");Ha.assignDefaults=Rb;function lm(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let u=(0,cn._)`${i}${(0,cn.getProperty)(t)}`;if(a){(0,vb.checkStrictMode)(e,`default is ignored for: ${u}`);return}let d=(0,cn._)`${u} === undefined`;s.useDefaults==="empty"&&(d=(0,cn._)`${d} || ${u} === null || ${u} === ""`),n.if(d,(0,cn._)`${u} = ${(0,cn.stringify)(r)}`)}o(lm,"assignDefault")});var ot=T(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.validateUnion=ee.validateArray=ee.usePattern=ee.callValidateCode=ee.schemaProperties=ee.allSchemaProperties=ee.noPropertyInData=ee.propertyInData=ee.isOwnProperty=ee.hasPropFunc=ee.reportMissingProp=ee.checkMissingProp=ee.checkReportMissingProp=void 0;var ae=L(),Vc=J(),ir=$t(),bb=J();function Ib(e,t){let{gen:r,data:n,it:a}=e;r.if(Zc(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ae._)`${t}`},!0),e.error()})}o(Ib,"checkReportMissingProp");ee.checkReportMissingProp=Ib;function Cb({gen:e,data:t,it:{opts:r}},n,a){return(0,ae.or)(...n.map(i=>(0,ae.and)(Zc(e,t,i,r.ownProperties),(0,ae._)`${a} = ${i}`)))}o(Cb,"checkMissingProp");ee.checkMissingProp=Cb;function Tb(e,t){e.setParams({missingProperty:t},!0),e.error()}o(Tb,"reportMissingProp");ee.reportMissingProp=Tb;function mm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ae._)`Object.prototype.hasOwnProperty`})}o(mm,"hasPropFunc");ee.hasPropFunc=mm;function Fc(e,t,r){return(0,ae._)`${mm(e)}.call(${t}, ${r})`}o(Fc,"isOwnProperty");ee.isOwnProperty=Fc;function Ab(e,t,r,n){let a=(0,ae._)`${t}${(0,ae.getProperty)(r)} !== undefined`;return n?(0,ae._)`${a} && ${Fc(e,t,r)}`:a}o(Ab,"propertyInData");ee.propertyInData=Ab;function Zc(e,t,r,n){let a=(0,ae._)`${t}${(0,ae.getProperty)(r)} === undefined`;return n?(0,ae.or)(a,(0,ae.not)(Fc(e,t,r))):a}o(Zc,"noPropertyInData");ee.noPropertyInData=Zc;function hm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(hm,"allSchemaProperties");ee.allSchemaProperties=hm;function kb(e,t){return hm(t).filter(r=>!(0,Vc.alwaysValidSchema)(e,t[r]))}o(kb,"schemaProperties");ee.schemaProperties=kb;function Eb({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},u,d,l){let p=l?(0,ae._)`${e}, ${t}, ${n}${a}`:t,m=[[ir.default.instancePath,(0,ae.strConcat)(ir.default.instancePath,i)],[ir.default.parentData,s.parentData],[ir.default.parentDataProperty,s.parentDataProperty],[ir.default.rootData,ir.default.rootData]];s.opts.dynamicRef&&m.push([ir.default.dynamicAnchors,ir.default.dynamicAnchors]);let f=(0,ae._)`${p}, ${r.object(...m)}`;return d!==ae.nil?(0,ae._)`${u}.call(${d}, ${f})`:(0,ae._)`${u}(${f})`}o(Eb,"callValidateCode");ee.callValidateCode=Eb;var Pb=(0,ae._)`new RegExp`;function xb({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,ae._)`${a.code==="new RegExp"?Pb:(0,bb.useFunc)(e,a)}(${r}, ${n})`})}o(xb,"usePattern");ee.usePattern=xb;function Ob(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,ae._)`${r}.length`);t.forRange("i",0,d,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Vc.Type.Num},i),t.if((0,ae.not)(i),u)})}o(s,"validateItems")}o(Ob,"validateArray");ee.validateArray=Ob;function Ub(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,Vc.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),u=t.name("_valid");t.block(()=>r.forEach((d,l)=>{let p=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},u);t.assign(s,(0,ae._)`${s} || ${u}`),e.mergeValidEvaluated(p,u)||t.if((0,ae.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(Ub,"validateUnion");ee.validateUnion=Ub});var _m=T(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.validateKeywordUsage=vt.validSchemaType=vt.funcKeywordCode=vt.macroKeywordCode=void 0;var $e=L(),Ar=$t(),zb=ot(),Nb=mo();function Db(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,u=t.macro.call(s.self,a,i,s),d=gm(r,n,u);s.opts.validateSchema!==!1&&s.self.validateSchema(u,!0);let l=r.name("valid");e.subschema({schema:u,schemaPath:$e.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}o(Db,"macroKeywordCode");vt.macroKeywordCode=Db;function Mb(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:u,it:d}=e;$b(d,t);let l=!u&&t.compile?t.compile.call(d.self,i,s,d):t.validate,p=gm(n,a,l),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&&fm(e),w(()=>e.error());else{let v=t.async?_():S();t.modifying&&fm(e),w(()=>qb(e,v))}}o(f,"validateKeyword");function _(){let v=n.let("ruleErrs",null);return n.try(()=>y((0,$e._)`await `),R=>n.assign(m,!1).if((0,$e._)`${R} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,$e._)`${R}.errors`),()=>n.throw(R))),v}o(_,"validateAsync");function S(){let v=(0,$e._)`${p}.errors`;return n.assign(v,null),y($e.nil),v}o(S,"validateSync");function y(v=t.async?(0,$e._)`await `:$e.nil){let R=d.opts.passContext?Ar.default.this:Ar.default.self,C=!("compile"in t&&!u||t.schema===!1);n.assign(m,(0,$e._)`${v}${(0,zb.callValidateCode)(e,p,R,C)}`,t.modifying)}o(y,"assignValid");function w(v){var R;n.if((0,$e.not)((R=t.valid)!==null&&R!==void 0?R:m),v)}o(w,"reportErrs")}o(Mb,"funcKeywordCode");vt.funcKeywordCode=Mb;function fm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,$e._)`${n.parentData}[${n.parentDataProperty}]`))}o(fm,"modifyData");function qb(e,t){let{gen:r}=e;r.if((0,$e._)`Array.isArray(${t})`,()=>{r.assign(Ar.default.vErrors,(0,$e._)`${Ar.default.vErrors} === null ? ${t} : ${Ar.default.vErrors}.concat(${t})`).assign(Ar.default.errors,(0,$e._)`${Ar.default.vErrors}.length`),(0,Nb.extendErrors)(e)},()=>e.error())}o(qb,"addErrs");function $b({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o($b,"checkAsyncKeyword");function gm(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,$e.stringify)(r)})}o(gm,"useKeyword");function Lb(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(Lb,"validSchemaType");vt.validSchemaType=Lb;function jb({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(jb,"validateKeywordUsage");vt.validateKeywordUsage=jb});var Sm=T(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.extendSubschemaMode=sr.extendSubschemaData=sr.getSubschema=void 0;var Rt=L(),ym=J();function Hb(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,Rt._)`${e.schemaPath}${(0,Rt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:u[r],schemaPath:(0,Rt._)`${e.schemaPath}${(0,Rt.getProperty)(t)}${(0,Rt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ym.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(Hb,"getSubschema");sr.getSubschema=Hb;function Gb(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:l,dataPathArr:p,opts:m}=t,f=u.let("data",(0,Rt._)`${t.data}${(0,Rt.getProperty)(r)}`,!0);d(f),e.errorPath=(0,Rt.str)`${l}${(0,ym.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Rt._)`${r}`,e.dataPathArr=[...p,e.parentDataProperty]}if(a!==void 0){let l=a instanceof Rt.Name?a:u.let("data",a,!0);d(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}o(d,"dataContextProps")}o(Gb,"extendSubschemaData");sr.extendSubschemaData=Gb;function Bb(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(Bb,"extendSubschemaMode");sr.extendSubschemaMode=Bb});var Kc=T((_1,wm)=>{"use strict";wm.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 Rm=T((S1,vm)=>{"use strict";var cr=vm.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(){};Ga(t,n,a,e,"",e)};cr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};cr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};cr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};cr.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 Ga(e,t,r,n,a,i,s,u,d,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,s,u,d,l);for(var p in n){var m=n[p];if(Array.isArray(m)){if(p in cr.arrayKeywords)for(var f=0;f<m.length;f++)Ga(e,t,r,m[f],a+"/"+p+"/"+f,i,a,p,n,f)}else if(p in cr.propsKeywords){if(m&&typeof m=="object")for(var _ in m)Ga(e,t,r,m[_],a+"/"+p+"/"+Vb(_),i,a,p,n,_)}else(p in cr.keywords||e.allKeys&&!(p in cr.skipKeywords))&&Ga(e,t,r,m,a+"/"+p,i,a,p,n)}r(n,a,i,s,u,d,l)}}o(Ga,"_traverse");function Vb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Vb,"escapeJsonPtr")});var fo=T(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.getSchemaRefs=Be.resolveUrl=Be.normalizeId=Be._getFullPath=Be.getFullPath=Be.inlineRef=void 0;var Fb=J(),Zb=Kc(),Kb=Rm(),Wb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Jb(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Wc(e):t?bm(e)<=t:!1}o(Jb,"inlineRef");Be.inlineRef=Jb;var Yb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wc(e){for(let t in e){if(Yb.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Wc)||typeof r=="object"&&Wc(r))return!0}return!1}o(Wc,"hasRef");function bm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Wb.has(r)&&(typeof e[r]=="object"&&(0,Fb.eachItem)(e[r],n=>t+=bm(n)),t===1/0))return 1/0}return t}o(bm,"countKeys");function Im(e,t="",r){r!==!1&&(t=un(t));let n=e.parse(t);return Cm(e,n)}o(Im,"getFullPath");Be.getFullPath=Im;function Cm(e,t){return e.serialize(t).split("#")[0]+"#"}o(Cm,"_getFullPath");Be._getFullPath=Cm;var Xb=/#\/?$/;function un(e){return e?e.replace(Xb,""):""}o(un,"normalizeId");Be.normalizeId=un;function Qb(e,t,r){return r=un(r),e.resolve(t,r)}o(Qb,"resolveUrl");Be.resolveUrl=Qb;var eI=/^[a-z_][-a-z0-9._]*$/i;function tI(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=un(e[r]||t),i={"":a},s=Im(n,a,!1),u={},d=new Set;return Kb(e,{allKeys:!0},(m,f,_,S)=>{if(S===void 0)return;let y=s+f,w=i[S];typeof m[r]=="string"&&(w=v.call(this,m[r])),R.call(this,m.$anchor),R.call(this,m.$dynamicAnchor),i[f]=w;function v(C){let N=this.opts.uriResolver.resolve;if(C=un(w?N(w,C):C),d.has(C))throw p(C);d.add(C);let M=this.refs[C];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?l(m,M.schema,C):C!==un(y)&&(C[0]==="#"?(l(m,u[C],C),u[C]=m):this.refs[C]=y),C}o(v,"addRef");function R(C){if(typeof C=="string"){if(!eI.test(C))throw new Error(`invalid anchor "${C}"`);v.call(this,`#${C}`)}}o(R,"addAnchor")}),u;function l(m,f,_){if(f!==void 0&&!Zb(m,f))throw p(_)}o(l,"checkAmbiguosRef");function p(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(p,"ambiguos")}o(tI,"getSchemaRefs");Be.getSchemaRefs=tI});var yo=T(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.getData=ur.KeywordCxt=ur.validateFunctionCode=void 0;var Pm=am(),Tm=ho(),Yc=jc(),Ba=ho(),rI=pm(),_o=_m(),Jc=Sm(),P=L(),D=$t(),nI=fo(),Lt=J(),go=mo();function oI(e){if(Um(e)&&(zm(e),Om(e))){sI(e);return}xm(e,()=>(0,Pm.topBoolOrEmptySchema)(e))}o(oI,"validateFunctionCode");ur.validateFunctionCode=oI;function xm({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,P._)`${D.default.data}, ${D.default.valCxt}`,n.$async,()=>{e.code((0,P._)`"use strict"; ${Am(r,a)}`),iI(e,a),e.code(i)}):e.func(t,(0,P._)`${D.default.data}, ${aI(a)}`,n.$async,()=>e.code(Am(r,a)).code(i))}o(xm,"validateFunction");function aI(e){return(0,P._)`{${D.default.instancePath}="", ${D.default.parentData}, ${D.default.parentDataProperty}, ${D.default.rootData}=${D.default.data}${e.dynamicRef?(0,P._)`, ${D.default.dynamicAnchors}={}`:P.nil}}={}`}o(aI,"destructureValCxt");function iI(e,t){e.if(D.default.valCxt,()=>{e.var(D.default.instancePath,(0,P._)`${D.default.valCxt}.${D.default.instancePath}`),e.var(D.default.parentData,(0,P._)`${D.default.valCxt}.${D.default.parentData}`),e.var(D.default.parentDataProperty,(0,P._)`${D.default.valCxt}.${D.default.parentDataProperty}`),e.var(D.default.rootData,(0,P._)`${D.default.valCxt}.${D.default.rootData}`),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,P._)`${D.default.valCxt}.${D.default.dynamicAnchors}`)},()=>{e.var(D.default.instancePath,(0,P._)`""`),e.var(D.default.parentData,(0,P._)`undefined`),e.var(D.default.parentDataProperty,(0,P._)`undefined`),e.var(D.default.rootData,D.default.data),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,P._)`{}`)})}o(iI,"destructureValCxtES5");function sI(e){let{schema:t,opts:r,gen:n}=e;xm(e,()=>{r.$comment&&t.$comment&&Dm(e),pI(e),n.let(D.default.vErrors,null),n.let(D.default.errors,0),r.unevaluated&&cI(e),Nm(e),fI(e)})}o(sI,"topSchemaObjCode");function cI(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,P._)`${r}.evaluated`),t.if((0,P._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,P._)`${e.evaluated}.props`,(0,P._)`undefined`)),t.if((0,P._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,P._)`${e.evaluated}.items`,(0,P._)`undefined`))}o(cI,"resetEvaluated");function Am(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,P._)`/*# sourceURL=${r} */`:P.nil}o(Am,"funcSourceUrl");function uI(e,t){if(Um(e)&&(zm(e),Om(e))){dI(e,t);return}(0,Pm.boolOrEmptySchema)(e,t)}o(uI,"subschemaCode");function Om({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(Om,"schemaCxtHasRules");function Um(e){return typeof e.schema!="boolean"}o(Um,"isSchemaObj");function dI(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&Dm(e),mI(e),hI(e);let i=n.const("_errs",D.default.errors);Nm(e,i),n.var(t,(0,P._)`${i} === ${D.default.errors}`)}o(dI,"subSchemaObjCode");function zm(e){(0,Lt.checkUnknownRules)(e),lI(e)}o(zm,"checkKeywords");function Nm(e,t){if(e.opts.jtd)return km(e,[],!1,t);let r=(0,Tm.getSchemaTypes)(e.schema),n=(0,Tm.coerceAndCheckDataType)(e,r);km(e,r,!n,t)}o(Nm,"typeAndKeywords");function lI(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Lt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(lI,"checkRefsAndKeywords");function pI(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Lt.checkStrictMode)(e,"default is ignored in the schema root")}o(pI,"checkNoDefault");function mI(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,nI.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(mI,"updateContext");function hI(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(hI,"checkAsyncSchema");function Dm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,P._)`${D.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,P.str)`${n}/$comment`,u=e.scopeValue("root",{ref:t.root});e.code((0,P._)`${D.default.self}.opts.$comment(${i}, ${s}, ${u}.schema)`)}}o(Dm,"commentKeyword");function fI(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,P._)`${D.default.errors} === 0`,()=>t.return(D.default.data),()=>t.throw((0,P._)`new ${a}(${D.default.vErrors})`)):(t.assign((0,P._)`${n}.errors`,D.default.vErrors),i.unevaluated&&gI(e),t.return((0,P._)`${D.default.errors} === 0`))}o(fI,"returnResults");function gI({gen:e,evaluated:t,props:r,items:n}){r instanceof P.Name&&e.assign((0,P._)`${t}.props`,r),n instanceof P.Name&&e.assign((0,P._)`${t}.items`,n)}o(gI,"assignEvaluated");function km(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:u,opts:d,self:l}=e,{RULES:p}=l;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Lt.schemaHasRulesButRef)(i,p))){a.block(()=>qm(e,"$ref",p.all.$ref.definition));return}d.jtd||_I(e,t),a.block(()=>{for(let f of p.rules)m(f);m(p.post)});function m(f){(0,Yc.shouldUseGroup)(i,f)&&(f.type?(a.if((0,Ba.checkDataType)(f.type,s,d.strictNumbers)),Em(e,f),t.length===1&&t[0]===f.type&&r&&(a.else(),(0,Ba.reportTypeError)(e)),a.endIf()):Em(e,f),u||a.if((0,P._)`${D.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(km,"schemaKeywords");function Em(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,rI.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Yc.shouldUseRule)(n,i)&&qm(e,i.keyword,i.definition,t.type)})}o(Em,"iterateKeywords");function _I(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(yI(e,t),e.opts.allowUnionTypes||SI(e,t),wI(e,e.dataTypes))}o(_I,"checkStrictTypes");function yI(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Mm(e.dataTypes,r)||Xc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),RI(e,t)}}o(yI,"checkContextTypes");function SI(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Xc(e,"use allowUnionTypes to allow union type keyword")}o(SI,"checkMultipleTypes");function wI(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Yc.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>vI(t,s))&&Xc(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(wI,"checkKeywordTypes");function vI(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(vI,"hasApplicableType");function Mm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(Mm,"includesType");function RI(e,t){let r=[];for(let n of e.dataTypes)Mm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(RI,"narrowSchemaTypes");function Xc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Lt.checkStrictMode)(e,t,e.opts.strictTypes)}o(Xc,"strictTypesError");var Va=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,_o.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,Lt.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",$m(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,_o.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",D.default.errors))}result(t,r,n){this.failResult((0,P.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,P.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,P._)`${r} !== undefined && (${(0,P.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?go.reportExtraError:go.reportError)(this,this.def.error,r)}$dataError(){(0,go.reportError)(this,this.def.$dataError||go.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,go.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=P.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=P.nil,r=P.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,P.or)((0,P._)`${a} === undefined`,r)),t!==P.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==P.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,P.or)(s(),u());function s(){if(n.length){if(!(r instanceof P.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,P._)`${(0,Ba.checkDataTypes)(d,r,i.opts.strictNumbers,Ba.DataType.Wrong)}`}return P.nil}function u(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,P._)`!${d}(${r})`}return P.nil}}subschema(t,r){let n=(0,Jc.getSubschema)(this.it,t);(0,Jc.extendSubschemaData)(n,this.it,t),(0,Jc.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return uI(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Lt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Lt.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,P.Name)),!0}};ur.KeywordCxt=Va;function qm(e,t,r,n){let a=new Va(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,_o.funcKeywordCode)(a,r):"macro"in r?(0,_o.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,_o.funcKeywordCode)(a,r)}o(qm,"keywordCode");var bI=/^\/(?:[^~]|~0|~1)*$/,II=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function $m(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return D.default.rootData;if(e[0]==="/"){if(!bI.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=D.default.rootData}else{let l=II.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let p=+l[1];if(a=l[2],a==="#"){if(p>=t)throw new Error(d("property/index",p));return n[t-p]}if(p>t)throw new Error(d("data",p));if(i=r[t-p],!a)return i}let s=i,u=a.split("/");for(let l of u)l&&(i=(0,P._)`${i}${(0,P.getProperty)((0,Lt.unescapeJsonPointer)(l))}`,s=(0,P._)`${s} && ${i}`);return s;function d(l,p){return`Cannot access ${l} ${p} levels up, current level is ${t}`}}o($m,"getData");ur.getData=$m});var Fa=T(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Qc=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};eu.default=Qc});var So=T(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var tu=fo(),ru=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,tu.resolveUrl)(t,r,n),this.missingSchema=(0,tu.normalizeId)((0,tu.getFullPath)(t,this.missingRef))}};nu.default=ru});var Ka=T(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;var pt=L(),CI=Fa(),kr=$t(),mt=fo(),Lm=J(),TI=yo(),dn=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,mt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};at.SchemaEnv=dn;function au(e){let t=jm.call(this,e);if(t)return t;let r=(0,mt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new pt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),u;e.$async&&(u=s.scopeValue("Error",{ref:CI.default,code:(0,pt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let l={gen:s,allErrors:this.opts.allErrors,data:kr.default.data,parentData:kr.default.parentData,parentDataProperty:kr.default.parentDataProperty,dataNames:[kr.default.data],dataPathArr:[pt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,pt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:u,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:pt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,pt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(e),(0,TI.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let m=s.toString();p=`${s.scopeRefs(kr.default.scope)}return ${m}`,this.opts.code.process&&(p=this.opts.code.process(p,e));let _=new Function(`${kr.default.self}`,`${kr.default.scope}`,p)(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:S,items:y}=l;_.evaluated={props:S instanceof pt.Name?void 0:S,items:y instanceof pt.Name?void 0:y,dynamicProps:S instanceof pt.Name,dynamicItems:y instanceof pt.Name},_.source&&(_.source.evaluated=(0,pt.stringify)(_.evaluated))}return e.validate=_,e}catch(m){throw delete e.validate,delete e.validateName,p&&this.logger.error("Error compiling schema, function code:",p),m}finally{this._compilations.delete(e)}}o(au,"compileSchema");at.compileSchema=au;function AI(e,t,r){var n;r=(0,mt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=PI.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 dn({schema:s,schemaId:u,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=kI.call(this,i)}o(AI,"resolveRef");at.resolveRef=AI;function kI(e){return(0,mt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:au.call(this,e)}o(kI,"inlineOrCompile");function jm(e){for(let t of this._compilations)if(EI(t,e))return t}o(jm,"getCompilingSchema");at.getCompilingSchema=jm;function EI(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(EI,"sameSchemaEnv");function PI(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Za.call(this,e,t)}o(PI,"resolve");function Za(e,t){let r=this.opts.uriResolver.parse(t),n=(0,mt._getFullPath)(this.opts.uriResolver,r),a=(0,mt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return ou.call(this,r,e);let i=(0,mt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let u=Za.call(this,e,s);return typeof u?.schema!="object"?void 0:ou.call(this,r,u)}if(typeof s?.schema=="object"){if(s.validate||au.call(this,s),i===(0,mt.normalizeId)(t)){let{schema:u}=s,{schemaId:d}=this.opts,l=u[d];return l&&(a=(0,mt.resolveUrl)(this.opts.uriResolver,a,l)),new dn({schema:u,schemaId:d,root:e,baseId:a})}return ou.call(this,r,s)}}o(Za,"resolveSchema");at.resolveSchema=Za;var xI=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ou(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,Lm.unescapeFragment)(u)];if(d===void 0)return;r=d;let l=typeof r=="object"&&r[this.opts.schemaId];!xI.has(u)&&l&&(t=(0,mt.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Lm.schemaHasRulesButRef)(r,this.RULES)){let u=(0,mt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Za.call(this,n,u)}let{schemaId:s}=this.opts;if(i=i||new dn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(ou,"getJsonPointer")});var Hm=T((x1,OI)=>{OI.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 su=T((O1,Fm)=>{"use strict";var UI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Bm=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 iu(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(iu,"stringArrayToHexStripped");var zI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Gm(e){return e.length=0,!0}o(Gm,"consumeIsZone");function NI(e,t,r){if(e.length){let n=iu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(NI,"consumeHextets");function DI(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,u=NI;for(let d=0;d<e.length;d++){let l=e[d];if(!(l==="["||l==="]"))if(l===":"){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(l==="%"){if(!u(a,n,r))break;u=Gm}else{a.push(l);continue}}return a.length&&(u===Gm?r.zone=a.join(""):s?n.push(a.join("")):n.push(iu(a))),r.address=n.join(""),r}o(DI,"getIPV6");function Vm(e){if(MI(e,":")<2)return{host:e,isIPV6:!1};let t=DI(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(Vm,"normalizeIPv6");function MI(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(MI,"findToken");function qI(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(qI,"removeDotSegments");function $I(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($I,"normalizeComponentEncoding");function LI(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Bm(r)){let n=Vm(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(LI,"recomposeAuthority");Fm.exports={nonSimpleDomain:zI,recomposeAuthority:LI,normalizeComponentEncoding:$I,removeDotSegments:qI,isIPv4:Bm,isUUID:UI,normalizeIPv6:Vm,stringArrayToHexStripped:iu}});var Ym=T((z1,Jm)=>{"use strict";var{isUUID:jI}=su(),HI=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,GI=["http","https","ws","wss","urn","urn:uuid"];function BI(e){return GI.indexOf(e)!==-1}o(BI,"isValidSchemeName");function cu(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(cu,"wsIsSecure");function Zm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(Zm,"httpParse");function Km(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(Km,"httpSerialize");function VI(e){return e.secure=cu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(VI,"wsParse");function FI(e){if((e.port===(cu(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(FI,"wsSerialize");function ZI(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=uu(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(ZI,"urnParse");function KI(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=uu(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(KI,"urnSerialize");function WI(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!jI(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(WI,"urnuuidParse");function JI(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(JI,"urnuuidSerialize");var Wm={scheme:"http",domainHost:!0,parse:Zm,serialize:Km},YI={scheme:"https",domainHost:Wm.domainHost,parse:Zm,serialize:Km},Wa={scheme:"ws",domainHost:!0,parse:VI,serialize:FI},XI={scheme:"wss",domainHost:Wa.domainHost,parse:Wa.parse,serialize:Wa.serialize},QI={scheme:"urn",parse:ZI,serialize:KI,skipNormalize:!0},eC={scheme:"urn:uuid",parse:WI,serialize:JI,skipNormalize:!0},Ja={http:Wm,https:YI,ws:Wa,wss:XI,urn:QI,"urn:uuid":eC};Object.setPrototypeOf(Ja,null);function uu(e){return e&&(Ja[e]||Ja[e.toLowerCase()])||void 0}o(uu,"getSchemeHandler");Jm.exports={wsIsSecure:cu,SCHEMES:Ja,isValidSchemeName:BI,getSchemeHandler:uu}});var eh=T((D1,Xa)=>{"use strict";var{normalizeIPv6:tC,removeDotSegments:wo,recomposeAuthority:rC,normalizeComponentEncoding:Ya,isIPv4:nC,nonSimpleDomain:oC}=su(),{SCHEMES:aC,getSchemeHandler:Xm}=Ym();function iC(e,t){return typeof e=="string"?e=bt(jt(e,t),t):typeof e=="object"&&(e=jt(bt(e,t),t)),e}o(iC,"normalize");function sC(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=Qm(jt(e,n),jt(t,n),n,!0);return n.skipEscape=!0,bt(a,n)}o(sC,"resolve");function Qm(e,t,r,n){let a={};return n||(e=jt(bt(e,r),r),t=jt(bt(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=wo(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=wo(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=wo(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=wo(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(Qm,"resolveComponent");function cC(e,t,r){return typeof e=="string"?(e=unescape(e),e=bt(Ya(jt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=bt(Ya(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=bt(Ya(jt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=bt(Ya(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(cC,"equal");function bt(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=Xm(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=rC(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=wo(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(bt,"serialize");var uC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function jt(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(uC);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(nC(n.host)===!1){let d=tC(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=Xm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&oC(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(jt,"parse");var du={SCHEMES:aC,normalize:iC,resolve:sC,resolveComponent:Qm,equal:cC,serialize:bt,parse:jt};Xa.exports=du;Xa.exports.default=du;Xa.exports.fastUri=du});var rh=T(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var th=eh();th.code='require("ajv/dist/runtime/uri").default';lu.default=th});var dh=T(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.CodeGen=Te.Name=Te.nil=Te.stringify=Te.str=Te._=Te.KeywordCxt=void 0;var dC=yo();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:o(function(){return dC.KeywordCxt},"get")});var ln=L();Object.defineProperty(Te,"_",{enumerable:!0,get:o(function(){return ln._},"get")});Object.defineProperty(Te,"str",{enumerable:!0,get:o(function(){return ln.str},"get")});Object.defineProperty(Te,"stringify",{enumerable:!0,get:o(function(){return ln.stringify},"get")});Object.defineProperty(Te,"nil",{enumerable:!0,get:o(function(){return ln.nil},"get")});Object.defineProperty(Te,"Name",{enumerable:!0,get:o(function(){return ln.Name},"get")});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:o(function(){return ln.CodeGen},"get")});var lC=Fa(),sh=So(),pC=Lc(),vo=Ka(),mC=L(),Ro=fo(),Qa=ho(),mu=J(),nh=Hm(),hC=rh(),ch=o((e,t)=>new RegExp(e,t),"defaultRegExp");ch.code="new RegExp";var fC=["removeAdditional","useDefaults","coerceTypes"],gC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_C={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."},yC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},oh=200;function SC(e){var t,r,n,a,i,s,u,d,l,p,m,f,_,S,y,w,v,R,C,N,M,Ye,Ot,Us,zs;let Bn=e.strict,Ns=(t=e.code)===null||t===void 0?void 0:t.optimize,mp=Ns===!0||Ns===void 0?1:Ns||0,hp=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:ch,Ww=(a=e.uriResolver)!==null&&a!==void 0?a:hC.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Bn)!==null&&s!==void 0?s:!0,strictNumbers:(d=(u=e.strictNumbers)!==null&&u!==void 0?u:Bn)!==null&&d!==void 0?d:!0,strictTypes:(p=(l=e.strictTypes)!==null&&l!==void 0?l:Bn)!==null&&p!==void 0?p:"log",strictTuples:(f=(m=e.strictTuples)!==null&&m!==void 0?m:Bn)!==null&&f!==void 0?f:"log",strictRequired:(S=(_=e.strictRequired)!==null&&_!==void 0?_:Bn)!==null&&S!==void 0?S:!1,code:e.code?{...e.code,optimize:mp,regExp:hp}:{optimize:mp,regExp:hp},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:oh,loopEnum:(w=e.loopEnum)!==null&&w!==void 0?w:oh,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(R=e.messages)!==null&&R!==void 0?R:!0,inlineRefs:(C=e.inlineRefs)!==null&&C!==void 0?C:!0,schemaId:(N=e.schemaId)!==null&&N!==void 0?N:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Ye=e.validateSchema)!==null&&Ye!==void 0?Ye:!0,validateFormats:(Ot=e.validateFormats)!==null&&Ot!==void 0?Ot:!0,unicodeRegExp:(Us=e.unicodeRegExp)!==null&&Us!==void 0?Us:!0,int32range:(zs=e.int32range)!==null&&zs!==void 0?zs:!0,uriResolver:Ww}}o(SC,"requiredOptions");var bo=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,...SC(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new mC.ValueScope({scope:{},prefixes:gC,es5:r,lines:n}),this.logger=CC(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,pC.getRules)(),ah.call(this,_C,t,"NOT SUPPORTED"),ah.call(this,yC,t,"DEPRECATED","warn"),this._metaOpts=bC.call(this),t.formats&&vC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&RC.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),wC.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=nh;n==="id"&&(a={...nh},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(p,m){await i.call(this,p.$schema);let f=this._addSchema(p,m);return f.validate||s.call(this,f)}async function i(p){p&&!this.getSchema(p)&&await a.call(this,{$ref:p},!0)}async function s(p){try{return this._compileSchemaEnv(p)}catch(m){if(!(m instanceof sh.default))throw m;return u.call(this,m),await d.call(this,m.missingSchema),s.call(this,p)}}function u({missingSchema:p,missingRef:m}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${m} cannot be resolved`)}async function d(p){let m=await l.call(this,p);this.refs[p]||await i.call(this,m.$schema),this.refs[p]||this.addSchema(m,p,r)}async function l(p){let m=this._loading[p];if(m)return m;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}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,Ro.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=ih.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new vo.SchemaEnv({schema:{},schemaId:n});if(r=vo.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=ih.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,Ro.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(AC.call(this,n,r),!r)return(0,mu.eachItem)(n,i=>pu.call(this,i)),this;EC.call(this,r);let a={...r,type:(0,Qa.getJSONTypes)(r.type),schemaType:(0,Qa.getJSONTypes)(r.schemaType)};return(0,mu.eachItem)(n,a.type.length===0?i=>pu.call(this,i,a):i=>a.type.forEach(s=>pu.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:l}=d.definition,p=s[u];l&&p&&(s[u]=uh(p))}}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,Ro.normalizeId)(s||n);let l=Ro.getSchemaRefs.call(this,t,n);return d=new vo.SchemaEnv({schema:t,schemaId:u,meta:r,baseId:n,localRefs:l}),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):vo.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{vo.compileSchema.call(this,t)}finally{this.opts=r}}};bo.ValidationError=lC.default;bo.MissingRefError=sh.default;Te.default=bo;function ah(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(ah,"checkOptions");function ih(e){return e=(0,Ro.normalizeId)(e),this.schemas[e]||this.refs[e]}o(ih,"getSchEnv");function wC(){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(wC,"addInitialSchemas");function vC(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(vC,"addInitialFormats");function RC(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(RC,"addInitialKeywords");function bC(){let e={...this.opts};for(let t of fC)delete e[t];return e}o(bC,"getMetaSchemaOptions");var IC={log(){},warn(){},error(){}};function CC(e){if(e===!1)return IC;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(CC,"getLogger");var TC=/^[a-z_$][a-z0-9_$:-]*$/i;function AC(e,t){let{RULES:r}=this;if((0,mu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!TC.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(AC,"checkKeyword");function pu(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,Qa.getJSONTypes)(t.type),schemaType:(0,Qa.getJSONTypes)(t.schemaType)}};t.before?kC.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(pu,"addRule");function kC(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(kC,"addBeforeRule");function EC(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=uh(t)),e.validateSchema=this.compile(t,!0))}o(EC,"keywordMetaschema");var PC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function uh(e){return{anyOf:[e,PC]}}o(uh,"schemaOrData")});var lh=T(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var xC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hu.default=xC});var fh=T(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.callRef=Er.getValidate=void 0;var OC=So(),ph=ot(),Ve=L(),pn=$t(),mh=Ka(),ei=J(),UC={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:l}=i;if((r==="#"||r==="#/")&&a===l.baseId)return m();let p=mh.resolveRef.call(d,l,a,r);if(p===void 0)throw new OC.default(n.opts.uriResolver,a,r);if(p instanceof mh.SchemaEnv)return f(p);return _(p);function m(){if(i===l)return ti(e,s,i,i.$async);let S=t.scopeValue("root",{ref:l});return ti(e,(0,Ve._)`${S}.validate`,l,l.$async)}function f(S){let y=hh(e,S);ti(e,y,S,S.$async)}function _(S){let y=t.scopeValue("schema",u.code.source===!0?{ref:S,code:(0,Ve.stringify)(S)}:{ref:S}),w=t.name("valid"),v=e.subschema({schema:S,dataTypes:[],schemaPath:Ve.nil,topSchemaRef:y,errSchemaPath:r},w);e.mergeEvaluated(v),e.ok(w)}}};function hh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ve._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(hh,"getValidate");Er.getValidate=hh;function ti(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:u,opts:d}=i,l=d.passContext?pn.default.this:Ve.nil;n?p():m();function p(){if(!u.$async)throw new Error("async schema referenced by sync schema");let S=a.let("valid");a.try(()=>{a.code((0,Ve._)`await ${(0,ph.callValidateCode)(e,t,l)}`),_(t),s||a.assign(S,!0)},y=>{a.if((0,Ve._)`!(${y} instanceof ${i.ValidationError})`,()=>a.throw(y)),f(y),s||a.assign(S,!1)}),e.ok(S)}o(p,"callAsyncRef");function m(){e.result((0,ph.callValidateCode)(e,t,l),()=>_(t),()=>f(t))}o(m,"callSyncRef");function f(S){let y=(0,Ve._)`${S}.errors`;a.assign(pn.default.vErrors,(0,Ve._)`${pn.default.vErrors} === null ? ${y} : ${pn.default.vErrors}.concat(${y})`),a.assign(pn.default.errors,(0,Ve._)`${pn.default.vErrors}.length`)}o(f,"addErrorsFrom");function _(S){var y;if(!i.opts.unevaluated)return;let w=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(i.props=ei.mergeEvaluated.props(a,w.props,i.props));else{let v=a.var("props",(0,Ve._)`${S}.evaluated.props`);i.props=ei.mergeEvaluated.props(a,v,i.props,Ve.Name)}if(i.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(i.items=ei.mergeEvaluated.items(a,w.items,i.items));else{let v=a.var("items",(0,Ve._)`${S}.evaluated.items`);i.items=ei.mergeEvaluated.items(a,v,i.items,Ve.Name)}}o(_,"addEvaluatedFrom")}o(ti,"callRef");Er.callRef=ti;Er.default=UC});var gh=T(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var zC=lh(),NC=fh(),DC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zC.default,NC.default];fu.default=DC});var _h=T(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});var ri=L(),dr=ri.operators,ni={maximum:{okStr:"<=",ok:dr.LTE,fail:dr.GT},minimum:{okStr:">=",ok:dr.GTE,fail:dr.LT},exclusiveMaximum:{okStr:"<",ok:dr.LT,fail:dr.GTE},exclusiveMinimum:{okStr:">",ok:dr.GT,fail:dr.LTE}},MC={message:o(({keyword:e,schemaCode:t})=>(0,ri.str)`must be ${ni[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ri._)`{comparison: ${ni[e].okStr}, limit: ${t}}`,"params")},qC={keyword:Object.keys(ni),type:"number",schemaType:"number",$data:!0,error:MC,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ri._)`${r} ${ni[t].fail} ${n} || isNaN(${r})`)}};gu.default=qC});var yh=T(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var Io=L(),$C={message:o(({schemaCode:e})=>(0,Io.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Io._)`{multipleOf: ${e}}`,"params")},LC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$C,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),u=i?(0,Io._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Io._)`${s} !== parseInt(${s})`;e.fail$data((0,Io._)`(${n} === 0 || (${s} = ${r}/${n}, ${u}))`)}};_u.default=LC});var wh=T(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});function Sh(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(Sh,"ucs2length");yu.default=Sh;Sh.code='require("ajv/dist/runtime/ucs2length").default'});var vh=T(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var Pr=L(),jC=J(),HC=wh(),GC={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Pr.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,Pr._)`{limit: ${e}}`,"params")},BC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:GC,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Pr.operators.GT:Pr.operators.LT,s=a.opts.unicode===!1?(0,Pr._)`${r}.length`:(0,Pr._)`${(0,jC.useFunc)(e.gen,HC.default)}(${r})`;e.fail$data((0,Pr._)`${s} ${i} ${n}`)}};Su.default=BC});var Rh=T(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var VC=ot(),oi=L(),FC={message:o(({schemaCode:e})=>(0,oi.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,oi._)`{pattern: ${e}}`,"params")},ZC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:FC,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",u=r?(0,oi._)`(new RegExp(${a}, ${s}))`:(0,VC.usePattern)(e,n);e.fail$data((0,oi._)`!${u}.test(${t})`)}};wu.default=ZC});var bh=T(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var Co=L(),KC={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Co.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Co._)`{limit: ${e}}`,"params")},WC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:KC,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Co.operators.GT:Co.operators.LT;e.fail$data((0,Co._)`Object.keys(${r}).length ${a} ${n}`)}};vu.default=WC});var Ih=T(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});var To=ot(),Ao=L(),JC=J(),YC={message:o(({params:{missingProperty:e}})=>(0,Ao.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Ao._)`{missingProperty: ${e}}`,"params")},XC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:YC,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?l():p(),u.strictRequired){let _=e.parentSchema.properties,{definedProperties:S}=e.it;for(let y of r)if(_?.[y]===void 0&&!S.has(y)){let w=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,JC.checkStrictMode)(s,v,s.opts.strictRequired)}}function l(){if(d||i)e.block$data(Ao.nil,m);else for(let _ of r)(0,To.checkReportMissingProp)(e,_)}o(l,"allErrorsMode");function p(){let _=t.let("missing");if(d||i){let S=t.let("valid",!0);e.block$data(S,()=>f(_,S)),e.ok(S)}else t.if((0,To.checkMissingProp)(e,r,_)),(0,To.reportMissingProp)(e,_),t.else()}o(p,"exitOnErrorMode");function m(){t.forOf("prop",n,_=>{e.setParams({missingProperty:_}),t.if((0,To.noPropertyInData)(t,a,_,u.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function f(_,S){e.setParams({missingProperty:_}),t.forOf(_,n,()=>{t.assign(S,(0,To.propertyInData)(t,a,_,u.ownProperties)),t.if((0,Ao.not)(S),()=>{e.error(),t.break()})},Ao.nil)}o(f,"loopUntilMissing")}};Ru.default=XC});var Ch=T(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var ko=L(),QC={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,ko.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,ko._)`{limit: ${e}}`,"params")},eT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:QC,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?ko.operators.GT:ko.operators.LT;e.fail$data((0,ko._)`${r}.length ${a} ${n}`)}};bu.default=eT});var ai=T(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});var Th=Kc();Th.code='require("ajv/dist/runtime/equal").default';Iu.default=Th});var Ah=T(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});var Cu=ho(),Ae=L(),tT=J(),rT=ai(),nT={message:o(({params:{i:e,j:t}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,Ae._)`{i: ${e}, j: ${t}}`,"params")},oT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:nT,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"),l=i.items?(0,Cu.getSchemaTypes)(i.items):[];e.block$data(d,p,(0,Ae._)`${s} === false`),e.ok(d);function p(){let S=t.let("i",(0,Ae._)`${r}.length`),y=t.let("j");e.setParams({i:S,j:y}),t.assign(d,!0),t.if((0,Ae._)`${S} > 1`,()=>(m()?f:_)(S,y))}o(p,"validateUniqueItems");function m(){return l.length>0&&!l.some(S=>S==="object"||S==="array")}o(m,"canOptimize");function f(S,y){let w=t.name("item"),v=(0,Cu.checkDataTypes)(l,w,u.opts.strictNumbers,Cu.DataType.Wrong),R=t.const("indices",(0,Ae._)`{}`);t.for((0,Ae._)`;${S}--;`,()=>{t.let(w,(0,Ae._)`${r}[${S}]`),t.if(v,(0,Ae._)`continue`),l.length>1&&t.if((0,Ae._)`typeof ${w} == "string"`,(0,Ae._)`${w} += "_"`),t.if((0,Ae._)`typeof ${R}[${w}] == "number"`,()=>{t.assign(y,(0,Ae._)`${R}[${w}]`),e.error(),t.assign(d,!1).break()}).code((0,Ae._)`${R}[${w}] = ${S}`)})}o(f,"loopN");function _(S,y){let w=(0,tT.useFunc)(t,rT.default),v=t.name("outer");t.label(v).for((0,Ae._)`;${S}--;`,()=>t.for((0,Ae._)`${y} = ${S}; ${y}--;`,()=>t.if((0,Ae._)`${w}(${r}[${S}], ${r}[${y}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(_,"loopN2")}};Tu.default=oT});var kh=T(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var Au=L(),aT=J(),iT=ai(),sT={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,Au._)`{allowedValue: ${e}}`,"params")},cT={keyword:"const",$data:!0,error:sT,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Au._)`!${(0,aT.useFunc)(t,iT.default)}(${r}, ${a})`):e.fail((0,Au._)`${i} !== ${r}`)}};ku.default=cT});var Eh=T(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});var Eo=L(),uT=J(),dT=ai(),lT={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Eo._)`{allowedValues: ${e}}`,"params")},pT={keyword:"enum",schemaType:"array",$data:!0,error:lT,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,l=o(()=>d??(d=(0,uT.useFunc)(t,dT.default)),"getEql"),p;if(u||n)p=t.let("valid"),e.block$data(p,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let _=t.const("vSchema",i);p=(0,Eo.or)(...a.map((S,y)=>f(_,y)))}e.pass(p);function m(){t.assign(p,!1),t.forOf("v",i,_=>t.if((0,Eo._)`${l()}(${r}, ${_})`,()=>t.assign(p,!0).break()))}o(m,"loopEnum");function f(_,S){let y=a[S];return typeof y=="object"&&y!==null?(0,Eo._)`${l()}(${r}, ${_}[${S}])`:(0,Eo._)`${r} === ${y}`}o(f,"equalCode")}};Eu.default=pT});var Ph=T(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});var mT=_h(),hT=yh(),fT=vh(),gT=Rh(),_T=bh(),yT=Ih(),ST=Ch(),wT=Ah(),vT=kh(),RT=Eh(),bT=[mT.default,hT.default,fT.default,gT.default,_T.default,yT.default,ST.default,wT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},vT.default,RT.default];Pu.default=bT});var Ou=T(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.validateAdditionalItems=void 0;var xr=L(),xu=J(),IT={message:o(({params:{len:e}})=>(0,xr.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,xr._)`{limit: ${e}}`,"params")},CT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:IT,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,xu.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xh(e,n)}};function xh(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let u=r.const("len",(0,xr._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,xr._)`${u} <= ${t.length}`);else if(typeof n=="object"&&!(0,xu.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,xr._)`${u} <= ${t.length}`);r.if((0,xr.not)(l),()=>d(l)),e.ok(l)}function d(l){r.forRange("i",t.length,u,p=>{e.subschema({keyword:i,dataProp:p,dataPropType:xu.Type.Num},l),s.allErrors||r.if((0,xr.not)(l),()=>r.break())})}o(d,"validateItems")}o(xh,"validateAdditionalItems");Po.validateAdditionalItems=xh;Po.default=CT});var Uu=T(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.validateTuple=void 0;var Oh=L(),ii=J(),TT=ot(),AT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Uh(e,"additionalItems",t);r.items=!0,!(0,ii.alwaysValidSchema)(r,t)&&e.ok((0,TT.validateArray)(e))}};function Uh(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:s,it:u}=e;p(a),u.opts.unevaluated&&r.length&&u.items!==!0&&(u.items=ii.mergeEvaluated.items(n,r.length,u.items));let d=n.name("valid"),l=n.const("len",(0,Oh._)`${i}.length`);r.forEach((m,f)=>{(0,ii.alwaysValidSchema)(u,m)||(n.if((0,Oh._)`${l} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},d)),e.ok(d))});function p(m){let{opts:f,errSchemaPath:_}=u,S=r.length,y=S===m.minItems&&(S===m.maxItems||m[t]===!1);if(f.strictTuples&&!y){let w=`"${s}" is ${S}-tuple, but minItems or maxItems/${t} are not specified or different at path "${_}"`;(0,ii.checkStrictMode)(u,w,f.strictTuples)}}o(p,"checkStrictTuple")}o(Uh,"validateTuple");xo.validateTuple=Uh;xo.default=AT});var zh=T(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var kT=Uu(),ET={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,kT.validateTuple)(e,"items"),"code")};zu.default=ET});var Dh=T(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var Nh=L(),PT=J(),xT=ot(),OT=Ou(),UT={message:o(({params:{len:e}})=>(0,Nh.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Nh._)`{limit: ${e}}`,"params")},zT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:UT,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,PT.alwaysValidSchema)(n,t)&&(a?(0,OT.validateAdditionalItems)(e,a):e.ok((0,xT.validateArray)(e)))}};Nu.default=zT});var Mh=T(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var it=L(),si=J(),NT={message:o(({params:{min:e,max:t}})=>t===void 0?(0,it.str)`must contain at least ${e} valid item(s)`:(0,it.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,it._)`{minContains: ${e}}`:(0,it._)`{minContains: ${e}, maxContains: ${t}}`,"params")},DT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:NT,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,s,u,{minContains:d,maxContains:l}=n;i.opts.next?(s=d===void 0?1:d,u=l):s=1;let p=t.const("len",(0,it._)`${a}.length`);if(e.setParams({min:s,max:u}),u===void 0&&s===0){(0,si.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(u!==void 0&&s>u){(0,si.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,si.alwaysValidSchema)(i,r)){let y=(0,it._)`${p} >= ${s}`;u!==void 0&&(y=(0,it._)`${y} && ${p} <= ${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,it._)`${a}.length > 0`,f)):(t.let(m,!1),f()),e.result(m,()=>e.reset());function f(){let y=t.name("_valid"),w=t.let("count",0);_(y,()=>t.if(y,()=>S(w)))}o(f,"validateItemsWithCount");function _(y,w){t.forRange("i",0,p,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:si.Type.Num,compositeRule:!0},y),w()})}o(_,"validateItems");function S(y){t.code((0,it._)`${y}++`),u===void 0?t.if((0,it._)`${y} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,it._)`${y} > ${u}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,it._)`${y} >= ${s}`,()=>t.assign(m,!0)))}o(S,"checkLimits")}};Du.default=DT});var Lh=T(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.validateSchemaDeps=It.validatePropertyDeps=It.error=void 0;var Mu=L(),MT=J(),Oo=ot();It.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Mu.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Mu._)`{property: ${e},
30
30
  missingProperty: ${n},
31
31
  depsCount: ${t},
32
- deps: ${r}}`,"params")};var yT={keyword:"dependencies",type:"object",schemaType:"object",error:_t.error,code(e){let[t,r]=wT(e);cf(e,t),uf(e,r)}};function wT({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(wT,"splitDependencies");function cf(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let c=t[i];if(c.length===0)continue;let d=(0,So.propertyInData)(r,n,i,a.opts.ownProperties);e.setParams({property:i,depsCount:c.length,deps:c.join(", ")}),a.allErrors?r.if(d,()=>{for(let p of c)(0,So.checkReportMissingProp)(e,p)}):(r.if((0,vu._)`${d} && (${(0,So.checkMissingProp)(e,c,s)})`),(0,So.reportMissingProp)(e,s),r.else())}}o(cf,"validatePropertyDeps");_t.validatePropertyDeps=cf;function uf(e,t=e.schema){let{gen:r,data:n,keyword:a,it:s}=e,i=r.name("valid");for(let c in t)(0,_T.alwaysValidSchema)(s,t[c])||(r.if((0,So.propertyInData)(r,n,c,s.opts.ownProperties),()=>{let d=e.subschema({keyword:a,schemaProp:c},i);e.mergeValidEvaluated(d,i)},()=>r.var(i,!0)),e.ok(i))}o(uf,"validateSchemaDeps");_t.validateSchemaDeps=uf;_t.default=yT});var pf=C(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var lf=D(),ST=Z(),vT={message:"property name must be valid",params:o(({params:e})=>(0,lf._)`{propertyName: ${e.propertyName}}`,"params")},bT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vT,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,ST.alwaysValidSchema)(a,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,lf.not)(s),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(s)}};bu.default=bT});var Iu=C(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});var Fa=Ye(),it=D(),RT=Ot(),Za=Z(),IT={message:"must NOT have additional properties",params:o(({params:e})=>(0,it._)`{additionalProperty: ${e.additionalProperty}}`,"params")},TT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IT,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:c,opts:d}=i;if(i.props=!0,d.removeAdditional!=="all"&&(0,Za.alwaysValidSchema)(i,r))return;let p=(0,Fa.allSchemaProperties)(n.properties),l=(0,Fa.allSchemaProperties)(n.patternProperties);m(),e.ok((0,it._)`${s} === ${RT.default.errors}`);function m(){t.forIn("key",a,S=>{!p.length&&!l.length?w(S):t.if(h(S),()=>w(S))})}o(m,"checkAdditionalProperties");function h(S){let v;if(p.length>8){let b=(0,Za.schemaRefOrVal)(i,n.properties,"properties");v=(0,Fa.isOwnProperty)(t,b,S)}else p.length?v=(0,it.or)(...p.map(b=>(0,it._)`${S} === ${b}`)):v=it.nil;return l.length&&(v=(0,it.or)(v,...l.map(b=>(0,it._)`${(0,Fa.usePattern)(e,b)}.test(${S})`))),(0,it.not)(v)}o(h,"isAdditional");function _(S){t.code((0,it._)`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(),c||t.break();return}if(typeof r=="object"&&!(0,Za.alwaysValidSchema)(i,r)){let v=t.name("valid");d.removeAdditional==="failing"?(y(S,v,!1),t.if((0,it.not)(v),()=>{e.reset(),_(S)})):(y(S,v),c||t.if((0,it.not)(v),()=>t.break()))}}o(w,"additionalPropertyCode");function y(S,v,b){let T={keyword:"additionalProperties",dataProp:S,dataPropType:Za.Type.Str};b===!1&&Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(T,v)}o(y,"applyAdditionalSchema")}};Ru.default=TT});var hf=C(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});var CT=ao(),mf=Ye(),Tu=Z(),ff=Iu(),ET={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ff.default.code(new CT.KeywordCxt(s,ff.default,"additionalProperties"));let i=(0,mf.allSchemaProperties)(r);for(let m of i)s.definedProperties.add(m);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Tu.mergeEvaluated.props(t,(0,Tu.toHash)(i),s.props));let c=i.filter(m=>!(0,Tu.alwaysValidSchema)(s,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,mf.propertyInData)(t,a,m,s.opts.ownProperties)),l(m),s.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return s.opts.useDefaults&&!s.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};Cu.default=ET});var wf=C(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});var gf=Ye(),Ka=D(),_f=Z(),yf=Z(),AT={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:s}=e,{opts:i}=s,c=(0,gf.allSchemaProperties)(r),d=c.filter(y=>(0,_f.alwaysValidSchema)(s,r[y]));if(c.length===0||d.length===c.length&&(!s.opts.unevaluated||s.props===!0))return;let p=i.strictSchema&&!i.allowMatchingProperties&&a.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof Ka.Name)&&(s.props=(0,yf.evaluatedPropsToName)(t,s.props));let{props:m}=s;h();function h(){for(let y of c)p&&_(y),s.allErrors?w(y):(t.var(l,!0),w(y),t.if(l))}o(h,"validatePatternProperties");function _(y){for(let S in p)new RegExp(y).test(S)&&(0,_f.checkStrictMode)(s,`property ${S} matches pattern ${y} (use allowMatchingProperties)`)}o(_,"checkMatchingProperties");function w(y){t.forIn("key",n,S=>{t.if((0,Ka._)`${(0,gf.usePattern)(e,y)}.test(${S})`,()=>{let v=d.includes(y);v||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:S,dataPropType:yf.Type.Str},l),s.opts.unevaluated&&m!==!0?t.assign((0,Ka._)`${m}[${S}]`,!0):!v&&!s.allErrors&&t.if((0,Ka.not)(l),()=>t.break())})})}o(w,"validateProperties")}};Eu.default=AT});var Sf=C(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});var PT=Z(),xT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,PT.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"}};Au.default=xT});var vf=C(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});var kT=Ye(),OT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kT.validateUnion,error:{message:"must match a schema in anyOf"}};Pu.default=OT});var bf=C(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});var Wa=D(),UT=Z(),NT={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,Wa._)`{passingSchemas: ${e.passing}}`,"params")},$T={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:NT,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 s=r,i=t.let("valid",!1),c=t.let("passing",null),d=t.name("_valid");e.setParams({passing:c}),t.block(p),e.result(i,()=>e.reset(),()=>e.error(!0));function p(){s.forEach((l,m)=>{let h;(0,UT.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,Wa._)`${d} && ${i}`).assign(i,!1).assign(c,(0,Wa._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(i,!0),t.assign(c,m),h&&e.mergeEvaluated(h,Wa.Name)})})}o(p,"validateOneOf")}};xu.default=$T});var Rf=C(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var zT=Z(),MT={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((s,i)=>{if((0,zT.alwaysValidSchema)(n,s))return;let c=e.subschema({keyword:"allOf",schemaProp:i},a);e.ok(a),e.mergeEvaluated(c)})}};ku.default=MT});var Cf=C(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var Ja=D(),Tf=Z(),DT={message:o(({params:e})=>(0,Ja.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,Ja._)`{failingKeyword: ${e.ifClause}}`,"params")},qT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:DT,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Tf.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=If(n,"then"),s=If(n,"else");if(!a&&!s)return;let i=t.let("valid",!0),c=t.name("_valid");if(d(),e.reset(),a&&s){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,Ja.not)(c),p("else"));e.pass(i,()=>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(i,c),e.mergeValidEvaluated(h,i),m?t.assign(m,(0,Ja._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function If(e,t){let r=e.schema[t];return r!==void 0&&!(0,Tf.alwaysValidSchema)(e,r)}o(If,"hasSchema");Ou.default=qT});var Ef=C(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var LT=Z(),jT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,LT.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Uu.default=jT});var Af=C(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var HT=gu(),GT=nf(),BT=_u(),VT=af(),FT=sf(),ZT=df(),KT=pf(),WT=Iu(),JT=hf(),YT=wf(),XT=Sf(),QT=vf(),eC=bf(),tC=Rf(),rC=Cf(),nC=Ef();function oC(e=!1){let t=[XT.default,QT.default,eC.default,tC.default,rC.default,nC.default,KT.default,WT.default,ZT.default,JT.default,YT.default];return e?t.push(GT.default,VT.default):t.push(HT.default,BT.default),t.push(FT.default),t}o(oC,"getApplicator");Nu.default=oC});var Pf=C($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var de=D(),aC={message:o(({schemaCode:e})=>(0,de.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,de._)`{format: ${e}}`,"params")},sC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:aC,code(e,t){let{gen:r,data:n,$data:a,schema:s,schemaCode:i,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():_();function h(){let w=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),y=r.const("fDef",(0,de._)`${w}[${i}]`),S=r.let("fType"),v=r.let("format");r.if((0,de._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(S,(0,de._)`${y}.type || "string"`).assign(v,(0,de._)`${y}.validate`),()=>r.assign(S,(0,de._)`"string"`).assign(v,y)),e.fail$data((0,de.or)(b(),T()));function b(){return d.strictSchema===!1?de.nil:(0,de._)`${i} && !${v}`}o(b,"unknownFmt");function T(){let U=l.$async?(0,de._)`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,de._)`${v}(${n})`,$=(0,de._)`(typeof ${v} == "function" ? ${U} : ${v}.test(${n}))`;return(0,de._)`${v} && ${v} !== true && ${S} === ${t} && !${$}`}o(T,"invalidFmt")}o(h,"validate$DataFormat");function _(){let w=m.formats[s];if(!w){b();return}if(w===!0)return;let[y,S,v]=T(w);y===t&&e.pass(U());function b(){if(d.strictSchema===!1){m.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function T($){let Be=$ instanceof RegExp?(0,de.regexpCode)($):d.code.formats?(0,de._)`${d.code.formats}${(0,de.getProperty)(s)}`:void 0,It=r.scopeValue("formats",{key:s,ref:$,code:Be});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,de._)`${It}.validate`]:["string",$,It]}o(T,"getFormat");function U(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!l.$async)throw new Error("async format in sync schema");return(0,de._)`await ${v}(${n})`}return typeof S=="function"?(0,de._)`${v}(${n})`:(0,de._)`${v}.test(${n})`}o(U,"validCondition")}o(_,"validateFormat")}};$u.default=sC});var xf=C(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var iC=Pf(),cC=[iC.default];zu.default=cC});var kf=C(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.contentVocabulary=nn.metadataVocabulary=void 0;nn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];nn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Uf=C(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var uC=qm(),dC=Qm(),lC=Af(),pC=xf(),Of=kf(),mC=[uC.default,dC.default,(0,lC.default)(),pC.default,Of.metadataVocabulary,Of.contentVocabulary];Mu.default=mC});var $f=C(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.DiscrError=void 0;var Nf;(function(e){e.Tag="tag",e.Mapping="mapping"})(Nf||(Ya.DiscrError=Nf={}))});var Mf=C(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var on=D(),Du=$f(),zf=Oa(),fC=so(),hC=Z(),gC={message:o(({params:{discrError:e,tagName:t}})=>e===Du.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,on._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},_C={keyword:"discriminator",type:"object",schemaType:"object",error:gC,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:s}=e,{oneOf:i}=a;if(!s.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(!i)throw new Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),p=t.const("tag",(0,on._)`${r}${(0,on.getProperty)(c)}`);t.if((0,on._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:Du.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let _=h();t.if(!1);for(let w in _)t.elseIf((0,on._)`${p} === ${w}`),t.assign(d,m(_[w]));t.else(),e.error(!1,{discrError:Du.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(_){let w=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:_},w);return e.mergeEvaluated(y,on.Name),w}o(m,"applyTagSchema");function h(){var _;let w={},y=v(a),S=!0;for(let U=0;U<i.length;U++){let $=i[U];if($?.$ref&&!(0,hC.schemaHasRulesButRef)($,s.self.RULES)){let It=$.$ref;if($=zf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,It),$ instanceof zf.SchemaEnv&&($=$.schema),$===void 0)throw new fC.default(s.opts.uriResolver,s.baseId,It)}let Be=(_=$?.properties)===null||_===void 0?void 0:_[c];if(typeof Be!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);S=S&&(y||v($)),b(Be,U)}if(!S)throw new Error(`discriminator: "${c}" must be required`);return w;function v({required:U}){return Array.isArray(U)&&U.includes(c)}function b(U,$){if(U.const)T(U.const,$);else if(U.enum)for(let Be of U.enum)T(Be,$);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function T(U,$){if(typeof U!="string"||U in w)throw new Error(`discriminator: "${c}" values must be unique strings`);w[U]=$}}o(h,"getMapping")}};qu.default=_C});var Df=C((K1,yC)=>{yC.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 ju=C((re,Lu)=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.MissingRefError=re.ValidationError=re.CodeGen=re.Name=re.nil=re.stringify=re.str=re._=re.KeywordCxt=re.Ajv=void 0;var wC=Um(),SC=Uf(),vC=Mf(),qf=Df(),bC=["/properties"],Xa="http://json-schema.org/draft-07/schema",an=class extends wC.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),SC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(vC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(qf,bC):qf;this.addMetaSchema(t,Xa,!1),this.refs["http://json-schema.org/schema"]=Xa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xa)?Xa:void 0)}};re.Ajv=an;Lu.exports=re=an;Lu.exports.Ajv=an;Object.defineProperty(re,"__esModule",{value:!0});re.default=an;var RC=ao();Object.defineProperty(re,"KeywordCxt",{enumerable:!0,get:o(function(){return RC.KeywordCxt},"get")});var sn=D();Object.defineProperty(re,"_",{enumerable:!0,get:o(function(){return sn._},"get")});Object.defineProperty(re,"str",{enumerable:!0,get:o(function(){return sn.str},"get")});Object.defineProperty(re,"stringify",{enumerable:!0,get:o(function(){return sn.stringify},"get")});Object.defineProperty(re,"nil",{enumerable:!0,get:o(function(){return sn.nil},"get")});Object.defineProperty(re,"Name",{enumerable:!0,get:o(function(){return sn.Name},"get")});Object.defineProperty(re,"CodeGen",{enumerable:!0,get:o(function(){return sn.CodeGen},"get")});var IC=xa();Object.defineProperty(re,"ValidationError",{enumerable:!0,get:o(function(){return IC.default},"get")});var TC=so();Object.defineProperty(re,"MissingRefError",{enumerable:!0,get:o(function(){return TC.default},"get")})});var Zf=C(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.formatNames=wt.fastFormats=wt.fullFormats=void 0;function yt(e,t){return{validate:e,compare:t}}o(yt,"fmtDef");wt.fullFormats={date:yt(Gf,Vu),time:yt(Gu(!0),Fu),"date-time":yt(Lf(!0),Vf),"iso-time":yt(Gu(),Bf),"iso-date-time":yt(Lf(),Ff),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kC,"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:DC,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:OC,int32:{type:"number",validate:$C},int64:{type:"number",validate:zC},float:{type:"number",validate:Hf},double:{type:"number",validate:Hf},password:!0,binary:!0};wt.fastFormats={...wt.fullFormats,date:yt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vu),time:yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Fu),"date-time":yt(/^\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,Vf),"iso-time":yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Bf),"iso-date-time":yt(/^\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,Ff),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};wt.formatNames=Object.keys(wt.fullFormats);function CC(e){return e%4===0&&(e%100!==0||e%400===0)}o(CC,"isLeapYear");var EC=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,AC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gf(e){let t=EC.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&&CC(r)?29:AC[n])}o(Gf,"date");function Vu(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Vu,"compareDate");var Hu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Gu(e){return o(function(r){let n=Hu.exec(r);if(!n)return!1;let a=+n[1],s=+n[2],i=+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&&s<=59&&i<60)return!0;let m=s-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&i<61},"time")}o(Gu,"getTime");function Fu(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(Fu,"compareTime");function Bf(e,t){if(!(e&&t))return;let r=Hu.exec(e),n=Hu.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(Bf,"compareIsoTime");var Bu=/t|\s/i;function Lf(e){let t=Gu(e);return o(function(n){let a=n.split(Bu);return a.length===2&&Gf(a[0])&&t(a[1])},"date_time")}o(Lf,"getDateTime");function Vf(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(Vf,"compareDateTime");function Ff(e,t){if(!(e&&t))return;let[r,n]=e.split(Bu),[a,s]=t.split(Bu),i=Vu(r,a);if(i!==void 0)return i||Fu(n,s)}o(Ff,"compareIsoDateTime");var PC=/\/|:/,xC=/^(?:[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 kC(e){return PC.test(e)&&xC.test(e)}o(kC,"uri");var jf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function OC(e){return jf.lastIndex=0,jf.test(e)}o(OC,"byte");var UC=-(2**31),NC=2**31-1;function $C(e){return Number.isInteger(e)&&e<=NC&&e>=UC}o($C,"validateInt32");function zC(e){return Number.isInteger(e)}o(zC,"validateInt64");function Hf(){return!0}o(Hf,"validateNumber");var MC=/[^\\]\\Z/;function DC(e){if(MC.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(DC,"regex")});var Kf=C(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.formatLimitDefinition=void 0;var qC=ju(),ct=D(),or=ct.operators,Qa={formatMaximum:{okStr:"<=",ok:or.LTE,fail:or.GT},formatMinimum:{okStr:">=",ok:or.GTE,fail:or.LT},formatExclusiveMaximum:{okStr:"<",ok:or.LT,fail:or.GTE},formatExclusiveMinimum:{okStr:">",ok:or.GT,fail:or.LTE}},LC={message:o(({keyword:e,schemaCode:t})=>(0,ct.str)`should be ${Qa[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ct._)`{comparison: ${Qa[e].okStr}, limit: ${t}}`,"params")};cn.formatLimitDefinition={keyword:Object.keys(Qa),type:"string",schemaType:"string",$data:!0,error:LC,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:s}=e,{opts:i,self:c}=s;if(!i.validateFormats)return;let d=new qC.KeywordCxt(s,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:i.code.formats}),_=t.const("fmt",(0,ct._)`${h}[${d.schemaCode}]`);e.fail$data((0,ct.or)((0,ct._)`typeof ${_} != "object"`,(0,ct._)`${_} instanceof RegExp`,(0,ct._)`typeof ${_}.compare != "function"`,m(_)))}o(p,"validate$DataFormat");function l(){let h=d.schema,_=c.formats[h];if(!_||_===!0)return;if(typeof _!="object"||_ instanceof RegExp||typeof _.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let w=t.scopeValue("formats",{key:h,ref:_,code:i.code.formats?(0,ct._)`${i.code.formats}${(0,ct.getProperty)(h)}`:void 0});e.fail$data(m(w))}o(l,"validateFormat");function m(h){return(0,ct._)`${h}.compare(${r}, ${n}) ${Qa[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var jC=o(e=>(e.addKeyword(cn.formatLimitDefinition),e),"formatLimitPlugin");cn.default=jC});var Xf=C((vo,Yf)=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});var un=Zf(),HC=Kf(),Zu=D(),Wf=new Zu.Name("fullFormats"),GC=new Zu.Name("fastFormats"),Ku=o((e,t={keywords:!0})=>{if(Array.isArray(t))return Jf(e,t,un.fullFormats,Wf),e;let[r,n]=t.mode==="fast"?[un.fastFormats,GC]:[un.fullFormats,Wf],a=t.formats||un.formatNames;return Jf(e,a,r,n),t.keywords&&(0,HC.default)(e),e},"formatsPlugin");Ku.get=(e,t="full")=>{let n=(t==="fast"?un.fastFormats:un.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Jf(e,t,r,n){var a,s;(a=(s=e.opts.code).formats)!==null&&a!==void 0||(s.formats=(0,Zu._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}o(Jf,"addFormats");Yf.exports=vo=Ku;Object.defineProperty(vo,"__esModule",{value:!0});vo.default=Ku});xw();function Gt(e){return!!e._zod}o(Gt,"isZ4Schema");function xe(e,t){return Gt(e)?vi(e,t):e.safeParse(t)}o(xe,"safeParse");function jr(e){if(!e)return;let t;if(Gt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(jr,"getObjectShape");function Jl(e){if(Gt(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}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(Jl,"getLiteralValue");W();var Vt="2025-11-25",Yl="2025-03-26",Ft=[Vt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",oa="2.0",he=Zl(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Xl=ne([f(),V().int()]),Ql=f(),p$=fe({ttl:V().optional(),pollInterval:V().optional()}),Uw=I({ttl:V().optional()}),Nw=I({taskId:f()}),Ti=fe({progressToken:Xl.optional(),[Zt]:Nw.optional()}),Fe=I({_meta:Ti.optional()}),$n=Fe.extend({task:Uw.optional()}),ep=o(e=>$n.safeParse(e).success,"isTaskAugmentedRequestParams"),ye=I({method:f(),params:Fe.loose().optional()}),Ke=I({_meta:Ti.optional()}),We=I({method:f(),params:Ke.loose().optional()}),we=fe({_meta:Ti.optional()}),aa=ne([f(),V().int()]),tp=I({jsonrpc:P(oa),id:aa,...ye.shape}).strict(),mt=o(e=>tp.safeParse(e).success,"isJSONRPCRequest"),rp=I({jsonrpc:P(oa),...We.shape}).strict(),np=o(e=>rp.safeParse(e).success,"isJSONRPCNotification"),Ci=I({jsonrpc:P(oa),id:aa,result:we}).strict(),nt=o(e=>Ci.safeParse(e).success,"isJSONRPCResultResponse");var A;(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"})(A||(A={}));var Ei=I({jsonrpc:P(oa),id:aa.optional(),error:I({code:V().int(),message:f(),data:ue().optional()})}).strict();var Gr=o(e=>Ei.safeParse(e).success,"isJSONRPCErrorResponse");var hr=ne([tp,rp,Ci,Ei]),m$=ne([Ci,Ei]),Et=we.strict(),$w=Ke.extend({requestId:aa.optional(),reason:f().optional()}),sa=We.extend({method:P("notifications/cancelled"),params:$w}),zw=I({src:f(),mimeType:f().optional(),sizes:R(f()).optional(),theme:Ve(["light","dark"]).optional()}),zn=I({icons:R(zw).optional()}),Hr=I({name:f(),title:f().optional()}),Br=Hr.extend({...Hr.shape,...zn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),Mw=Ri(I({applyDefaults:Y().optional()}),ee(f(),ue())),Dw=Ii(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ri(I({form:Mw.optional(),url:he.optional()}),ee(f(),ue()).optional())),qw=fe({list:he.optional(),cancel:he.optional(),requests:fe({sampling:fe({createMessage:he.optional()}).optional(),elicitation:fe({create:he.optional()}).optional()}).optional()}),Lw=fe({list:he.optional(),cancel:he.optional(),requests:fe({tools:fe({call:he.optional()}).optional()}).optional()}),jw=I({experimental:ee(f(),he).optional(),sampling:I({context:he.optional(),tools:he.optional()}).optional(),elicitation:Dw.optional(),roots:I({listChanged:Y().optional()}).optional(),tasks:qw.optional(),extensions:ee(f(),he).optional()}),Hw=Fe.extend({protocolVersion:f(),capabilities:jw,clientInfo:Br}),ia=ye.extend({method:P("initialize"),params:Hw}),Ai=o(e=>ia.safeParse(e).success,"isInitializeRequest"),Gw=I({experimental:ee(f(),he).optional(),logging:he.optional(),completions:he.optional(),prompts:I({listChanged:Y().optional()}).optional(),resources:I({subscribe:Y().optional(),listChanged:Y().optional()}).optional(),tools:I({listChanged:Y().optional()}).optional(),tasks:Lw.optional(),extensions:ee(f(),he).optional()}),Pi=we.extend({protocolVersion:f(),capabilities:Gw,serverInfo:Br,instructions:f().optional()}),ca=We.extend({method:P("notifications/initialized"),params:Ke.optional()}),op=o(e=>ca.safeParse(e).success,"isInitializedNotification"),ua=ye.extend({method:P("ping"),params:Fe.optional()}),Bw=I({progress:V(),total:se(V()),message:se(f())}),Vw=I({...Ke.shape,...Bw.shape,progressToken:Xl}),da=We.extend({method:P("notifications/progress"),params:Vw}),Fw=Fe.extend({cursor:Ql.optional()}),Mn=ye.extend({params:Fw.optional()}),Dn=we.extend({nextCursor:Ql.optional()}),Zw=Ve(["working","input_required","completed","failed","cancelled"]),qn=I({taskId:f(),status:Zw,ttl:ne([V(),Vl()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:se(V()),statusMessage:se(f())}),At=we.extend({task:qn}),Kw=Ke.merge(qn),Ln=We.extend({method:P("notifications/tasks/status"),params:Kw}),la=ye.extend({method:P("tasks/get"),params:Fe.extend({taskId:f()})}),pa=we.merge(qn),ma=ye.extend({method:P("tasks/result"),params:Fe.extend({taskId:f()})}),f$=we.loose(),fa=Mn.extend({method:P("tasks/list")}),ha=Dn.extend({tasks:R(qn)}),ga=ye.extend({method:P("tasks/cancel"),params:Fe.extend({taskId:f()})}),ap=we.merge(qn),sp=I({uri:f(),mimeType:se(f()),_meta:ee(f(),ue()).optional()}),ip=sp.extend({text:f()}),xi=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),cp=sp.extend({blob:xi}),jn=Ve(["user","assistant"]),Vr=I({audience:R(jn).optional(),priority:V().min(0).max(1).optional(),lastModified:Gl.datetime({offset:!0}).optional()}),up=I({...Hr.shape,...zn.shape,uri:f(),description:se(f()),mimeType:se(f()),size:se(V()),annotations:Vr.optional(),_meta:se(fe({}))}),Ww=I({...Hr.shape,...zn.shape,uriTemplate:f(),description:se(f()),mimeType:se(f()),annotations:Vr.optional(),_meta:se(fe({}))}),ki=Mn.extend({method:P("resources/list")}),Oi=Dn.extend({resources:R(up)}),Jw=Mn.extend({method:P("resources/templates/list")}),Ui=Dn.extend({resourceTemplates:R(Ww)}),Ni=Fe.extend({uri:f()}),Yw=Ni,$i=ye.extend({method:P("resources/read"),params:Yw}),zi=we.extend({contents:R(ne([ip,cp]))}),Mi=We.extend({method:P("notifications/resources/list_changed"),params:Ke.optional()}),Xw=Ni,Qw=ye.extend({method:P("resources/subscribe"),params:Xw}),eS=Ni,tS=ye.extend({method:P("resources/unsubscribe"),params:eS}),rS=Ke.extend({uri:f()}),nS=We.extend({method:P("notifications/resources/updated"),params:rS}),oS=I({name:f(),description:se(f()),required:se(Y())}),aS=I({...Hr.shape,...zn.shape,description:se(f()),arguments:se(R(oS)),_meta:se(fe({}))}),Di=Mn.extend({method:P("prompts/list")}),qi=Dn.extend({prompts:R(aS)}),sS=Fe.extend({name:f(),arguments:ee(f(),f()).optional()}),Li=ye.extend({method:P("prompts/get"),params:sS}),ji=I({type:P("text"),text:f(),annotations:Vr.optional(),_meta:ee(f(),ue()).optional()}),Hi=I({type:P("image"),data:xi,mimeType:f(),annotations:Vr.optional(),_meta:ee(f(),ue()).optional()}),Gi=I({type:P("audio"),data:xi,mimeType:f(),annotations:Vr.optional(),_meta:ee(f(),ue()).optional()}),iS=I({type:P("tool_use"),name:f(),id:f(),input:ee(f(),ue()),_meta:ee(f(),ue()).optional()}),cS=I({type:P("resource"),resource:ne([ip,cp]),annotations:Vr.optional(),_meta:ee(f(),ue()).optional()}),uS=up.extend({type:P("resource_link")}),Bi=ne([ji,Hi,Gi,uS,cS]),dS=I({role:jn,content:Bi}),Vi=we.extend({description:f().optional(),messages:R(dS)}),Fi=We.extend({method:P("notifications/prompts/list_changed"),params:Ke.optional()}),lS=I({title:f().optional(),readOnlyHint:Y().optional(),destructiveHint:Y().optional(),idempotentHint:Y().optional(),openWorldHint:Y().optional()}),pS=I({taskSupport:Ve(["required","optional","forbidden"]).optional()}),dp=I({...Hr.shape,...zn.shape,description:f().optional(),inputSchema:I({type:P("object"),properties:ee(f(),he).optional(),required:R(f()).optional()}).catchall(ue()),outputSchema:I({type:P("object"),properties:ee(f(),he).optional(),required:R(f()).optional()}).catchall(ue()).optional(),annotations:lS.optional(),execution:pS.optional(),_meta:ee(f(),ue()).optional()}),Zi=Mn.extend({method:P("tools/list")}),Ki=Dn.extend({tools:R(dp)}),Kt=we.extend({content:R(Bi).default([]),structuredContent:ee(f(),ue()).optional(),isError:Y().optional()}),h$=Kt.or(we.extend({toolResult:ue()})),mS=$n.extend({name:f(),arguments:ee(f(),ue()).optional()}),Hn=ye.extend({method:P("tools/call"),params:mS}),Wi=We.extend({method:P("notifications/tools/list_changed"),params:Ke.optional()}),lp=I({autoRefresh:Y().default(!0),debounceMs:V().int().nonnegative().default(300)}),Gn=Ve(["debug","info","notice","warning","error","critical","alert","emergency"]),fS=Fe.extend({level:Gn}),Ji=ye.extend({method:P("logging/setLevel"),params:fS}),hS=Ke.extend({level:Gn,logger:f().optional(),data:ue()}),gS=We.extend({method:P("notifications/message"),params:hS}),_S=I({name:f().optional()}),yS=I({hints:R(_S).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),wS=I({mode:Ve(["auto","required","none"]).optional()}),SS=I({type:P("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:R(Bi).default([]),structuredContent:I({}).loose().optional(),isError:Y().optional(),_meta:ee(f(),ue()).optional()}),vS=bi("type",[ji,Hi,Gi]),na=bi("type",[ji,Hi,Gi,iS,SS]),bS=I({role:jn,content:ne([na,R(na)]),_meta:ee(f(),ue()).optional()}),RS=$n.extend({messages:R(bS),modelPreferences:yS.optional(),systemPrompt:f().optional(),includeContext:Ve(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:R(f()).optional(),metadata:he.optional(),tools:R(dp).optional(),toolChoice:wS.optional()}),Yi=ye.extend({method:P("sampling/createMessage"),params:RS}),gr=we.extend({model:f(),stopReason:se(Ve(["endTurn","stopSequence","maxTokens"]).or(f())),role:jn,content:vS}),Bn=we.extend({model:f(),stopReason:se(Ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:jn,content:ne([na,R(na)])}),IS=I({type:P("boolean"),title:f().optional(),description:f().optional(),default:Y().optional()}),TS=I({type:P("string"),title:f().optional(),description:f().optional(),minLength:V().optional(),maxLength:V().optional(),format:Ve(["email","uri","date","date-time"]).optional(),default:f().optional()}),CS=I({type:Ve(["number","integer"]),title:f().optional(),description:f().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),ES=I({type:P("string"),title:f().optional(),description:f().optional(),enum:R(f()),default:f().optional()}),AS=I({type:P("string"),title:f().optional(),description:f().optional(),oneOf:R(I({const:f(),title:f()})),default:f().optional()}),PS=I({type:P("string"),title:f().optional(),description:f().optional(),enum:R(f()),enumNames:R(f()).optional(),default:f().optional()}),xS=ne([ES,AS]),kS=I({type:P("array"),title:f().optional(),description:f().optional(),minItems:V().optional(),maxItems:V().optional(),items:I({type:P("string"),enum:R(f())}),default:R(f()).optional()}),OS=I({type:P("array"),title:f().optional(),description:f().optional(),minItems:V().optional(),maxItems:V().optional(),items:I({anyOf:R(I({const:f(),title:f()}))}),default:R(f()).optional()}),US=ne([kS,OS]),NS=ne([PS,xS,US]),$S=ne([NS,IS,TS,CS]),zS=$n.extend({mode:P("form").optional(),message:f(),requestedSchema:I({type:P("object"),properties:ee(f(),$S),required:R(f()).optional()})}),MS=$n.extend({mode:P("url"),message:f(),elicitationId:f(),url:f().url()}),DS=ne([zS,MS]),Xi=ye.extend({method:P("elicitation/create"),params:DS}),qS=Ke.extend({elicitationId:f()}),LS=We.extend({method:P("notifications/elicitation/complete"),params:qS}),Wt=we.extend({action:Ve(["accept","decline","cancel"]),content:Ii(e=>e===null?void 0:e,ee(f(),ne([f(),V(),Y(),R(f())])).optional())}),jS=I({type:P("ref/resource"),uri:f()});var HS=I({type:P("ref/prompt"),name:f()}),GS=Fe.extend({ref:ne([HS,jS]),argument:I({name:f(),value:f()}),context:I({arguments:ee(f(),f()).optional()}).optional()}),BS=ye.extend({method:P("completion/complete"),params:GS});var Qi=we.extend({completion:fe({values:R(f()).max(100),total:se(V().int()),hasMore:se(Y())})}),VS=I({uri:f().startsWith("file://"),name:f().optional(),_meta:ee(f(),ue()).optional()}),FS=ye.extend({method:P("roots/list"),params:Fe.optional()}),ec=we.extend({roots:R(VS)}),ZS=We.extend({method:P("notifications/roots/list_changed"),params:Ke.optional()}),g$=ne([ua,ia,BS,Ji,Li,Di,ki,Jw,$i,Qw,tS,Hn,Zi,la,ma,fa,ga]),_$=ne([sa,da,ca,ZS,Ln]),y$=ne([Et,gr,Bn,Wt,ec,pa,ha,At]),w$=ne([ua,Yi,Xi,FS,la,ma,fa,ga]),S$=ne([sa,da,gS,nS,Mi,Wi,Fi,Ln,LS]),v$=ne([Et,Pi,Qi,Vi,qi,Oi,Ui,zi,Kt,Ki,pa,ha,At]),E=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===A.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new Bt(a.elicitations,r)}return new e(t,r,n)}},Bt=class extends E{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Jt(e){return e==="completed"||e==="failed"||e==="cancelled"}o(Jt,"isTerminal");var KS=Symbol("Let zodToJsonSchema decide on which parser to use");var yz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tc(e){let r=jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Jl(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(tc,"getMethodLiteral");function rc(e,t){let r=xe(e,t);if(!r.success)throw r.error;return r.data}o(rc,"parseWithCompat");var ev=6e4,Fr=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(sa,r=>{this._oncancel(r)}),this.setNotificationHandler(da,r=>{this._onprogress(r)}),this.setRequestHandler(ua,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(la,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new E(A.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(ma,async(r,n)=>{let a=o(async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(s,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 E(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 i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new E(A.InvalidParams,`Task not found: ${s}`);if(!Jt(i.status))return await this._waitForTaskUpdate(s,n.signal),await a();if(Jt(i.status)){let c=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...c,_meta:{...c._meta,[Zt]:{taskId:s}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(fa,async(r,n)=>{try{let{tasks:a,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:a,nextCursor:s,_meta:{}}}catch(a){throw new E(A.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(ga,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new E(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Jt(a.status))throw new E(A.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 s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new E(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(a){throw a instanceof E?a:new E(A.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,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,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),E.fromError(A.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=s=>{n?.(s),this._onerror(s)};let a=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{a?.(s,i),nt(s)||Gr(s)?this._onresponse(s):mt(s)?this._onrequest(s,i):np(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},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=E.fromError(A.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,s=t.params?._meta?.[Zt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:A.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{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 i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let c=ep(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,p={signal:i.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async l=>{if(i.signal.aborted)return;let m={relatedRequestId:t.id};s&&(m.relatedTask={taskId:s}),await this.notification(l,m)},"sendNotification"),sendRequest:o(async(l,m,h)=>{if(i.signal.aborted)throw new E(A.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:t.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let w=_.relatedTask?.taskId??s;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:s,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(i.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(i.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:A.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{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)===i&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),s=this._progressHandlers.get(a);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(a),c=this._timeoutInfo.get(a);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),i(d);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),nt(t))n(t);else{let i=new E(t.error.code,t.error.message,t.error.data);n(i)}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 s=!1;if(nt(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let c=i.task;typeof c.taskId=="string"&&(s=!0,this._taskProgressTokens.set(c.taskId,r))}}if(s||this._progressHandlers.delete(r),nt(t))a(t);else{let i=E.fromError(t.error.code,t.error.message,t.error.data);a(i)}}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(i){yield{type:"error",error:i instanceof E?i:new E(A.InternalError,String(i))}}return}let s;try{let i=await this.request(t,At,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new E(A.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:c},Jt(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:c.status==="failed"?yield{type:"error",error:new E(A.InternalError,`Task ${s} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new E(A.InternalError,`Task ${s} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,d)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof E?i:new E(A.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i,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++,_={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),_.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(_.params={..._.params,task:c}),d&&(_.params={..._.params,_meta:{..._.params?._meta||{},[Zt]:d}});let w=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:s,onresumptiontoken:i}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`)));let T=b instanceof E?b:new E(A.RequestTimeout,String(b));l(T)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let T=xe(r,b.result);T.success?p(T.data):l(T.error)}catch(T){l(T)}}}),n?.signal?.addEventListener("abort",()=>{w(n?.signal?.reason)});let y=n?.timeout??ev,S=o(()=>w(E.fromError(A.RequestTimeout,"Request timed out",{timeout:y})),"timeoutHandler");this._setupTimeout(h,y,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let b=o(T=>{let U=this._responseHandlers.get(h);U?U(T):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(v,{type:"request",message:_,timestamp:Date.now()}).catch(T=>{this._cleanupTimeout(h),l(T)})}else this._transport.send(_,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},pa,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},ha,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},ap,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||{},[Zt]: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||{},[Zt]:r.relatedTask}}}),this._transport?.send(c,r).catch(d=>this._onerror(d))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=tc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,s)=>{let i=rc(t,a);return Promise.resolve(r(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=tc(t);this._notificationHandlers.set(n,a=>{let s=rc(t,a);return Promise.resolve(r(s))})}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"&&mt(a.message)){let s=a.message.id,i=this._requestResolvers.get(s);i?(i(new E(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(t);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,s)=>{if(r.aborted){s(new E(A.InvalidRequest,"Request cancelled"));return}let i=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new E(A.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 s=await n.getTask(a,r);if(!s)throw new E(A.InvalidParams,"Failed to retrieve task: Task not found");return s},"getTask"),storeTaskResult:o(async(a,s,i)=>{await n.storeTaskResult(a,s,i,r);let c=await n.getTask(a,r);if(c){let d=Ln.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Jt(c.status)&&this._cleanupTaskProgressHandler(a)}},"storeTaskResult"),getTaskResult:o(a=>n.getTaskResult(a,r),"getTaskResult"),updateTaskStatus:o(async(a,s,i)=>{let c=await n.getTask(a,r);if(!c)throw new E(A.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Jt(c.status))throw new E(A.InvalidParams,`Cannot update task "${a}" from terminal status "${c.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,s,i,r);let d=await n.getTask(a,r);if(d){let p=Ln.parse({method:"notifications/tasks/status",params:d});await this.notification(p),Jt(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function pp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(pp,"isPlainObject");function _a(e,t){let r={...e};for(let n in t){let a=n,s=t[a];if(s===void 0)continue;let i=r[a];pp(i)&&pp(s)?r[a]={...i,...s}:r[a]=s}return r}o(_a,"mergeCapabilities");var Qf=Ll(ju(),1),eh=Ll(Xf(),1);function BC(){let e=new Qf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eh.default)(e),e}o(BC,"createDefaultAjvInstance");var dn=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??BC()}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 es=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],s=Array.isArray(a.content)?a.content:[a.content],i=s.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(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!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(s.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},gr,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 s=a==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:s},Wt,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 ts(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(ts,"assertToolsCallTaskCapability");function rs(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(rs,"assertClientRequestTaskCapability");var ns=class extends Fr{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Gn.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let s=this._loggingLevels.get(a);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new dn,this.setRequestHandler(ia,n=>this._oninitialize(n)),this.setNotificationHandler(ca,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ji,async(n,a)=>{let s=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,c=Gn.safeParse(i);return c.success&&this._loggingLevels.set(s,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new es(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_a(this._capabilities,t)}setRequestHandler(t,r){let a=jr(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let s;if(Gt(a)){let c=a;s=c._zod?.def?.value??c.value}else{let c=a;s=c._def?.value??c.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let c=o(async(d,p)=>{let l=xe(Hn,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new E(A.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let w=xe(At,h);if(!w.success){let y=w.error instanceof Error?w.error.message:String(w.error);throw new E(A.InvalidParams,`Invalid task creation result: ${y}`)}return w.data}let _=xe(Kt,h);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new E(A.InvalidParams,`Invalid tools/call result: ${w}`)}return _.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){rs(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&ts(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:Ft.includes(r)?r:Vt,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"},Et)}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],s=a.some(p=>p.type==="tool_result"),i=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=i?Array.isArray(i.content)?i.content:[i.content]:[],d=c.some(p=>p.type==="tool_use");if(s){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},Bn,r):this.request({method:"sampling/createMessage",params:t},gr,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},Wt,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"},s=await this.request({method:"elicitation/create",params:a},Wt,r);if(s.action==="accept"&&s.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(s.content);if(!c.valid)throw new E(A.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(i){throw i instanceof E?i:new E(A.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},ec,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 os=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 s={code:r,message:n};return a?.data!==void 0&&(s.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,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 s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
32
+ deps: ${r}}`,"params")};var qT={keyword:"dependencies",type:"object",schemaType:"object",error:It.error,code(e){let[t,r]=$T(e);qh(e,t),$h(e,r)}};function $T({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($T,"splitDependencies");function qh(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,Oo.propertyInData)(r,n,s,a.opts.ownProperties);e.setParams({property:s,depsCount:u.length,deps:u.join(", ")}),a.allErrors?r.if(d,()=>{for(let l of u)(0,Oo.checkReportMissingProp)(e,l)}):(r.if((0,Mu._)`${d} && (${(0,Oo.checkMissingProp)(e,u,i)})`),(0,Oo.reportMissingProp)(e,i),r.else())}}o(qh,"validatePropertyDeps");It.validatePropertyDeps=qh;function $h(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let u in t)(0,MT.alwaysValidSchema)(i,t[u])||(r.if((0,Oo.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($h,"validateSchemaDeps");It.validateSchemaDeps=$h;It.default=qT});var Hh=T(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var jh=L(),LT=J(),jT={message:"property name must be valid",params:o(({params:e})=>(0,jh._)`{propertyName: ${e.propertyName}}`,"params")},HT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jT,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,LT.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,jh.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};qu.default=HT});var Lu=T($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var ci=ot(),ht=L(),GT=$t(),ui=J(),BT={message:"must NOT have additional properties",params:o(({params:e})=>(0,ht._)`{additionalProperty: ${e.additionalProperty}}`,"params")},VT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:BT,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,ui.alwaysValidSchema)(s,r))return;let l=(0,ci.allSchemaProperties)(n.properties),p=(0,ci.allSchemaProperties)(n.patternProperties);m(),e.ok((0,ht._)`${i} === ${GT.default.errors}`);function m(){t.forIn("key",a,w=>{!l.length&&!p.length?S(w):t.if(f(w),()=>S(w))})}o(m,"checkAdditionalProperties");function f(w){let v;if(l.length>8){let R=(0,ui.schemaRefOrVal)(s,n.properties,"properties");v=(0,ci.isOwnProperty)(t,R,w)}else l.length?v=(0,ht.or)(...l.map(R=>(0,ht._)`${w} === ${R}`)):v=ht.nil;return p.length&&(v=(0,ht.or)(v,...p.map(R=>(0,ht._)`${(0,ci.usePattern)(e,R)}.test(${w})`))),(0,ht.not)(v)}o(f,"isAdditional");function _(w){t.code((0,ht._)`delete ${a}[${w}]`)}o(_,"deleteAdditional");function S(w){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){_(w);return}if(r===!1){e.setParams({additionalProperty:w}),e.error(),u||t.break();return}if(typeof r=="object"&&!(0,ui.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(y(w,v,!1),t.if((0,ht.not)(v),()=>{e.reset(),_(w)})):(y(w,v),u||t.if((0,ht.not)(v),()=>t.break()))}}o(S,"additionalPropertyCode");function y(w,v,R){let C={keyword:"additionalProperties",dataProp:w,dataPropType:ui.Type.Str};R===!1&&Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(C,v)}o(y,"applyAdditionalSchema")}};$u.default=VT});var Vh=T(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var FT=yo(),Gh=ot(),ju=J(),Bh=Lu(),ZT={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&&Bh.default.code(new FT.KeywordCxt(i,Bh.default,"additionalProperties"));let s=(0,Gh.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=ju.mergeEvaluated.props(t,(0,ju.toHash)(s),i.props));let u=s.filter(m=>!(0,ju.alwaysValidSchema)(i,r[m]));if(u.length===0)return;let d=t.name("valid");for(let m of u)l(m)?p(m):(t.if((0,Gh.propertyInData)(t,a,m,i.opts.ownProperties)),p(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function l(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(l,"hasDefault");function p(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(p,"applyPropertySchema")}};Hu.default=ZT});var Wh=T(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var Fh=ot(),di=L(),Zh=J(),Kh=J(),KT={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,Fh.allSchemaProperties)(r),d=u.filter(y=>(0,Zh.alwaysValidSchema)(i,r[y]));if(u.length===0||d.length===u.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&a.properties,p=t.name("valid");i.props!==!0&&!(i.props instanceof di.Name)&&(i.props=(0,Kh.evaluatedPropsToName)(t,i.props));let{props:m}=i;f();function f(){for(let y of u)l&&_(y),i.allErrors?S(y):(t.var(p,!0),S(y),t.if(p))}o(f,"validatePatternProperties");function _(y){for(let w in l)new RegExp(y).test(w)&&(0,Zh.checkStrictMode)(i,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}o(_,"checkMatchingProperties");function S(y){t.forIn("key",n,w=>{t.if((0,di._)`${(0,Fh.usePattern)(e,y)}.test(${w})`,()=>{let v=d.includes(y);v||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:Kh.Type.Str},p),i.opts.unevaluated&&m!==!0?t.assign((0,di._)`${m}[${w}]`,!0):!v&&!i.allErrors&&t.if((0,di.not)(p),()=>t.break())})})}o(S,"validateProperties")}};Gu.default=KT});var Jh=T(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var WT=J(),JT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,WT.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"}};Bu.default=JT});var Yh=T(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var YT=ot(),XT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:YT.validateUnion,error:{message:"must match a schema in anyOf"}};Vu.default=XT});var Xh=T(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var li=L(),QT=J(),eA={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,li._)`{passingSchemas: ${e.passing}}`,"params")},tA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eA,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(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((p,m)=>{let f;(0,QT.alwaysValidSchema)(a,p)?t.var(d,!0):f=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,li._)`${d} && ${s}`).assign(s,!1).assign(u,(0,li._)`[${u}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(u,m),f&&e.mergeEvaluated(f,li.Name)})})}o(l,"validateOneOf")}};Fu.default=tA});var Qh=T(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var rA=J(),nA={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,rA.alwaysValidSchema)(n,i))return;let u=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(u)})}};Zu.default=nA});var rf=T(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var pi=L(),tf=J(),oA={message:o(({params:e})=>(0,pi.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,pi._)`{failingKeyword: ${e.ifClause}}`,"params")},aA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:oA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,tf.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=ef(n,"then"),i=ef(n,"else");if(!a&&!i)return;let s=t.let("valid",!0),u=t.name("_valid");if(d(),e.reset(),a&&i){let p=t.let("ifClause");e.setParams({ifClause:p}),t.if(u,l("then",p),l("else",p))}else a?t.if(u,l("then")):t.if((0,pi.not)(u),l("else"));e.pass(s,()=>e.error(!0));function d(){let p=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(p)}o(d,"validateIf");function l(p,m){return()=>{let f=e.subschema({keyword:p},u);t.assign(s,u),e.mergeValidEvaluated(f,s),m?t.assign(m,(0,pi._)`${p}`):e.setParams({ifClause:p})}}o(l,"validateClause")}};function ef(e,t){let r=e.schema[t];return r!==void 0&&!(0,tf.alwaysValidSchema)(e,r)}o(ef,"hasSchema");Ku.default=aA});var nf=T(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var iA=J(),sA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,iA.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Wu.default=sA});var of=T(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var cA=Ou(),uA=zh(),dA=Uu(),lA=Dh(),pA=Mh(),mA=Lh(),hA=Hh(),fA=Lu(),gA=Vh(),_A=Wh(),yA=Jh(),SA=Yh(),wA=Xh(),vA=Qh(),RA=rf(),bA=nf();function IA(e=!1){let t=[yA.default,SA.default,wA.default,vA.default,RA.default,bA.default,hA.default,fA.default,mA.default,gA.default,_A.default];return e?t.push(uA.default,lA.default):t.push(cA.default,dA.default),t.push(pA.default),t}o(IA,"getApplicator");Ju.default=IA});var af=T(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var ge=L(),CA={message:o(({schemaCode:e})=>(0,ge.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ge._)`{format: ${e}}`,"params")},TA={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CA,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:u}=e,{opts:d,errSchemaPath:l,schemaEnv:p,self:m}=u;if(!d.validateFormats)return;a?f():_();function f(){let S=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),y=r.const("fDef",(0,ge._)`${S}[${s}]`),w=r.let("fType"),v=r.let("format");r.if((0,ge._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(w,(0,ge._)`${y}.type || "string"`).assign(v,(0,ge._)`${y}.validate`),()=>r.assign(w,(0,ge._)`"string"`).assign(v,y)),e.fail$data((0,ge.or)(R(),C()));function R(){return d.strictSchema===!1?ge.nil:(0,ge._)`${s} && !${v}`}o(R,"unknownFmt");function C(){let N=p.$async?(0,ge._)`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ge._)`${v}(${n})`,M=(0,ge._)`(typeof ${v} == "function" ? ${N} : ${v}.test(${n}))`;return(0,ge._)`${v} && ${v} !== true && ${w} === ${t} && !${M}`}o(C,"invalidFmt")}o(f,"validate$DataFormat");function _(){let S=m.formats[i];if(!S){R();return}if(S===!0)return;let[y,w,v]=C(S);y===t&&e.pass(N());function R(){if(d.strictSchema===!1){m.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${i}" ignored in schema at path "${l}"`}}o(R,"unknownFormat");function C(M){let Ye=M instanceof RegExp?(0,ge.regexpCode)(M):d.code.formats?(0,ge._)`${d.code.formats}${(0,ge.getProperty)(i)}`:void 0,Ot=r.scopeValue("formats",{key:i,ref:M,code:Ye});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,ge._)`${Ot}.validate`]:["string",M,Ot]}o(C,"getFormat");function N(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!p.$async)throw new Error("async format in sync schema");return(0,ge._)`await ${v}(${n})`}return typeof w=="function"?(0,ge._)`${v}(${n})`:(0,ge._)`${v}.test(${n})`}o(N,"validCondition")}o(_,"validateFormat")}};Yu.default=TA});var sf=T(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var AA=af(),kA=[AA.default];Xu.default=kA});var cf=T(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.contentVocabulary=mn.metadataVocabulary=void 0;mn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];mn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var df=T(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var EA=gh(),PA=Ph(),xA=of(),OA=sf(),uf=cf(),UA=[EA.default,PA.default,(0,xA.default)(),OA.default,uf.metadataVocabulary,uf.contentVocabulary];Qu.default=UA});var pf=T(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.DiscrError=void 0;var lf;(function(e){e.Tag="tag",e.Mapping="mapping"})(lf||(mi.DiscrError=lf={}))});var hf=T(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var hn=L(),ed=pf(),mf=Ka(),zA=So(),NA=J(),DA={message:o(({params:{discrError:e,tagName:t}})=>e===ed.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,hn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},MA={keyword:"discriminator",type:"object",schemaType:"object",error:DA,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),l=t.const("tag",(0,hn._)`${r}${(0,hn.getProperty)(u)}`);t.if((0,hn._)`typeof ${l} == "string"`,()=>p(),()=>e.error(!1,{discrError:ed.DiscrError.Tag,tag:l,tagName:u})),e.ok(d);function p(){let _=f();t.if(!1);for(let S in _)t.elseIf((0,hn._)`${l} === ${S}`),t.assign(d,m(_[S]));t.else(),e.error(!1,{discrError:ed.DiscrError.Mapping,tag:l,tagName:u}),t.endIf()}o(p,"validateMapping");function m(_){let S=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:_},S);return e.mergeEvaluated(y,hn.Name),S}o(m,"applyTagSchema");function f(){var _;let S={},y=v(a),w=!0;for(let N=0;N<s.length;N++){let M=s[N];if(M?.$ref&&!(0,NA.schemaHasRulesButRef)(M,i.self.RULES)){let Ot=M.$ref;if(M=mf.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ot),M instanceof mf.SchemaEnv&&(M=M.schema),M===void 0)throw new zA.default(i.opts.uriResolver,i.baseId,Ot)}let Ye=(_=M?.properties)===null||_===void 0?void 0:_[u];if(typeof Ye!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${u}"`);w=w&&(y||v(M)),R(Ye,N)}if(!w)throw new Error(`discriminator: "${u}" must be required`);return S;function v({required:N}){return Array.isArray(N)&&N.includes(u)}function R(N,M){if(N.const)C(N.const,M);else if(N.enum)for(let Ye of N.enum)C(Ye,M);else throw new Error(`discriminator: "properties/${u}" must have "const" or "enum"`)}function C(N,M){if(typeof N!="string"||N in S)throw new Error(`discriminator: "${u}" values must be unique strings`);S[N]=M}}o(f,"getMapping")}};td.default=MA});var ff=T((QH,qA)=>{qA.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 nd=T((ie,rd)=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.MissingRefError=ie.ValidationError=ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=ie.Ajv=void 0;var $A=dh(),LA=df(),jA=hf(),gf=ff(),HA=["/properties"],hi="http://json-schema.org/draft-07/schema",fn=class extends $A.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),LA.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(jA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(gf,HA):gf;this.addMetaSchema(t,hi,!1),this.refs["http://json-schema.org/schema"]=hi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hi)?hi:void 0)}};ie.Ajv=fn;rd.exports=ie=fn;rd.exports.Ajv=fn;Object.defineProperty(ie,"__esModule",{value:!0});ie.default=fn;var GA=yo();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:o(function(){return GA.KeywordCxt},"get")});var gn=L();Object.defineProperty(ie,"_",{enumerable:!0,get:o(function(){return gn._},"get")});Object.defineProperty(ie,"str",{enumerable:!0,get:o(function(){return gn.str},"get")});Object.defineProperty(ie,"stringify",{enumerable:!0,get:o(function(){return gn.stringify},"get")});Object.defineProperty(ie,"nil",{enumerable:!0,get:o(function(){return gn.nil},"get")});Object.defineProperty(ie,"Name",{enumerable:!0,get:o(function(){return gn.Name},"get")});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:o(function(){return gn.CodeGen},"get")});var BA=Fa();Object.defineProperty(ie,"ValidationError",{enumerable:!0,get:o(function(){return BA.default},"get")});var VA=So();Object.defineProperty(ie,"MissingRefError",{enumerable:!0,get:o(function(){return VA.default},"get")})});var If=T(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.formatNames=Tt.fastFormats=Tt.fullFormats=void 0;function Ct(e,t){return{validate:e,compare:t}}o(Ct,"fmtDef");Tt.fullFormats={date:Ct(wf,sd),time:Ct(ad(!0),cd),"date-time":Ct(_f(!0),Rf),"iso-time":Ct(ad(),vf),"iso-date-time":Ct(_f(),bf),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:YA,"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:ok,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:XA,int32:{type:"number",validate:tk},int64:{type:"number",validate:rk},float:{type:"number",validate:Sf},double:{type:"number",validate:Sf},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sd),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,cd),"date-time":Ct(/^\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,Rf),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vf),"iso-date-time":Ct(/^\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,bf),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};Tt.formatNames=Object.keys(Tt.fullFormats);function FA(e){return e%4===0&&(e%100!==0||e%400===0)}o(FA,"isLeapYear");var ZA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,KA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function wf(e){let t=ZA.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&&FA(r)?29:KA[n])}o(wf,"date");function sd(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(sd,"compareDate");var od=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ad(e){return o(function(r){let n=od.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],u=n[4],d=n[5]==="-"?-1:1,l=+(n[6]||0),p=+(n[7]||0);if(l>23||p>59||e&&!u)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-p*d,f=a-l*d-(m<0?1:0);return(f===23||f===-1)&&(m===59||m===-1)&&s<61},"time")}o(ad,"getTime");function cd(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(cd,"compareTime");function vf(e,t){if(!(e&&t))return;let r=od.exec(e),n=od.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(vf,"compareIsoTime");var id=/t|\s/i;function _f(e){let t=ad(e);return o(function(n){let a=n.split(id);return a.length===2&&wf(a[0])&&t(a[1])},"date_time")}o(_f,"getDateTime");function Rf(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(Rf,"compareDateTime");function bf(e,t){if(!(e&&t))return;let[r,n]=e.split(id),[a,i]=t.split(id),s=sd(r,a);if(s!==void 0)return s||cd(n,i)}o(bf,"compareIsoDateTime");var WA=/\/|:/,JA=/^(?:[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 YA(e){return WA.test(e)&&JA.test(e)}o(YA,"uri");var yf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function XA(e){return yf.lastIndex=0,yf.test(e)}o(XA,"byte");var QA=-(2**31),ek=2**31-1;function tk(e){return Number.isInteger(e)&&e<=ek&&e>=QA}o(tk,"validateInt32");function rk(e){return Number.isInteger(e)}o(rk,"validateInt64");function Sf(){return!0}o(Sf,"validateNumber");var nk=/[^\\]\\Z/;function ok(e){if(nk.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(ok,"regex")});var Cf=T(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.formatLimitDefinition=void 0;var ak=nd(),ft=L(),lr=ft.operators,fi={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},ik={message:o(({keyword:e,schemaCode:t})=>(0,ft.str)`should be ${fi[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ft._)`{comparison: ${fi[e].okStr}, limit: ${t}}`,"params")};_n.formatLimitDefinition={keyword:Object.keys(fi),type:"string",schemaType:"string",$data:!0,error:ik,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 ak.KeywordCxt(i,u.RULES.all.format.definition,"format");d.$data?l():p();function l(){let f=t.scopeValue("formats",{ref:u.formats,code:s.code.formats}),_=t.const("fmt",(0,ft._)`${f}[${d.schemaCode}]`);e.fail$data((0,ft.or)((0,ft._)`typeof ${_} != "object"`,(0,ft._)`${_} instanceof RegExp`,(0,ft._)`typeof ${_}.compare != "function"`,m(_)))}o(l,"validate$DataFormat");function p(){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 S=t.scopeValue("formats",{key:f,ref:_,code:s.code.formats?(0,ft._)`${s.code.formats}${(0,ft.getProperty)(f)}`:void 0});e.fail$data(m(S))}o(p,"validateFormat");function m(f){return(0,ft._)`${f}.compare(${r}, ${n}) ${fi[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var sk=o(e=>(e.addKeyword(_n.formatLimitDefinition),e),"formatLimitPlugin");_n.default=sk});var Ef=T((Uo,kf)=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var yn=If(),ck=Cf(),ud=L(),Tf=new ud.Name("fullFormats"),uk=new ud.Name("fastFormats"),dd=o((e,t={keywords:!0})=>{if(Array.isArray(t))return Af(e,t,yn.fullFormats,Tf),e;let[r,n]=t.mode==="fast"?[yn.fastFormats,uk]:[yn.fullFormats,Tf],a=t.formats||yn.formatNames;return Af(e,a,r,n),t.keywords&&(0,ck.default)(e),e},"formatsPlugin");dd.get=(e,t="full")=>{let n=(t==="fast"?yn.fastFormats:yn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Af(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,ud._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(Af,"addFormats");kf.exports=Uo=dd;Object.defineProperty(Uo,"__esModule",{value:!0});Uo.default=dd});Jw();function Jt(e){return!!e._zod}o(Jt,"isZ4Schema");function Me(e,t){return Jt(e)?Ms(e,t):e.safeParse(t)}o(Me,"safeParse");function Jr(e){if(!e)return;let t;if(Jt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(Jr,"getObjectShape");function Ap(e){if(Jt(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(Ap,"getLiteralValue");X();var Xt="2025-11-25",kp="2025-03-26",Qt=[Xt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],er="io.modelcontextprotocol/related-task",wa="2.0",ve=Ip(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Ep=ce([h(),K().int()]),Pp=h(),_M=we({ttl:K().optional(),pollInterval:K().optional()}),Qw=I({ttl:K().optional()}),ev=I({taskId:h()}),js=we({progressToken:Ep.optional(),[er]:ev.optional()}),Qe=I({_meta:js.optional()}),Zn=Qe.extend({task:Qw.optional()}),xp=o(e=>Zn.safeParse(e).success,"isTaskAugmentedRequestParams"),be=I({method:h(),params:Qe.loose().optional()}),tt=I({_meta:js.optional()}),rt=I({method:h(),params:tt.loose().optional()}),Ie=we({_meta:js.optional()}),va=ce([h(),K().int()]),Op=I({jsonrpc:E(wa),id:va,...be.shape}).strict(),wt=o(e=>Op.safeParse(e).success,"isJSONRPCRequest"),Up=I({jsonrpc:E(wa),...rt.shape}).strict(),zp=o(e=>Up.safeParse(e).success,"isJSONRPCNotification"),Hs=I({jsonrpc:E(wa),id:va,result:Ie}).strict(),dt=o(e=>Hs.safeParse(e).success,"isJSONRPCResultResponse");var k;(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"})(k||(k={}));var Gs=I({jsonrpc:E(wa),id:va.optional(),error:I({code:K().int(),message:h(),data:fe().optional()})}).strict();var Xr=o(e=>Gs.safeParse(e).success,"isJSONRPCErrorResponse");var wr=ce([Op,Up,Hs,Gs]),yM=ce([Hs,Gs]),zt=Ie.strict(),tv=tt.extend({requestId:va.optional(),reason:h().optional()}),Ra=rt.extend({method:E("notifications/cancelled"),params:tv}),rv=I({src:h(),mimeType:h().optional(),sizes:b(h()).optional(),theme:Xe(["light","dark"]).optional()}),Kn=I({icons:b(rv).optional()}),Yr=I({name:h(),title:h().optional()}),Qr=Yr.extend({...Yr.shape,...Kn.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),nv=$s(I({applyDefaults:te().optional()}),oe(h(),fe())),ov=Ls(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,$s(I({form:nv.optional(),url:ve.optional()}),oe(h(),fe()).optional())),av=we({list:ve.optional(),cancel:ve.optional(),requests:we({sampling:we({createMessage:ve.optional()}).optional(),elicitation:we({create:ve.optional()}).optional()}).optional()}),iv=we({list:ve.optional(),cancel:ve.optional(),requests:we({tools:we({call:ve.optional()}).optional()}).optional()}),sv=I({experimental:oe(h(),ve).optional(),sampling:I({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:ov.optional(),roots:I({listChanged:te().optional()}).optional(),tasks:av.optional(),extensions:oe(h(),ve).optional()}),cv=Qe.extend({protocolVersion:h(),capabilities:sv,clientInfo:Qr}),ba=be.extend({method:E("initialize"),params:cv}),Bs=o(e=>ba.safeParse(e).success,"isInitializeRequest"),uv=I({experimental:oe(h(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:I({listChanged:te().optional()}).optional(),resources:I({subscribe:te().optional(),listChanged:te().optional()}).optional(),tools:I({listChanged:te().optional()}).optional(),tasks:iv.optional(),extensions:oe(h(),ve).optional()}),Vs=Ie.extend({protocolVersion:h(),capabilities:uv,serverInfo:Qr,instructions:h().optional()}),Ia=rt.extend({method:E("notifications/initialized"),params:tt.optional()}),Np=o(e=>Ia.safeParse(e).success,"isInitializedNotification"),Ca=be.extend({method:E("ping"),params:Qe.optional()}),dv=I({progress:K(),total:pe(K()),message:pe(h())}),lv=I({...tt.shape,...dv.shape,progressToken:Ep}),Ta=rt.extend({method:E("notifications/progress"),params:lv}),pv=Qe.extend({cursor:Pp.optional()}),Wn=be.extend({params:pv.optional()}),Jn=Ie.extend({nextCursor:Pp.optional()}),mv=Xe(["working","input_required","completed","failed","cancelled"]),Yn=I({taskId:h(),status:mv,ttl:ce([K(),Rp()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:pe(K()),statusMessage:pe(h())}),Nt=Ie.extend({task:Yn}),hv=tt.merge(Yn),Xn=rt.extend({method:E("notifications/tasks/status"),params:hv}),Aa=be.extend({method:E("tasks/get"),params:Qe.extend({taskId:h()})}),ka=Ie.merge(Yn),Ea=be.extend({method:E("tasks/result"),params:Qe.extend({taskId:h()})}),SM=Ie.loose(),Pa=Wn.extend({method:E("tasks/list")}),xa=Jn.extend({tasks:b(Yn)}),Oa=be.extend({method:E("tasks/cancel"),params:Qe.extend({taskId:h()})}),Dp=Ie.merge(Yn),Mp=I({uri:h(),mimeType:pe(h()),_meta:oe(h(),fe()).optional()}),qp=Mp.extend({text:h()}),Fs=h().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$p=Mp.extend({blob:Fs}),Qn=Xe(["user","assistant"]),en=I({audience:b(Qn).optional(),priority:K().min(0).max(1).optional(),lastModified:wp.datetime({offset:!0}).optional()}),Lp=I({...Yr.shape,...Kn.shape,uri:h(),description:pe(h()),mimeType:pe(h()),size:pe(K()),annotations:en.optional(),_meta:pe(we({}))}),fv=I({...Yr.shape,...Kn.shape,uriTemplate:h(),description:pe(h()),mimeType:pe(h()),annotations:en.optional(),_meta:pe(we({}))}),Zs=Wn.extend({method:E("resources/list")}),Ks=Jn.extend({resources:b(Lp)}),gv=Wn.extend({method:E("resources/templates/list")}),Ws=Jn.extend({resourceTemplates:b(fv)}),Js=Qe.extend({uri:h()}),_v=Js,Ys=be.extend({method:E("resources/read"),params:_v}),Xs=Ie.extend({contents:b(ce([qp,$p]))}),Qs=rt.extend({method:E("notifications/resources/list_changed"),params:tt.optional()}),yv=Js,Sv=be.extend({method:E("resources/subscribe"),params:yv}),wv=Js,vv=be.extend({method:E("resources/unsubscribe"),params:wv}),Rv=tt.extend({uri:h()}),bv=rt.extend({method:E("notifications/resources/updated"),params:Rv}),Iv=I({name:h(),description:pe(h()),required:pe(te())}),Cv=I({...Yr.shape,...Kn.shape,description:pe(h()),arguments:pe(b(Iv)),_meta:pe(we({}))}),ec=Wn.extend({method:E("prompts/list")}),tc=Jn.extend({prompts:b(Cv)}),Tv=Qe.extend({name:h(),arguments:oe(h(),h()).optional()}),rc=be.extend({method:E("prompts/get"),params:Tv}),nc=I({type:E("text"),text:h(),annotations:en.optional(),_meta:oe(h(),fe()).optional()}),oc=I({type:E("image"),data:Fs,mimeType:h(),annotations:en.optional(),_meta:oe(h(),fe()).optional()}),ac=I({type:E("audio"),data:Fs,mimeType:h(),annotations:en.optional(),_meta:oe(h(),fe()).optional()}),Av=I({type:E("tool_use"),name:h(),id:h(),input:oe(h(),fe()),_meta:oe(h(),fe()).optional()}),kv=I({type:E("resource"),resource:ce([qp,$p]),annotations:en.optional(),_meta:oe(h(),fe()).optional()}),Ev=Lp.extend({type:E("resource_link")}),ic=ce([nc,oc,ac,Ev,kv]),Pv=I({role:Qn,content:ic}),sc=Ie.extend({description:h().optional(),messages:b(Pv)}),cc=rt.extend({method:E("notifications/prompts/list_changed"),params:tt.optional()}),xv=I({title:h().optional(),readOnlyHint:te().optional(),destructiveHint:te().optional(),idempotentHint:te().optional(),openWorldHint:te().optional()}),Ov=I({taskSupport:Xe(["required","optional","forbidden"]).optional()}),jp=I({...Yr.shape,...Kn.shape,description:h().optional(),inputSchema:I({type:E("object"),properties:oe(h(),ve).optional(),required:b(h()).optional()}).catchall(fe()),outputSchema:I({type:E("object"),properties:oe(h(),ve).optional(),required:b(h()).optional()}).catchall(fe()).optional(),annotations:xv.optional(),execution:Ov.optional(),_meta:oe(h(),fe()).optional()}),uc=Wn.extend({method:E("tools/list")}),dc=Jn.extend({tools:b(jp)}),tr=Ie.extend({content:b(ic).default([]),structuredContent:oe(h(),fe()).optional(),isError:te().optional()}),wM=tr.or(Ie.extend({toolResult:fe()})),Uv=Zn.extend({name:h(),arguments:oe(h(),fe()).optional()}),eo=be.extend({method:E("tools/call"),params:Uv}),lc=rt.extend({method:E("notifications/tools/list_changed"),params:tt.optional()}),Hp=I({autoRefresh:te().default(!0),debounceMs:K().int().nonnegative().default(300)}),to=Xe(["debug","info","notice","warning","error","critical","alert","emergency"]),zv=Qe.extend({level:to}),pc=be.extend({method:E("logging/setLevel"),params:zv}),Nv=tt.extend({level:to,logger:h().optional(),data:fe()}),Dv=rt.extend({method:E("notifications/message"),params:Nv}),Mv=I({name:h().optional()}),qv=I({hints:b(Mv).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),$v=I({mode:Xe(["auto","required","none"]).optional()}),Lv=I({type:E("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:b(ic).default([]),structuredContent:I({}).loose().optional(),isError:te().optional(),_meta:oe(h(),fe()).optional()}),jv=qs("type",[nc,oc,ac]),Sa=qs("type",[nc,oc,ac,Av,Lv]),Hv=I({role:Qn,content:ce([Sa,b(Sa)]),_meta:oe(h(),fe()).optional()}),Gv=Zn.extend({messages:b(Hv),modelPreferences:qv.optional(),systemPrompt:h().optional(),includeContext:Xe(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:b(h()).optional(),metadata:ve.optional(),tools:b(jp).optional(),toolChoice:$v.optional()}),mc=be.extend({method:E("sampling/createMessage"),params:Gv}),vr=Ie.extend({model:h(),stopReason:pe(Xe(["endTurn","stopSequence","maxTokens"]).or(h())),role:Qn,content:jv}),ro=Ie.extend({model:h(),stopReason:pe(Xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:Qn,content:ce([Sa,b(Sa)])}),Bv=I({type:E("boolean"),title:h().optional(),description:h().optional(),default:te().optional()}),Vv=I({type:E("string"),title:h().optional(),description:h().optional(),minLength:K().optional(),maxLength:K().optional(),format:Xe(["email","uri","date","date-time"]).optional(),default:h().optional()}),Fv=I({type:Xe(["number","integer"]),title:h().optional(),description:h().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),Zv=I({type:E("string"),title:h().optional(),description:h().optional(),enum:b(h()),default:h().optional()}),Kv=I({type:E("string"),title:h().optional(),description:h().optional(),oneOf:b(I({const:h(),title:h()})),default:h().optional()}),Wv=I({type:E("string"),title:h().optional(),description:h().optional(),enum:b(h()),enumNames:b(h()).optional(),default:h().optional()}),Jv=ce([Zv,Kv]),Yv=I({type:E("array"),title:h().optional(),description:h().optional(),minItems:K().optional(),maxItems:K().optional(),items:I({type:E("string"),enum:b(h())}),default:b(h()).optional()}),Xv=I({type:E("array"),title:h().optional(),description:h().optional(),minItems:K().optional(),maxItems:K().optional(),items:I({anyOf:b(I({const:h(),title:h()}))}),default:b(h()).optional()}),Qv=ce([Yv,Xv]),eR=ce([Wv,Jv,Qv]),tR=ce([eR,Bv,Vv,Fv]),rR=Zn.extend({mode:E("form").optional(),message:h(),requestedSchema:I({type:E("object"),properties:oe(h(),tR),required:b(h()).optional()})}),nR=Zn.extend({mode:E("url"),message:h(),elicitationId:h(),url:h().url()}),oR=ce([rR,nR]),hc=be.extend({method:E("elicitation/create"),params:oR}),aR=tt.extend({elicitationId:h()}),iR=rt.extend({method:E("notifications/elicitation/complete"),params:aR}),rr=Ie.extend({action:Xe(["accept","decline","cancel"]),content:Ls(e=>e===null?void 0:e,oe(h(),ce([h(),K(),te(),b(h())])).optional())}),sR=I({type:E("ref/resource"),uri:h()});var cR=I({type:E("ref/prompt"),name:h()}),uR=Qe.extend({ref:ce([cR,sR]),argument:I({name:h(),value:h()}),context:I({arguments:oe(h(),h()).optional()}).optional()}),dR=be.extend({method:E("completion/complete"),params:uR});var fc=Ie.extend({completion:we({values:b(h()).max(100),total:pe(K().int()),hasMore:pe(te())})}),lR=I({uri:h().startsWith("file://"),name:h().optional(),_meta:oe(h(),fe()).optional()}),pR=be.extend({method:E("roots/list"),params:Qe.optional()}),gc=Ie.extend({roots:b(lR)}),mR=rt.extend({method:E("notifications/roots/list_changed"),params:tt.optional()}),vM=ce([Ca,ba,dR,pc,rc,ec,Zs,gv,Ys,Sv,vv,eo,uc,Aa,Ea,Pa,Oa]),RM=ce([Ra,Ta,Ia,mR,Xn]),bM=ce([zt,vr,ro,rr,gc,ka,xa,Nt]),IM=ce([Ca,mc,hc,pR,Aa,Ea,Pa,Oa]),CM=ce([Ra,Ta,Dv,bv,Qs,lc,cc,Xn,iR]),TM=ce([zt,Vs,fc,sc,tc,Ks,Ws,Xs,tr,dc,ka,xa,Nt]),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===k.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new Yt(a.elicitations,r)}return new e(t,r,n)}},Yt=class extends A{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(k.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function nr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(nr,"isTerminal");var hR=Symbol("Let zodToJsonSchema decide on which parser to use");var bq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _c(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ap(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(_c,"getMethodLiteral");function yc(e,t){let r=Me(e,t);if(!r.success)throw r.error;return r.data}o(yc,"parseWithCompat");var wR=6e4,tn=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(Ra,r=>{this._oncancel(r)}),this.setNotificationHandler(Ta,r=>{this._onprogress(r)}),this.setRequestHandler(Ca,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Aa,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(k.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Ea,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,l=d.id,p=this._requestResolvers.get(l);if(p)if(this._requestResolvers.delete(l),u.type==="response")p(d);else{let m=d,f=new A(m.error.code,m.error.message,m.error.data);p(f)}else{let m=u.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${l}`))}continue}await this._transport?.send(u.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new A(k.InvalidParams,`Task not found: ${i}`);if(!nr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(nr(s.status)){let u=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...u,_meta:{...u._meta,[er]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(Pa,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(k.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(Oa,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(k.InvalidParams,`Task not found: ${r.params.taskId}`);if(nr(a.status))throw new A(k.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(k.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof A?a:new A(k.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(k.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),dt(i)||Xr(i)?this._onresponse(i):wt(i)?this._onrequest(i,s):zp(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(k.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?.[er]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:t.id,error:{code:k.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},a?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):a?.send(p).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=xp(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,l={signal:s.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async p=>{if(s.signal.aborted)return;let m={relatedRequestId:t.id};i&&(m.relatedTask={taskId:i}),await this.notification(p,m)},"sendNotification"),sendRequest:o(async(p,m,f)=>{if(s.signal.aborted)throw new A(k.ConnectionClosed,"Request was cancelled");let _={...f,relatedRequestId:t.id};i&&!_.relatedTask&&(_.relatedTask={taskId:i});let S=_.relatedTask?.taskId??i;return S&&d&&await d.updateTaskStatus(S,"input_required"),await this.request(p,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,l)).then(async p=>{if(s.signal.aborted)return;let m={result:p,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 p=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(p.code)?p.code:k.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).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),dt(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(dt(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),dt(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(k.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Nt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(k.InternalError,"Task creation did not return a task");for(;;){let u=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:u},nr(u.status)){u.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:u.status==="failed"?yield{type:"error",error:new A(k.InternalError,`Task ${i} failed`)}:u.status==="cancelled"&&(yield{type:"error",error:new A(k.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(l=>setTimeout(l,d)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(k.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:u,relatedTask:d}=n??{};return new Promise((l,p)=>{let m=o(R=>{p(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||{},[er]:d}});let S=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(N=>this._onerror(new Error(`Failed to send cancellation: ${N}`)));let C=R instanceof A?R:new A(k.RequestTimeout,String(R));p(C)},"cancel");this._responseHandlers.set(f,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return p(R);try{let C=Me(r,R.result);C.success?l(C.data):p(C.error)}catch(C){p(C)}}}),n?.signal?.addEventListener("abort",()=>{S(n?.signal?.reason)});let y=n?.timeout??wR,w=o(()=>S(A.fromError(k.RequestTimeout,"Request timed out",{timeout:y})),"timeoutHandler");this._setupTimeout(f,y,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let R=o(C=>{let N=this._responseHandlers.get(f);N?N(C):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(C=>{this._cleanupTimeout(f),p(C)})}else this._transport.send(_,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(R=>{this._cleanupTimeout(f),p(R)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ka,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},xa,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Dp,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||{},[er]: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||{},[er]: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||{},[er]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=_c(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=yc(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=_c(t);this._notificationHandlers.set(n,a=>{let i=yc(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"&&wt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new A(k.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(k.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new A(k.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(k.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=Xn.parse({method:"notifications/tasks/status",params:u});await this.notification(d),nr(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 A(k.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(nr(u.status))throw new A(k.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 l=Xn.parse({method:"notifications/tasks/status",params:d});await this.notification(l),nr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function Gp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Gp,"isPlainObject");function Ua(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];Gp(s)&&Gp(i)?r[a]={...s,...i}:r[a]=i}return r}o(Ua,"mergeCapabilities");var Pf=fp(nd(),1),xf=fp(Ef(),1);function dk(){let e=new Pf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,xf.default)(e),e}o(dk,"createDefaultAjvInstance");var Sn=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??dk()}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 gi=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(p=>p.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]:[],l=d.some(p=>p.type==="tool_use");if(s){if(i.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let p=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(p.size!==m.size||![...p].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},vr,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},rr,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 _i(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(_i,"assertToolsCallTaskCapability");function yi(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(yi,"assertClientRequestTaskCapability");var Si=class extends tn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(to.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 Sn,this.setRequestHandler(ba,n=>this._oninitialize(n)),this.setNotificationHandler(Ia,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pc,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,u=to.safeParse(s);return u.success&&this._loggingLevels.set(i,u.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new gi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ua(this._capabilities,t)}setRequestHandler(t,r){let a=Jr(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(Jt(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,l)=>{let p=Me(eo,d);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new A(k.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:m}=p.data,f=await Promise.resolve(r(d,l));if(m.task){let S=Me(Nt,f);if(!S.success){let y=S.error instanceof Error?S.error.message:String(S.error);throw new A(k.InvalidParams,`Invalid task creation result: ${y}`)}return S.data}let _=Me(tr,f);if(!_.success){let S=_.error instanceof Error?_.error.message:String(_.error);throw new A(k.InvalidParams,`Invalid tools/call result: ${S}`)}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){yi(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&_i(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:Qt.includes(r)?r:Xt,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"},zt)}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(l=>l.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(l=>l.type==="tool_use");if(i){if(a.some(l=>l.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 l=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==p.size||![...l].every(m=>p.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},ro,r):this.request({method:"sampling/createMessage",params:t},vr,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},rr,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},rr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let u=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!u.valid)throw new A(k.InvalidParams,`Elicitation response content does not match requested schema: ${u.errorMessage}`)}catch(s){throw s instanceof A?s:new A(k.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},gc,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 wi=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
- `;this._retryInterval!==void 0&&(i=`id: ${s}
35
+ `;this._retryInterval!==void 0&&(s=`id: ${i}
36
36
  retry: ${this._retryInterval}
37
37
  data:
38
38
 
39
- `),t.enqueue(r.encode(i))}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 s=new TextEncoder,i,c=new ReadableStream({start:o(p=>{i=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:i,encoder:s,cleanup:o(()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.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,s,i=new ReadableStream({start:o(d=>{s=d},"start"),cancel:o(()=>{},"cancel")}),c=await this._eventStore.replayEventsAfter(t,{send:o(async(d,p)=>{if(!this.writeSSEEvent(s,a,p,d)){this.onerror?.(new Error("Failed replay events"));try{s.close()}catch{}}},"send")});return this._streamMapping.set(c,{controller:s,encoder:a,cleanup:o(()=>{this._streamMapping.delete(c);try{s.close()}catch{}},"cleanup")}),new Response(i,{headers:n})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(t,r,n,a){try{let s=`event: message
40
- `;return a&&(s+=`id: ${a}
41
- `),s+=`data: ${JSON.stringify(n)}
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 l=t.headers.get("last-event-id");if(l)return this.replayEvents(l)}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(l=>{s=l},"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,l)=>{if(!this.writeSSEEvent(i,a,l,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
40
+ `;return a&&(i+=`id: ${a}
41
+ `),i+=`data: ${JSON.stringify(n)}
42
42
 
43
- `,t.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!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 s={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=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(i)?c=i.map(v=>hr.parse(v)):c=[hr.parse(i)]}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(Ai);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(mt)){for(let v of c)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(v=>Ai(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Yl;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)mt(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:s})});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 c)mt(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,h);for(let v of c){let b,T;mt(v)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),T=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:b,closeStandaloneSSEStream:T})}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&&!Ft.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ft.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ft.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((nt(t)||Gr(t))&&(n=t.id),n===void 0){if(nt(t)||Gr(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=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,i);return}let a=this._requestToStreamMapping.get(n);if(!a)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(a);if(!this._enableJsonResponse&&s?.controller&&s?.encoder){let i;this._eventStore&&(i=await this._eventStore.storeEvent(a,t)),this.writeSSEEvent(s.controller,s.encoder,t,i)}if(nt(t)||Gr(t)){this._requestResponseMap.set(n,t);let i=Array.from(this._requestToStreamMapping.entries()).filter(([d,p])=>p===a).map(([d])=>d);if(i.every(d=>this._requestResponseMap.has(d))){if(!s)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&s.resolveJson){let d={"Content-Type":"application/json"};this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId);let p=i.map(l=>this._requestResponseMap.get(l));p.length===1?s.resolveJson(new Response(JSON.stringify(p[0]),{status:200,headers:d})):s.resolveJson(new Response(JSON.stringify(p),{status:200,headers:d}))}else s.cleanup();for(let d of i)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function Wu(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(Wu,"truncate");function th(e){return"cause"in e?e.cause:void 0}o(th,"readCause");function Re(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=Wu(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=Wu(r.message);let n=th(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let s=a===1?"cause":`cause${a}`;e[`${s}Name`]=n.name,e[`${s}Message`]=Wu(n.message),n=th(n)}}o(Re,"addErrorLogFields");function et(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(et,"safeHost");function rh(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(rh,"setLogProperties");function Ju(e,t){rh(e,{tenantId:t.tenantId,subjectId:t.subjectId})}o(Ju,"applyGatewayPrincipalLogProperties");function nh(e,t){rh(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(nh,"applyGatewayRouteLogProperties");var ln={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."}}},oh={...ln.runtime,...ln.config,...ln.downstream_auth,...ln.downstream_oauth,...ln.upstream_auth,...ln.upstream_mcp};function Yu(e){return typeof e=="string"&&Object.hasOwn(oh,e)}o(Yu,"isGatewayProblemCode");function as(e){return Yu(e)&&Le(e).callbackFailure===!0}o(as,"isGatewayCallbackFailureCode");function Le(e){return oh[e]}o(Le,"readGatewayProblemDefinition");var ah="gatewayCode";function sh(e){let t=Le(e);return{title:t.title,body:t.publicDetail}}o(sh,"readGatewayCallbackFailureContent");function ae(e){if(!(e instanceof ra))return;let t=e.extensionMembers?.[ah];return Yu(t)?t:void 0}o(ae,"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=Le(n.code),s=n.privateDetail??(ss(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),i=FC(n);return new ra({message:s,extensionMembers:{[ah]:n.code}},i===void 0?void 0:{cause:i})}o(g,"createGatewayRuntimeError");async function je(e,t,r){let n=Le(r.code),a=ZC(r.code,r.detail),s=ss(r.code)?r.title??n.title:n.title,c={problem:{...Nn.getProblemFromStatus(n.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:n.status,title:s,detail:a,code:r.code}};return r.headers!==void 0&&(c.additionalHeaders=r.headers),Nn.format(c,e,t)}o(je,"gatewayProblemResponse");function ss(e){return Le(e).status<500}o(ss,"canExposeGatewayProblemDetail");function FC(e){return!e.privateDetail||ss(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(FC,"readRuntimeErrorCause");function ZC(e,t){let r=Le(e);return ss(e)&&t||r.publicDetail}o(ZC,"readSafeGatewayProblemDetail");W();var KC=["tenant_shared_oauth","user_oauth","static_secret","user_static_secret","tenant_static_secret"],WC=["none","client_secret_basic","client_secret_post"],ut=u.string().min(1).brand(),ge=u.string().min(1).brand(),dt=u.string().min(1).brand(),St=u.string().min(1).brand(),is=u.enum(KC),Xu=u.enum(WC),cs=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),Qu=u.object({name:cs,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();var ed=new Map;function us(e){ed.set(e.policyType,e)}o(us,"registerMcpAuthorizationPolicy");function td(e){if(e!==void 0)return ed.get(e)}o(td,"getMcpAuthorizationPolicy");function ds(e){return td(e)!==void 0}o(ds,"isRegisteredMcpAuthorizationPolicyType");function rd(){return[...ed.keys()]}o(rd,"listMcpAuthorizationPolicyTypes");W();var uh=ut,JC=u.object({mode:u.literal("auto")}).strict(),YC=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Xu.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"]})}),dh=u.discriminatedUnion("mode",[JC,YC]),XC=dh.default({mode:"auto"}),nd=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:XC}).strict(),ih=nd.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),lh=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),QC=new Set([...lh,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),eE=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),tE=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:cs,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 s=a.name.toLowerCase();lh.has(s)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for static secret injection`,path:["headers",n,"name"]}),r.has(s)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate static secret header ${a.name}`,path:["headers",n,"name"]}),r.add(s)}}),od=u.discriminatedUnion("kind",[eE,tE]),rE=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(),nE=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),ad=u.discriminatedUnion("kind",[rE,nE]),sd=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),oE=u.discriminatedUnion("mode",[u.object({mode:u.literal("tenant_shared_oauth"),oauth:ih}).strict(),u.object({mode:u.literal("user_oauth"),oauth:ih}).strict(),u.object({mode:u.literal("static_secret"),secret:od}).strict(),u.object({mode:u.literal("user_static_secret"),secret:ad}).strict(),u.object({mode:u.literal("tenant_static_secret"),secret:sd}).strict()]),aE=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(Qu).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let s=a.name.toLowerCase();QC.has(s)&&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(s)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate native MCP transport request header ${a.name}`,path:["requestHeaders",n,"name"]}),r.add(s)}}),Wj=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Br.optional(),authProfiles:u.record(dt,oE),transport:aE}).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"]})}),sE=u.object({tenant_shared_oauth:nd.optional(),user_oauth:nd.optional(),static_secret:u.object({secret:od}).strict().optional(),user_static_secret:u.object({secret:ad}).strict().optional(),tenant_static_secret:u.object({secret:sd}).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"})}),ch=u.object({id:uh,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Br.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(Qu).default([]),authProfiles:sE}).strict(),iE=u.object({name:cs,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),ls={id:uh.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:Br.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(iE).default([])},cE=u.discriminatedUnion("authMode",[u.object({...ls,authMode:u.enum(["tenant_shared_oauth","user_oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:dh.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Xu.optional()}).strict(),u.object({...ls,authMode:u.literal("static_secret"),secret:od}).strict(),u.object({...ls,authMode:u.literal("user_static_secret"),secret:ad}).strict(),u.object({...ls,authMode:u.literal("tenant_static_secret"),secret:sd}).strict()]);function ph(e){throw g("internal_server_error",e)}o(ph,"throwGatewayConfigError");function uE(e){let t="mcp-upstream-";return e.startsWith(t)||ph(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),ut.parse(e.slice(t.length))}o(uE,"inferUpstreamConnectionIdFromPolicyName");function dE(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(dE,"buildDefaultProtectedResourceMetadataUrl");function pn(e,t){return dt.parse(`${e}:${t}`)}o(pn,"buildUpstreamAuthProfileId");function ps(e,t){let r=ch.safeParse(e);if(r.success)return r.data;let n=cE.parse(e),a=n.id??(t===void 0?void 0:uE(t));a===void 0&&ph("Upstream policy options must include id when policy name is unavailable.");let s=n.requestHeaders.map(c=>({name:c.name,value:c.value,required:c.required})),i=(()=>{switch(n.authMode){case"tenant_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_static_secret":case"tenant_static_secret":return{[n.authMode]:{secret:n.secret}}}})();return ch.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??dE(n.mcpUrl),requestHeaders:s,authProfiles:i})}o(ps,"parseUpstreamConnectionPolicyOptions");function mh(e){return e.mode==="tenant_shared_oauth"||e.mode==="user_oauth"}o(mh,"isUpstreamOAuthAuthConfig");W();var lE=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),pE=u.looseObject({}),mE=u.looseObject({name:St,namespace:St.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:pE}),fE=u.looseObject({name:St,namespace:St.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),hE=u.looseObject({name:St,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),gE=u.enum(["openapi","upstream_mcp"]),_E=u.object({catalogSource:gE.default("openapi"),serverInfo:lE.optional(),tools:u.array(mE).default([]),prompts:u.array(fE).default([]),resources:u.array(hE).default([])}).strict();function fh(e){return _E.parse(e??{})}o(fh,"parseVirtualServerRouteOptions");function ms(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(ms,"toMcpTool");function fs(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(fs,"toMcpPrompt");function hs(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(hs,"toMcpResource");var yE="mcp-upstream-connection-inbound",hh="/mcp/";function Pe(e){throw new Tt(e)}o(Pe,"throwRegistryError");function gh(e){return e.policyType===yE}o(gh,"isUpstreamConnectionPolicy");function wE(e){return ds(e.policyType)}o(wE,"isMcpOAuthInboundPolicy");function SE(e){e.startsWith(hh)||Pe(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(hh.length);return(!t||t.includes("/"))&&Pe(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),ge.parse(t)}o(SE,"readVirtualServerIdFromPath");function vE(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Pe(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Pe(`Upstream policy ${e.policyName} does not declare an auth mode.`),is.parse(r)}o(vE,"readSingleAuthMode");function bE(e){let t=e.connection.authProfiles[e.authMode];t||Pe(`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"tenant_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_static_secret":return{mode:"user_static_secret",secret:t.secret};case"tenant_static_secret":return{mode:"tenant_static_secret",secret:t.secret}}}o(bE,"buildResolvedAuthConfig");function RE(e){let t=vE({policyName:e.policyName,connection:e.connection}),r=pn(e.connection.id,t),n=bE({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(RE,"buildRegisteredConnection");function IE(e){let t=new Map;for(let r of e)t.has(r.name)&&Pe(`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(IE,"buildPolicyMap");function TE(e){let t=new Map,r=new Set;for(let n of e.values()){if(!gh(n))continue;let a=ps(n.handler.options,n.name);r.has(a.id)&&Pe(`Duplicate upstream MCP connection id ${a.id} in policies.json.`),r.add(a.id);let s=RE({policyName:n.name,connection:a});t.set(n.name,s)}return t}o(TE,"buildConnectionsByPolicyName");function CE(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(CE,"readOperationId");function _h(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return St.parse(t)}catch{Pe(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(_h,"buildPublishedCapabilityName");function cd(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Pe(`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;Pe(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(cd,"readCapabilityUpstreamPolicy");function id(e){e.seen.has(e.key)&&Pe(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(id,"assertUniqueCatalogKey");function EE(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=_h({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:cd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(EE,"normalizeCatalogTool");function AE(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=_h({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:cd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(AE,"normalizeCatalogPrompt");function PE(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:cd({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(PE,"normalizeCatalogResource");function xE(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>EE({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>AE({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>PE({resource:d,connections:e.connections,routePath:e.routePath})),s=new Set;for(let d of r)id({kind:"tool",key:d.name,routePath:e.routePath,seen:s});let i=new Set;for(let d of n)id({kind:"prompt",key:d.name,routePath:e.routePath,seen:i});let c=new Set;for(let d of a)id({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(xE,"normalizeVirtualServerCatalog");function kE(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 s=a[0],i=s===void 0?void 0:e.policyByName.get(s);if(!i||!wE(i))continue;let c=CE(n);c||Pe(`MCP virtual server route ${n.path} must declare an operationId in routes.oas.json.`),r.has(c)&&Pe(`Duplicate MCP virtual server operationId ${c} across routes.`),r.add(c);let d=SE(n.path);t.has(d)&&Pe(`Duplicate MCP virtual server id ${d} across routes.`);let p=[];for(let h of a.slice(1)){let _=e.policyByName.get(h);if(!_||!gh(_))continue;let w=e.connectionsByPolicyName.get(h);w||Pe(`Upstream connection policy ${h} referenced by route ${n.path} could not be resolved.`),p.push(w)}let l=fh(n.handler.options),m=xE({catalog:l,connections:p,routePath:n.path});m.catalogSource==="upstream_mcp"&&p.length!==1&&Pe(`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(kE,"buildVirtualServers");function yh(e){let t=IE(e.policies),r=TE(t),n=kE({routes:e.routes,policyByName:t,connectionsByPolicyName:r}),a=new Map;for(let s of r.values())a.set(s.upstreamServerId,s);return{byVirtualServerId:n,connectionsById:a}}o(yh,"buildGatewayConnectionRegistry");var gs;function wh(e){gs=e}o(wh,"setGatewayConnectionRegistry");function tt(){if(!gs)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 gs}o(tt,"getGatewayConnectionRegistry");function Sh(e){let t=tt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return t}o(Sh,"getRegisteredVirtualServer");function bo(e){let t=tt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(bo,"requireRegisteredVirtualServer");function vh(){return gs}o(vh,"tryGetGatewayConnectionRegistry");var bh=new Ct("gateway-route");function Rh(e,t){bh.set(e,t)}o(Rh,"setGatewayRouteContext");function Ro(e){return bh.get(e)}o(Ro,"readGatewayRouteContext");function mn(e){let t=Ro(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(mn,"requireGatewayRouteContext");var Er="2025-06-18";var OE=new Set(["localhost","::1"]);function rt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(rt,"normalizeHostname");function Ue(e){let t=rt(e.hostname);return e.protocol==="http:"&&(OE.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(Ue,"isLoopbackHttpUrl");function Q(e){return new URL(e).origin}o(Q,"readGatewayRequestOrigin");import{metrics as UE,context as _s,propagation as Th,SpanKind as Ch,SpanStatusCode as ud,trace as Io}from"@opentelemetry/api";var NE="mcp-gateway",$E="mcp-gateway",zE=Er,ME="2.0",Eh=Io.getTracer(NE),dd=UE.getMeter($E),DE=dd.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),qE=dd.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),LE=dd.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),jE=["traceparent","tracestate","baggage"];function ld(){return performance.now()/1e3}o(ld,"nowSeconds");function Ah(e,t){t(Math.max(ld()-e,0))}o(Ah,"recordDurationSeconds");function Ih(e){return e===void 0?void 0:String(e)}o(Ih,"stringifyAttribute");function Ie(e,t,r){r!==void 0&&(e[t]=r)}o(Ie,"assignAttribute");function HE(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(HE,"readTargetName");function Ph(e){let t=HE({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(Ph,"buildMcpOperationSpanName");function pd(e){let t={"mcp.method.name":e.methodName};return Ie(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??ME),Ie(t,"jsonrpc.request.id",Ih(e.jsonRpcRequestId)),Ie(t,"mcp.protocol.version",e.mcpProtocolVersion??zE),Ie(t,"mcp.session.id",e.mcpSessionId),Ie(t,"mcp.resource.uri",e.resourceUri),Ie(t,"rpc.response.status_code",Ih(e.rpcResponseStatusCode)),Ie(t,"error.type",e.errorType),e.capabilityType==="tool"&&(Ie(t,"gen_ai.operation.name","execute_tool"),Ie(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&Ie(t,"gen_ai.prompt.name",e.capabilityName),Ie(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),Ie(t,"network.protocol.version",e.networkProtocolVersion),Ie(t,"network.transport",e.networkTransport),Ie(t,"server.address",e.serverAddress),Ie(t,"server.port",e.serverPort),Ie(t,"client.address",e.clientAddress),Ie(t,"client.port",e.clientPort),t}o(pd,"buildMcpOperationAttributes");function GE(e){let t=pd({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(GE,"buildMcpSessionAttributes");function xh(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:ud.ERROR}),t instanceof Error&&e.recordException(t)}o(xh,"setSpanError");function kh(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(kh,"readErrorType");function BE(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?_s.active():Th.extract(_s.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(BE,"readServerParentContext");function VE(e){let t=Io.getSpanContext(_s.active()),r=Io.getSpanContext(e);if(!(!t||!Io.isSpanContextValid(t))&&!(r&&Io.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(VE,"readAmbientSpanLink");function Oh(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(Oh,"readResultErrorType");async function Ar(e,t){let r=ld(),n=pd({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return Eh.startActiveSpan(Ph(e),{kind:Ch.CLIENT,attributes:n},async a=>{try{let s=await t(),i=Oh(s);return i&&(a.setAttribute("error.type",i),a.setStatus({code:ud.ERROR}),n["error.type"]=i),s}catch(s){let i=e.errorType??kh(s);throw n["error.type"]=i,xh(a,s,i),s}finally{Ah(r,s=>{DE.record(s,n)}),a.end()}})}o(Ar,"runMcpClientOperation");async function Pr(e,t){let r=ld(),n=BE(e.params),a=pd({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),s=VE(n);return Eh.startActiveSpan(Ph(e),{kind:Ch.SERVER,attributes:a,...s?{links:s}:{}},n,async i=>{try{let c=await t(),d=Oh(c);return d&&(i.setAttribute("error.type",d),i.setStatus({code:ud.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??kh(c);throw a["error.type"]=d,xh(i,c,d),c}finally{Ah(r,c=>{qE.record(c,a)}),i.end()}})}o(Pr,"runMcpServerOperation");function Uh(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return Th.inject(_s.active(),t._meta,{set(r,n,a){jE.includes(n)&&(r[n]=a)}}),t}o(Uh,"injectMcpTraceContextIntoParams");function Nh(e,t){let r=GE({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});LE.record(Math.max(t,0),r)}o(Nh,"recordMcpClientSessionDuration");var md=new Ct("route-upstream-bindings");function FE(e){let t=md.get(e);if(t)return t;let r={bindings:[]};return md.set(e,r),r}o(FE,"readOrCreateRouteUpstreamBindingRegistry");function $h(e){return`${e.upstreamServerId}:${e.authProfileId}`}o($h,"buildRouteBindingDuplicateKey");function fd(e,t){let r=FE(e),n=$h(t);if(r.bindings.find(s=>$h(s)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.bindings.push(t)}o(fd,"appendResolvedUpstreamBindingContext");function zh(e){return md.get(e)?.bindings??[]}o(zh,"readResolvedUpstreamBindingContexts");W();function lt(e){return Q(e)}o(lt,"readGatewayOAuthIssuer");W();var fn=u.string().trim().min(1),To={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},ZE=u.object({issuer:u.url(),jwksUrl:u.url(),audience:fn}),KE=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:fn.optional(),clientSecret:fn.optional(),scope:fn.default("openid profile email"),audience:fn.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(),WE=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(To.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(To.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(To.cimdEnabled)}).strict().default(To),JE=u.object({oidc:ZE,browserLogin:KE,gateway:WE.optional().default(To),devTenantId:fn.optional()}).strict();function Mh(e){return YE(e.browserLogin.url)?"local_dev":"federated_oidc"}o(Mh,"readBrowserLoginKind");function YE(e){let t;try{t=new URL(e)}catch{return!1}return Ue(t)&&t.pathname==="/oauth/dev-login"}o(YE,"isLoopbackDevLoginUrl");function ys(e){return JE.parse(e)}o(ys,"parseMcpOAuthRuntimeConfig");var hd;function Dh(e){hd=e}o(Dh,"setGatewayOAuthConfig");function _e(){if(!hd)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 hd}o(_e,"getGatewayOAuthConfig");W();var XE=43,QE=128,eA=/^[A-Za-z0-9._~-]+$/,gd="S256",hn=u.literal(gd),ws=u.string().min(XE).max(QE).regex(eA);W();W();var Ne=u.string().datetime({offset:!0}).brand();function K(e){return Ne.parse(e.toISOString())}o(K,"toIsoTimestamp");function ar(e,t){return new Date(e.getTime()+t*1e3)}o(ar,"addSeconds");var Ss=["none","client_secret_post","client_secret_basic"],tA=[...Ss,"private_key_jwt"],rA=["awaiting_login","awaiting_setup"],nA=u.string().min(1).brand(),oA=u.string().min(1).brand(),Ze=u.string().min(1).brand(),$t=u.uuid().brand(),sr=u.uuid().brand(),vs=u.uuid().brand(),Co=u.enum(Ss),aA=u.enum(tA),_d=u.enum(rA),qh=u.object({client_id:Ze,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),token_endpoint_auth_method:aA.default("none")}),Lh=u.object({clientId:Ze,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:Co,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:Ne.optional(),clientExpiresAt:Ne,revokedAt:Ne.optional(),createdAt:Ne}),yd=u.object({clientId:Ze,resource:u.string(),virtualServerId:ge,tenantId:nA,subjectId:oA,scope:u.string(),roles:u.array(u.string()),createdAt:Ne,expiresAt:Ne}),jh=yd.extend({id:sr,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:hn}),Hh=yd.extend({id:$t,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:Ne.optional(),revokedReason:u.string().optional()}),Gh=yd.extend({tokenHash:u.string(),grantId:$t,revokedAt:Ne.optional()});function wd(){return sr.parse(crypto.randomUUID())}o(wd,"createDownstreamAuthorizationTransactionId");function Sd(){return vs.parse(crypto.randomUUID())}o(Sd,"createDownstreamBrowserLoginStateId");function Bh(){return $t.parse(crypto.randomUUID())}o(Bh,"createDownstreamGrantId");var oe="mcp:tools";function Rs(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return Ue(r)&&Ue(n)&&rt(r.hostname)===rt(n.hostname)&&r.pathname===n.pathname&&r.search===n.search}o(Rs,"redirectUriMatchesRegistration");function Vh(e){return Ue(e)&&e.pathname==="/oauth/dev-login"}o(Vh,"isLoopbackDevLoginUrl");function bs(e,t){return new URL(e,lt(t)).toString()}o(bs,"buildGatewayOAuthUrl");function vd(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,Q(e.requestUrl)).toString()}o(vd,"buildScopedAuthorizationServerIssuer");function sA(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,Q(e.requestUrl)).toString()}o(sA,"buildScopedAuthorizationEndpoint");function bd(e){let t=_e();return{issuer:lt(e),authorization_endpoint:bs("/oauth/authorize",e),token_endpoint:bs("/oauth/token",e),registration_endpoint:bs("/oauth/register",e),revocation_endpoint:bs("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[oe],code_challenge_methods_supported:[gd],token_endpoint_auth_methods_supported:Ss,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":Mh(t)}}o(bd,"buildAuthorizationServerMetadata");function Fh(e){let t=vd(e);return{...bd(e.requestUrl),issuer:t,authorization_endpoint:sA(e)}}o(Fh,"buildScopedAuthorizationServerMetadata");async function Zh(e,t){try{let r=ge.parse(e.params.virtualServerId),n=bo(r);return Response.json(iA(n.virtualServerId,e.url))}catch(r){let n=ae(r);return je(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(Zh,"protectedResourceMetadataHandler");function iA(e,t){return{resource:Eo(e,t),resource_name:e,authorization_servers:[vd({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[oe],mcp_protocol_version:Er}}o(iA,"buildProtectedResourceMetadataResponseBody");function Eo(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,Q(t)).toString()}o(Eo,"buildCanonicalMcpResourceForVirtualServer");function Kh(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,Q(t)).toString()}o(Kh,"buildProtectedResourceMetadataUrlForVirtualServer");var cA=u.record(u.string(),u.unknown()),Wh=u.string().min(1),uA=u.union([Wh.transform(e=>[e]),u.array(Wh)]),$e=u.string().min(1).brand(),le=u.string().min(1).brand(),dA=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],lA=["https://zuplo.com/roles","roles","role","permissions","groups"],pA=$e.parse("zuplo-poc"),Jh=new Ct("gateway-principal");function mA(e){let t=cA.safeParse(e);return t.success?t.data:{}}o(mA,"toClaimRecord");function fA(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(fA,"readValidationFailureDetail");function hA(e,t,r){for(let s of dA){let i=le.safeParse(t[s]);if(i.success)return i.data}let n=le.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",fA(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===lt(r)?n.data:le.parse(`${a}|${n.data}`)}o(hA,"readNormalizedSubjectId");function gA(e){let t=new Set;for(let r of lA){let n=uA.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(gA,"readRoles");function gn(e,t){let r=mA(e?.data),n={subjectId:hA(e,r,t),tenantId:pA},a=gA(r);return a&&(n.roles=a),n}o(gn,"parseGatewayPrincipal");function Yh(e){let t=Id(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Yh,"requireGatewayPrincipal");function Xh(e,t){Jh.set(e,t)}o(Xh,"setGatewayPrincipal");function Id(e){return Jh.get(e)}o(Id,"readGatewayPrincipal");function _n(e){let r=['realm="OAuth"',`resource_metadata="${Rd(Kh(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${Rd(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${Rd(e.scope)}"`),`Bearer ${r.join(", ")}`}o(_n,"buildGatewayBearerChallenge");function Rd(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(Rd,"sanitizeQuotedHeaderParameter");var _A=2,Qh=4,yA=24,wA=16,eg=512,SA=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,vA=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,bA=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,RA=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,IA=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,TA=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function tg(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(tg,"readRoute");function CA(e){let t=tg(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(CA,"readRoutePath");function EA(e){let t=tg(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(EA,"readRouteOperationId");function AA(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(AA,"deriveStatusClass");function PA(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="tenant_shared"?"tenant_shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(PA,"deriveOriginAttributionMode");function xA(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(xA,"deriveClientKind");function kA(e,t){return t==="success"?"none":e===L.MCP_GATEWAY_REQUEST_RECEIVED||e===L.MCP_GATEWAY_REQUEST_REJECTED||e===L.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===L.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===L.MCP_GATEWAY_POLICY_DECISION?"policy":e===L.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===L.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===L.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o(kA,"deriveFailureStage");function OA(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===L.MCP_GATEWAY_POLICY_DECISION||e===L.MCP_GATEWAY_GUARDRAIL_DECISION||e===L.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===L.MCP_GATEWAY_CAPABILITY_FAILED||e===L.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===L.MCP_GATEWAY_REQUEST_REJECTED||e===L.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(OA,"deriveFailureOrigin");function UA(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===L.MCP_GATEWAY_POLICY_DECISION?"policy":e===L.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===L.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===L.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===L.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o(UA,"deriveReasonClass");function NA(e){return e.length<=eg?e:`${e.slice(0,eg)}...`}o(NA,"truncateAnalyticsString");function $A(e){return NA(e.replace(vA,"$1[REDACTED]$3").replace(RA,"$1$2[REDACTED]").replace(bA,"$1$2[REDACTED]").replace(IA,"Bearer [REDACTED]").replace(TA,"Basic [REDACTED]"))}o($A,"redactAnalyticsString");function rg(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return $A(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=Qh?"[DEPTH_LIMIT]":e.slice(0,wA).map(r=>rg(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=Qh?"[DEPTH_LIMIT]":ng(e,t+1)}}o(rg,"sanitizeAnalyticsValue");function ng(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,yA)){if(SA.test(n)){r[n]="[REDACTED]";continue}let s=rg(a,t);s!==void 0&&(r[n]=s)}return Object.keys(r).length===0?void 0:r}o(ng,"sanitizeMcpGatewayAnalyticsAttributes");function O(e){return e===void 0?null:e}o(O,"nullable");function zA(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(zA,"readEnvironment");function MA(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(MA,"readRequestId");function DA(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(DA,"attributesToJsonString");function qA(e,t){let r=Id(e),n=Ro(e),a=ng(t.attributes),s=MA(e),i=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??xA(t.clientName)??null,_=PA(i??void 0,c??void 0)??null,w=AA(t.httpStatusCode)??null,y=t.reasonClass??UA(t.eventType,t.outcome),S=t.failureOrigin??OA(t.eventType,t.outcome),v=t.failureStage??kA(t.eventType,t.outcome);return{schemaVersion:_A,outcome:t.outcome,tenantId:O(r?.tenantId),subjectId:O(r?.subjectId),environment:zA(e),traceId:t.traceId??s,spanId:O(t.spanId),parentEventId:O(t.parentEventId),mcpSessionId:O(t.mcpSessionId),routeSurface:O(t.routeSurface),routePath:CA(e)??null,operationId:EA(e)??null,virtualServerName:d,virtualServerTitle:O(t.virtualServerTitle),upstreamServerName:p,upstreamServerTitle:l,upstreamBindingId:O(t.upstreamBindingId),clientName:O(t.clientName),clientTitle:O(t.clientTitle),clientVersion:O(t.clientVersion),clientKind:h,authProfileId:m,upstreamAuthMode:c,ownerMode:i,authMethod:O(t.authMethod),originAttributionMode:_,httpMethod:O(t.httpMethod),httpStatusCode:O(t.httpStatusCode),statusClass:w,mcpMethod:O(t.mcpMethod),mcpProtocolVersion:O(t.mcpProtocolVersion),mcpStatus:O(t.mcpStatus),mcpErrorType:O(t.mcpErrorType),applicationError:O(t.applicationError),applicationErrorCode:O(t.applicationErrorCode),toolResultIsError:O(t.toolResultIsError),capabilityType:O(t.capabilityType),capabilityName:O(t.capabilityName),capabilityTitle:O(t.capabilityTitle),upstreamCapabilityName:O(t.upstreamCapabilityName),upstreamCapabilityTitle:O(t.upstreamCapabilityTitle),capabilitySchemaHash:O(t.capabilitySchemaHash),policyId:O(t.policyId),policyAction:O(t.policyAction),guardrailType:O(t.guardrailType),guardrailDirection:O(t.guardrailDirection),guardrailFindingCount:O(t.guardrailFindingCount),redactionCount:O(t.redactionCount),requestMutated:O(t.requestMutated),responseMutated:O(t.responseMutated),latencyMs:O(t.latencyMs),gatewayLatencyMs:O(t.gatewayLatencyMs),upstreamLatencyMs:O(t.upstreamLatencyMs),authLatencyMs:O(t.authLatencyMs),policyLatencyMs:O(t.policyLatencyMs),requestBytes:O(t.requestBytes),responseBytes:O(t.responseBytes),estimatedInputTokens:O(t.estimatedInputTokens),estimatedOutputTokens:O(t.estimatedOutputTokens),estimatedContextTokens:O(t.estimatedContextTokens),contextPressureBucket:O(t.contextPressureBucket),responseMimeTypes:O(t.responseMimeTypes),base64Suspected:O(t.base64Suspected),truncated:O(t.truncated),isLargePayloadRequest:O(t.isLargePayloadRequest),isLargePayloadResponse:O(t.isLargePayloadResponse),payloadCaptureMode:O(t.payloadCaptureMode),reasonCode:O(t.reasonCode),reasonClass:y,errorType:t.errorType??t.reasonCode??null,failureOrigin:S,failureStage:v,customMetadataJson:O(t.customMetadataJson),attributesJson:DA(a)}}o(qA,"buildMcpGatewayAnalyticsMetadata");function He(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,qA(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(He,"emitMcpGatewayAnalyticsEvent");function Ge(e){let t=tt().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(Ge,"getUpstreamServerConfig");function LA(e){let t=tt().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(LA,"resolveUpstreamAuthProfileId");function ir(e){LA(e);let t=tt().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 xr(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(!mh(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(xr,"requireUpstreamOAuthConfig");var jA={tenant_shared_oauth:{authMode:"tenant_shared_oauth",ownerMode:"tenant_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"},tenant_static_secret:{authMode:"tenant_static_secret",ownerMode:"tenant_shared",connectSupport:"none",connectUnsupportedDetail:"Tenant static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"tenant_static_secret_connection"},user_static_secret:{authMode:"user_static_secret",ownerMode:"user",connectSupport:"user_static_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_static_secret_connection"}};function vt(e){return jA[e]}o(vt,"describeUpstreamAuthMode");function Td(e){return vt(e).ownerMode}o(Td,"resolveOwnerModeForUpstreamAuthMode");W();var Cd=u.string().trim().min(1),HA=u.object({TOKEN_ENCRYPTION_KEY:Cd,OAUTH_STATE_SIGNING_KEY:Cd,TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING:Cd.optional()}),GA=["TOKEN_ENCRYPTION_KEY","OAUTH_STATE_SIGNING_KEY","TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING"];function BA(e){let t=Si[e];return typeof t=="string"?t:void 0}o(BA,"readEnvValue");function VA(){let e={};for(let t of GA){let r=BA(t);r!==void 0&&(e[t]=r)}return e}o(VA,"readRawEnv");var Ed;function FA(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.map(String).join("."):"environment"}: ${t.message}`)}o(FA,"formatZodIssues");function ZA(e){return new Tt(["Invalid MCP gateway environment configuration.","Validation failed for these environment variables:",...FA(e)].join(`
44
- `),{cause:e})}o(ZA,"createEnvValidationError");function KA(e){let t=HA.safeParse(e);if(!t.success)throw ZA(t.error);return t.data}o(KA,"parseGatewayEnv");function WA(){return Ed||(Ed=KA(VA())),Ed}o(WA,"readEnv");function Is(){return WA()}o(Is,"getEnv");W();W();function JA(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(JA,"parseDate");function cr(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(cr,"parseJsonValue");function Ad(e,t){return u.array(u.string()).parse(cr(e,t))}o(Ad,"parseStringArray");var ie=u.union([u.date(),u.string()]).transform(e=>JA(e));var YA=u.object({current_state_hash:u.string(),phase:_d,consumed_at:ie.nullable(),expires_at:ie}),XA=u.object({id:$t,revoked_at:ie.nullable().optional(),expires_at:ie,matched:u.enum(["current","previous"])}),QA=u.object({id:$t,matched:u.literal("current")}),eP=u.object({client_id:Ze,client_name:u.string(),redirect_uris:u.unknown(),token_endpoint_auth_method:Co,hashed_client_secret:u.string().nullable(),client_secret_expires_at:ie.nullable(),client_expires_at:ie,revoked_at:ie.nullable(),created_at:ie}).transform(e=>{let t={clientId:e.client_id,clientName:e.client_name,redirectUris:Ad(e.redirect_uris,"redirect_uris"),tokenEndpointAuthMethod:e.token_endpoint_auth_method,createdAt:K(e.created_at),clientExpiresAt:K(e.client_expires_at)};return e.hashed_client_secret&&(t.hashedClientSecret=e.hashed_client_secret),e.client_secret_expires_at&&(t.clientSecretExpiresAt=K(e.client_secret_expires_at)),e.revoked_at&&(t.revokedAt=K(e.revoked_at)),Lh.parse(t)}),Pd=u.object({id:sr,current_state_hash:u.string(),phase:_d,principal_subject_id:le.nullable(),principal_tenant_id:$e.nullable(),principal_roles:u.unknown().nullable(),client_id:Ze,redirect_uri:u.string(),resource:u.string(),virtual_server_id:ge,client_state:u.string().nullable(),scope:u.string(),code_challenge:u.string(),code_challenge_method:hn,created_at:ie,expires_at:ie,consumed_at:ie.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:K(e.created_at),expiresAt:K(e.expires_at)};if(e.client_state&&(t.clientState=e.client_state),e.consumed_at&&(t.consumedAt=K(e.consumed_at)),e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal_subject_id||!e.principal_tenant_id)throw new Error("Awaiting-setup pending authorization row is missing principal.");return{...t,phase:"awaiting_setup",principal:{subjectId:e.principal_subject_id,tenantId:e.principal_tenant_id,...e.principal_roles===null?{}:{roles:u.array(u.string()).parse(cr(e.principal_roles,"principal_roles"))}}}}),tP=u.object({id:sr});function ag(e){return{clientId:e.client_id,resource:e.resource,virtualServerId:e.virtual_server_id,tenantId:e.tenant_id,subjectId:e.subject_id,scope:e.scope,roles:Ad(e.roles,"roles"),createdAt:K(e.created_at),expiresAt:K(e.expires_at)}}o(ag,"downstreamGrantAccessFields");var og=u.object({id:$t,client_id:Ze,resource:u.string(),virtual_server_id:ge,tenant_id:$e,subject_id:le,scope:u.string(),roles:u.unknown(),current_refresh_token_hash:u.string().nullable(),previous_refresh_token_hash:u.string().nullable(),created_at:ie,expires_at:ie,revoked_at:ie.nullable(),revoked_reason:u.string().nullable()}).transform(e=>{let t={id:e.id,...ag(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=K(e.revoked_at)),e.revoked_reason&&(t.revokedReason=e.revoked_reason),Hh.parse(t)}),rP=u.object({token_hash:u.string(),grant_id:$t,client_id:Ze,resource:u.string(),virtual_server_id:ge,tenant_id:$e,subject_id:le,scope:u.string(),roles:u.unknown(),created_at:ie,expires_at:ie,revoked_at:ie.nullable()}).transform(e=>{let t={tokenHash:e.token_hash,grantId:e.grant_id,...ag(e)};return e.revoked_at&&(t.revokedAt=K(e.revoked_at)),Gh.parse(t)});function sg(e){return[e.clientId,e.redirectUri,e.resource,e.virtualServerId,e.tenantId,e.subjectId,e.scope,JSON.stringify(e.roles),e.codeChallenge,e.codeChallengeMethod,new Date(e.createdAt),new Date(e.expiresAt)]}o(sg,"authorizationTransactionValues");function nP(e,t){let r=jh.parse(t);return e.query(`INSERT INTO downstream_oauth_authorization_transactions (
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=>wr.parse(v)):u=[wr.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(Bs);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(wt)){for(let v of u)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let p=crypto.randomUUID(),m=u.find(v=>Bs(v)),f=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??kp;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(p,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(p)},"cleanup")});for(let R of u)wt(R)&&this._requestToStreamMapping.set(R.id,p);for(let R of u)this.onmessage?.(R,{authInfo:r?.authInfo,requestInfo:i})});let _=new TextEncoder,S,y=new ReadableStream({start:o(v=>{S=v},"start"),cancel:o(()=>{this._streamMapping.delete(p)},"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 u)wt(v)&&(this._streamMapping.set(p,{controller:S,encoder:_,cleanup:o(()=>{this._streamMapping.delete(p);try{S.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,p));await this.writePrimingEvent(S,_,p,f);for(let v of u){let R,C;wt(v)&&this._eventStore&&f>="2025-11-25"&&(R=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),C=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:R,closeStandaloneSSEStream:C})}return new Response(y,{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&&!Qt.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Qt.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Qt.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((dt(t)||Xr(t))&&(n=t.id),n===void 0){if(dt(t)||Xr(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(dt(t)||Xr(t)){this._requestResponseMap.set(n,t);let s=Array.from(this._requestToStreamMapping.entries()).filter(([d,l])=>l===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 l=s.map(p=>this._requestResponseMap.get(p));l.length===1?i.resolveJson(new Response(JSON.stringify(l[0]),{status:200,headers:d})):i.resolveJson(new Response(JSON.stringify(l),{status:200,headers:d}))}else i.cleanup();for(let d of s)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function ld(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(ld,"truncate");function Of(e){return"cause"in e?e.cause:void 0}o(Of,"readCause");function ke(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=ld(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=ld(r.message);let n=Of(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`]=ld(n.message),n=Of(n)}}o(ke,"addErrorLogFields");function st(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(st,"safeHost");function Uf(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(Uf,"setLogProperties");function pd(e,t){Uf(e,{tenantId:t.tenantId,subjectId:t.subjectId})}o(pd,"applyGatewayPrincipalLogProperties");function zf(e,t){Uf(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(zf,"applyGatewayRouteLogProperties");var wn={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."}}},Nf={...wn.runtime,...wn.config,...wn.downstream_auth,...wn.downstream_oauth,...wn.upstream_auth,...wn.upstream_mcp};function zo(e){return typeof e=="string"&&Object.hasOwn(Nf,e)}o(zo,"isGatewayProblemCode");function vi(e){return zo(e)&&Fe(e).callbackFailure===!0}o(vi,"isGatewayCallbackFailureCode");function Fe(e){return Nf[e]}o(Fe,"readGatewayProblemDefinition");function md(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(md,"readDefaultGatewayProblemCodeForStatus");var Df="gatewayCode";function Mf(e){let t=Fe(e);return{title:t.title,body:t.publicDetail}}o(Mf,"readGatewayCallbackFailureContent");function le(e){if(!(e instanceof ya))return;let t=e.extensionMembers?.[Df];return zo(t)?t:void 0}o(le,"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=Fe(n.code),i=n.privateDetail??(Ri(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=pk(n);return new ya({message:i,extensionMembers:{[Df]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function Ze(e,t,r){let n=Fe(r.code),a=mk(r.code,r.detail),i=Ri(r.code)?r.title??n.title:n.title,u={problem:{...Vn.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),Vn.format(u,e,t)}o(Ze,"gatewayProblemResponse");function Ri(e){return Fe(e).status<500}o(Ri,"canExposeGatewayProblemDetail");function pk(e){return!e.privateDetail||Ri(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(pk,"readRuntimeErrorCause");function mk(e,t){let r=Fe(e);return Ri(e)&&t||r.publicDetail}o(mk,"readSafeGatewayProblemDetail");X();var hk=["tenant_shared_oauth","user_oauth","static_secret","user_static_secret","tenant_static_secret"],fk=["none","client_secret_basic","client_secret_post"],Ee=c.string().min(1).brand(),me=c.string().min(1).brand(),Pe=c.string().min(1).brand(),At=c.string().min(1).brand(),bi=c.enum(hk),hd=c.enum(fk),Ii=c.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),fd=c.object({name:Ii,value:c.string().min(1).optional(),required:c.boolean().default(!0)}).strict();var gd=new Map;function Ci(e){gd.set(e.policyType,e)}o(Ci,"registerMcpAuthorizationPolicy");function _d(e){if(e!==void 0)return gd.get(e)}o(_d,"getMcpAuthorizationPolicy");function Ti(e){return _d(e)!==void 0}o(Ti,"isRegisteredMcpAuthorizationPolicyType");function yd(){return[...gd.keys()]}o(yd,"listMcpAuthorizationPolicyTypes");X();var Lf=Ee,gk=c.object({mode:c.literal("auto")}).strict(),_k=c.object({mode:c.literal("manual"),clientId:c.string().trim().min(1),clientSecret:c.string().min(1).optional(),tokenEndpointAuthMethod:hd.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"]})}),jf=c.discriminatedUnion("mode",[gk,_k]),yk=jf.default({mode:"auto"}),Sd=c.object({scopes:c.array(c.string().min(1)).default([]),scopeDelimiter:c.string().min(1).default(" "),clientRegistration:yk}).strict(),qf=Sd.extend({redirectPath:c.string().startsWith("/auth/connections/")}).strict(),Hf=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),Sk=new Set([...Hf,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),wk=c.object({kind:c.literal("bearer_token"),token:c.string().min(1)}).strict(),vk=c.object({kind:c.literal("headers"),headers:c.array(c.object({name:Ii,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();Hf.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)}}),wd=c.discriminatedUnion("kind",[wk,vk]),Rk=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(),bk=c.object({kind:c.literal("bearer_token"),label:c.string().min(1).default("API key"),capture:c.enum(["browser_login"]).optional()}).strict(),vd=c.discriminatedUnion("kind",[Rk,bk]),Rd=c.object({kind:c.literal("bearer_token"),label:c.string().min(1).default("API key")}).strict(),Ik=c.discriminatedUnion("mode",[c.object({mode:c.literal("tenant_shared_oauth"),oauth:qf}).strict(),c.object({mode:c.literal("user_oauth"),oauth:qf}).strict(),c.object({mode:c.literal("static_secret"),secret:wd}).strict(),c.object({mode:c.literal("user_static_secret"),secret:vd}).strict(),c.object({mode:c.literal("tenant_static_secret"),secret:Rd}).strict()]),Ck=c.object({baseUrl:c.url(),resourceMetadataUrl:c.url(),requestHeaders:c.array(fd).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();Sk.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)}}),QG=c.object({displayName:c.string().min(1),description:c.string().min(1).optional(),serverInfo:Qr.optional(),authProfiles:c.record(Pe,Ik),transport:Ck}).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"]})}),Tk=c.object({tenant_shared_oauth:Sd.optional(),user_oauth:Sd.optional(),static_secret:c.object({secret:wd}).strict().optional(),user_static_secret:c.object({secret:vd}).strict().optional(),tenant_static_secret:c.object({secret:Rd}).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"})}),$f=c.object({id:Lf,displayName:c.string().min(1),description:c.string().min(1).optional(),serverInfo:Qr.optional(),mcpUrl:c.url(),protectedResourceMetadataUrl:c.url(),requestHeaders:c.array(fd).default([]),authProfiles:Tk}).strict(),Ak=c.object({name:Ii,value:c.string().min(1).optional(),required:c.boolean().default(!0)}).strict(),Ai={id:Lf.optional(),displayName:c.string().min(1),summary:c.string().min(1).optional(),serverInfo:Qr.optional(),mcpUrl:c.url(),protectedResourceMetadataUrl:c.url().optional(),requestHeaders:c.array(Ak).default([])},kk=c.discriminatedUnion("authMode",[c.object({...Ai,authMode:c.enum(["tenant_shared_oauth","user_oauth"]),scopes:c.array(c.string().min(1)).default([]),scopeDelimiter:c.string().min(1).default(" "),clientRegistration:jf.optional(),clientId:c.string().trim().min(1).optional(),clientSecret:c.string().min(1).optional(),tokenEndpointAuthMethod:hd.optional()}).strict(),c.object({...Ai,authMode:c.literal("static_secret"),secret:wd}).strict(),c.object({...Ai,authMode:c.literal("user_static_secret"),secret:vd}).strict(),c.object({...Ai,authMode:c.literal("tenant_static_secret"),secret:Rd}).strict()]);function Gf(e){throw g("internal_server_error",e)}o(Gf,"throwGatewayConfigError");function Ek(e){let t="mcp-upstream-";return e.startsWith(t)||Gf(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),Ee.parse(e.slice(t.length))}o(Ek,"inferUpstreamConnectionIdFromPolicyName");function Pk(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(Pk,"buildDefaultProtectedResourceMetadataUrl");function vn(e,t){return Pe.parse(`${e}:${t}`)}o(vn,"buildUpstreamAuthProfileId");function ki(e,t){let r=$f.safeParse(e);if(r.success)return r.data;let n=kk.parse(e),a=n.id??(t===void 0?void 0:Ek(t));a===void 0&&Gf("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"tenant_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_static_secret":case"tenant_static_secret":return{[n.authMode]:{secret:n.secret}}}})();return $f.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??Pk(n.mcpUrl),requestHeaders:i,authProfiles:s})}o(ki,"parseUpstreamConnectionPolicyOptions");function Bf(e){return e.mode==="tenant_shared_oauth"||e.mode==="user_oauth"}o(Bf,"isUpstreamOAuthAuthConfig");X();var xk=c.looseObject({name:c.string().min(1),version:c.string().min(1).optional()}),Ok=c.looseObject({}),Uk=c.looseObject({name:At,namespace:At.optional(),upstreamPolicy:c.string().min(1).optional(),enabled:c.boolean().optional(),inputSchema:Ok}),zk=c.looseObject({name:At,namespace:At.optional(),upstreamPolicy:c.string().min(1).optional(),enabled:c.boolean().optional()}),Nk=c.looseObject({name:At,uri:c.string().min(1),upstreamPolicy:c.string().min(1).optional(),upstreamUri:c.string().min(1).optional(),enabled:c.boolean().optional()}),Dk=c.enum(["openapi","upstream_mcp"]),Mk=c.object({catalogSource:Dk.default("openapi"),serverInfo:xk.optional(),tools:c.array(Uk).default([]),prompts:c.array(zk).default([]),resources:c.array(Nk).default([])}).strict();function Vf(e){return Mk.parse(e??{})}o(Vf,"parseVirtualServerRouteOptions");function Ei(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ei,"toMcpTool");function Pi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Pi,"toMcpPrompt");function xi(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(xi,"toMcpResource");var qk="mcp-upstream-connection-inbound",Ff="/mcp/";function De(e){throw new et(e)}o(De,"throwRegistryError");function Zf(e){return e.policyType===qk}o(Zf,"isUpstreamConnectionPolicy");function $k(e){return Ti(e.policyType)}o($k,"isMcpOAuthInboundPolicy");function Lk(e){e.startsWith(Ff)||De(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(Ff.length);return(!t||t.includes("/"))&&De(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),me.parse(t)}o(Lk,"readVirtualServerIdFromPath");function jk(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&De(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&De(`Upstream policy ${e.policyName} does not declare an auth mode.`),bi.parse(r)}o(jk,"readSingleAuthMode");function Hk(e){let t=e.connection.authProfiles[e.authMode];t||De(`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"tenant_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_static_secret":return{mode:"user_static_secret",secret:t.secret};case"tenant_static_secret":return{mode:"tenant_static_secret",secret:t.secret}}}o(Hk,"buildResolvedAuthConfig");function Gk(e){let t=jk({policyName:e.policyName,connection:e.connection}),r=vn(e.connection.id,t),n=Hk({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(Gk,"buildRegisteredConnection");function Bk(e){let t=new Map;for(let r of e)t.has(r.name)&&De(`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(Bk,"buildPolicyMap");function Vk(e){let t=new Map,r=new Set;for(let n of e.values()){if(!Zf(n))continue;let a=ki(n.handler.options,n.name);r.has(a.id)&&De(`Duplicate upstream MCP connection id ${a.id} in policies.json.`),r.add(a.id);let i=Gk({policyName:n.name,connection:a});t.set(n.name,i)}return t}o(Vk,"buildConnectionsByPolicyName");function Fk(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(Fk,"readOperationId");function Kf(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return At.parse(t)}catch{De(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(Kf,"buildPublishedCapabilityName");function Id(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||De(`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;De(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Id,"readCapabilityUpstreamPolicy");function bd(e){e.seen.has(e.key)&&De(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(bd,"assertUniqueCatalogKey");function Zk(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=Kf({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Id({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(Zk,"normalizeCatalogTool");function Kk(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=Kf({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Id({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(Kk,"normalizeCatalogPrompt");function Wk(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Id({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(Wk,"normalizeCatalogResource");function Jk(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>Zk({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>Kk({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>Wk({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)bd({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)bd({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let u=new Set;for(let d of a)bd({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(Jk,"normalizeVirtualServerCatalog");function Yk(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||!$k(s))continue;let u=Fk(n);u||De(`MCP virtual server route ${n.path} must declare an operationId in routes.oas.json.`),r.has(u)&&De(`Duplicate MCP virtual server operationId ${u} across routes.`),r.add(u);let d=Lk(n.path);t.has(d)&&De(`Duplicate MCP virtual server id ${d} across routes.`);let l=[];for(let f of a.slice(1)){let _=e.policyByName.get(f);if(!_||!Zf(_))continue;let S=e.connectionsByPolicyName.get(f);S||De(`Upstream connection policy ${f} referenced by route ${n.path} could not be resolved.`),l.push(S)}let p=Vf(n.handler.options),m=Jk({catalog:p,connections:l,routePath:n.path});m.catalogSource==="upstream_mcp"&&l.length!==1&&De(`MCP virtual server route ${n.path} uses upstream MCP catalog mode but declares ${l.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:l})}return t}o(Yk,"buildVirtualServers");function Wf(e){let t=Bk(e.policies),r=Vk(t),n=Yk({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(Wf,"buildGatewayConnectionRegistry");var Oi;function Jf(e){Oi=e}o(Jf,"setGatewayConnectionRegistry");function ct(){if(!Oi)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 Oi}o(ct,"getGatewayConnectionRegistry");function Yf(e){let t=ct().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return t}o(Yf,"getRegisteredVirtualServer");function No(e){let t=ct().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(No,"requireRegisteredVirtualServer");function Xf(){return Oi}o(Xf,"tryGetGatewayConnectionRegistry");var Qf=new Ut("gateway-route");function eg(e,t){Qf.set(e,t)}o(eg,"setGatewayRouteContext");function Do(e){return Qf.get(e)}o(Do,"readGatewayRouteContext");function Rn(e){let t=Do(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(Rn,"requireGatewayRouteContext");var Or="2025-06-18";var Xk=new Set(["localhost","::1"]);function ut(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(ut,"normalizeHostname");function Le(e){let t=ut(e.hostname);return e.protocol==="http:"&&(Xk.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(Le,"isLoopbackHttpUrl");function ne(e){return new URL(e).origin}o(ne,"readGatewayRequestOrigin");import{metrics as Qk,context as Ui,propagation as rg,SpanKind as ng,SpanStatusCode as Cd,trace as Mo}from"@opentelemetry/api";var eE="mcp-gateway",tE="mcp-gateway",rE=Or,nE="2.0",og=Mo.getTracer(eE),Td=Qk.getMeter(tE),oE=Td.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),aE=Td.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),iE=Td.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),sE=["traceparent","tracestate","baggage"];function Ad(){return performance.now()/1e3}o(Ad,"nowSeconds");function ag(e,t){t(Math.max(Ad()-e,0))}o(ag,"recordDurationSeconds");function tg(e){return e===void 0?void 0:String(e)}o(tg,"stringifyAttribute");function xe(e,t,r){r!==void 0&&(e[t]=r)}o(xe,"assignAttribute");function cE(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(cE,"readTargetName");function ig(e){let t=cE({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(ig,"buildMcpOperationSpanName");function kd(e){let t={"mcp.method.name":e.methodName};return xe(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??nE),xe(t,"jsonrpc.request.id",tg(e.jsonRpcRequestId)),xe(t,"mcp.protocol.version",e.mcpProtocolVersion??rE),xe(t,"mcp.session.id",e.mcpSessionId),xe(t,"mcp.resource.uri",e.resourceUri),xe(t,"rpc.response.status_code",tg(e.rpcResponseStatusCode)),xe(t,"error.type",e.errorType),e.capabilityType==="tool"&&(xe(t,"gen_ai.operation.name","execute_tool"),xe(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&xe(t,"gen_ai.prompt.name",e.capabilityName),xe(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),xe(t,"network.protocol.version",e.networkProtocolVersion),xe(t,"network.transport",e.networkTransport),xe(t,"server.address",e.serverAddress),xe(t,"server.port",e.serverPort),xe(t,"client.address",e.clientAddress),xe(t,"client.port",e.clientPort),t}o(kd,"buildMcpOperationAttributes");function uE(e){let t=kd({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(uE,"buildMcpSessionAttributes");function sg(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:Cd.ERROR}),t instanceof Error&&e.recordException(t)}o(sg,"setSpanError");function cg(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(cg,"readErrorType");function dE(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Ui.active():rg.extract(Ui.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(dE,"readServerParentContext");function lE(e){let t=Mo.getSpanContext(Ui.active()),r=Mo.getSpanContext(e);if(!(!t||!Mo.isSpanContextValid(t))&&!(r&&Mo.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(lE,"readAmbientSpanLink");function ug(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(ug,"readResultErrorType");async function Ur(e,t){let r=Ad(),n=kd({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return og.startActiveSpan(ig(e),{kind:ng.CLIENT,attributes:n},async a=>{try{let i=await t(),s=ug(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:Cd.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??cg(i);throw n["error.type"]=s,sg(a,i,s),i}finally{ag(r,i=>{oE.record(i,n)}),a.end()}})}o(Ur,"runMcpClientOperation");async function zr(e,t){let r=Ad(),n=dE(e.params),a=kd({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=lE(n);return og.startActiveSpan(ig(e),{kind:ng.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let u=await t(),d=ug(u);return d&&(s.setAttribute("error.type",d),s.setStatus({code:Cd.ERROR}),a["error.type"]=d),u}catch(u){let d=e.errorType??cg(u);throw a["error.type"]=d,sg(s,u,d),u}finally{ag(r,u=>{aE.record(u,a)}),s.end()}})}o(zr,"runMcpServerOperation");function dg(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return rg.inject(Ui.active(),t._meta,{set(r,n,a){sE.includes(n)&&(r[n]=a)}}),t}o(dg,"injectMcpTraceContextIntoParams");function lg(e,t){let r=uE({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});iE.record(Math.max(t,0),r)}o(lg,"recordMcpClientSessionDuration");var Ed=new Ut("route-upstream-bindings");function pE(e){let t=Ed.get(e);if(t)return t;let r={bindings:[]};return Ed.set(e,r),r}o(pE,"readOrCreateRouteUpstreamBindingRegistry");function pg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(pg,"buildRouteBindingDuplicateKey");function Pd(e,t){let r=pE(e),n=pg(t);if(r.bindings.find(i=>pg(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.bindings.push(t)}o(Pd,"appendResolvedUpstreamBindingContext");function mg(e){return Ed.get(e)?.bindings??[]}o(mg,"readResolvedUpstreamBindingContexts");X();var V=c.string().datetime({offset:!0}).brand();function O(e){return V.parse(e.toISOString())}o(O,"toIsoTimestamp");function gt(e,t){return new Date(e.getTime()+t*1e3)}o(gt,"addSeconds");X();var bn=c.string().trim().min(1),qo={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},mE=c.object({issuer:c.url(),jwksUrl:c.url(),audience:bn}),hE=c.object({url:c.url(),tokenUrl:c.url().optional(),clientId:bn.optional(),clientSecret:bn.optional(),scope:bn.default("openid profile email"),audience:bn.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(),fE=c.object({accessTokenTtlSeconds:c.coerce.number().int().positive().default(qo.accessTokenTtlSeconds),refreshTokenTtlSeconds:c.coerce.number().int().positive().default(qo.refreshTokenTtlSeconds),cimdEnabled:c.boolean().default(qo.cimdEnabled)}).strict().default(qo),gE=c.object({oidc:mE,browserLogin:hE,gateway:fE.optional().default(qo),devTenantId:bn.optional()}).strict();function hg(e){return _E(e.browserLogin.url)?"local_dev":"federated_oidc"}o(hg,"readBrowserLoginKind");function _E(e){let t;try{t=new URL(e)}catch{return!1}return Le(t)&&t.pathname==="/oauth/dev-login"}o(_E,"isLoopbackDevLoginUrl");function zi(e){return gE.parse(e)}o(zi,"parseMcpOAuthRuntimeConfig");var xd;function fg(e){xd=e}o(fg,"setGatewayOAuthConfig");function Re(){if(!xd)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 xd}o(Re,"getGatewayOAuthConfig");function _t(e){return ne(e)}o(_t,"readGatewayOAuthIssuer");X();var yE=43,SE=128,wE=/^[A-Za-z0-9._~-]+$/,Od="S256",In=c.literal(Od),Ni=c.string().min(yE).max(SE).regex(wE);X();var Di=["none","client_secret_post","client_secret_basic"],vE=[...Di,"private_key_jwt"],RE=["awaiting_login","awaiting_setup"],bE=c.string().min(1).brand(),IE=c.string().min(1).brand(),he=c.string().min(1).brand(),yt=c.uuid().brand(),je=c.uuid().brand(),Mi=c.uuid().brand(),$o=c.enum(Di),CE=c.enum(vE),Ud=c.enum(RE),gg=c.object({client_id:he,client_name:c.string().min(1),redirect_uris:c.array(c.string().min(1)).min(1),token_endpoint_auth_method:CE.default("none")}),qi=c.object({clientId:he,clientName:c.string().min(1),redirectUris:c.array(c.string().min(1)),tokenEndpointAuthMethod:$o,hashedClientSecret:c.string().optional(),clientSecretExpiresAt:V.optional(),clientExpiresAt:V,revokedAt:V.optional(),createdAt:V}),zd=c.object({clientId:he,resource:c.string(),virtualServerId:me,tenantId:bE,subjectId:IE,scope:c.string(),roles:c.array(c.string()),createdAt:V,expiresAt:V}),_g=zd.extend({id:je,redirectUri:c.string(),clientState:c.string().optional(),codeChallenge:c.string(),codeChallengeMethod:In}),Lo=zd.extend({id:yt,currentRefreshTokenHash:c.string().optional(),previousRefreshTokenHash:c.string().optional(),revokedAt:V.optional(),revokedReason:c.string().optional()}),Cn=zd.extend({tokenHash:c.string(),grantId:yt,revokedAt:V.optional()});function Nd(){return je.parse(crypto.randomUUID())}o(Nd,"createDownstreamAuthorizationTransactionId");function Dd(){return Mi.parse(crypto.randomUUID())}o(Dd,"createDownstreamBrowserLoginStateId");function Md(){return yt.parse(crypto.randomUUID())}o(Md,"createDownstreamGrantId");var ue="mcp:tools";function Li(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return Le(r)&&Le(n)&&ut(r.hostname)===ut(n.hostname)&&r.pathname===n.pathname&&r.search===n.search}o(Li,"redirectUriMatchesRegistration");function yg(e){return Le(e)&&e.pathname==="/oauth/dev-login"}o(yg,"isLoopbackDevLoginUrl");function $i(e,t){return new URL(e,_t(t)).toString()}o($i,"buildGatewayOAuthUrl");function qd(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ne(e.requestUrl)).toString()}o(qd,"buildScopedAuthorizationServerIssuer");function TE(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ne(e.requestUrl)).toString()}o(TE,"buildScopedAuthorizationEndpoint");function $d(e){let t=Re();return{issuer:_t(e),authorization_endpoint:$i("/oauth/authorize",e),token_endpoint:$i("/oauth/token",e),registration_endpoint:$i("/oauth/register",e),revocation_endpoint:$i("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ue],code_challenge_methods_supported:[Od],token_endpoint_auth_methods_supported:Di,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":hg(t)}}o($d,"buildAuthorizationServerMetadata");function Sg(e){let t=qd(e);return{...$d(e.requestUrl),issuer:t,authorization_endpoint:TE(e)}}o(Sg,"buildScopedAuthorizationServerMetadata");async function wg(e,t){try{let r=me.parse(e.params.virtualServerId),n=No(r);return Response.json(AE(n.virtualServerId,e.url))}catch(r){let n=le(r);return Ze(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(wg,"protectedResourceMetadataHandler");function AE(e,t){return{resource:Nr(e,t),resource_name:e,authorization_servers:[qd({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ue],mcp_protocol_version:Or}}o(AE,"buildProtectedResourceMetadataResponseBody");function Nr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ne(t)).toString()}o(Nr,"buildCanonicalMcpResourceForVirtualServer");function vg(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ne(t)).toString()}o(vg,"buildProtectedResourceMetadataUrlForVirtualServer");import{base64url as Ld}from"jose";var kE="sha256:",EE=32;function Rg(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Rg,"copyToArrayBuffer");function PE(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(PE,"constantTimeEqual");function Ke(){let e=crypto.getRandomValues(new Uint8Array(EE));return Ld.encode(e)}o(Ke,"createOpaqueToken");async function F(e){let t=await crypto.subtle.digest("SHA-256",Rg(new TextEncoder().encode(e)));return`${kE}${Ld.encode(new Uint8Array(t))}`}o(F,"hashOpaqueValue");async function bg(e){let t=await F(e.value);return PE(t,e.expectedHash)}o(bg,"verifyOpaqueValue");async function jd(e){let t=await crypto.subtle.digest("SHA-256",Rg(new TextEncoder().encode(e)));return Ld.encode(new Uint8Array(t))}o(jd,"calculatePkceS256Challenge");X();var xE=c.record(c.string(),c.unknown()),Ig=c.string().min(1),OE=c.union([Ig.transform(e=>[e]),c.array(Ig)]),de=c.string().min(1).brand(),Q=c.string().min(1).brand(),UE=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],zE=["https://zuplo.com/roles","roles","role","permissions","groups"],NE=de.parse("zuplo-poc"),Cg=new Ut("gateway-principal");function DE(e){let t=xE.safeParse(e);return t.success?t.data:{}}o(DE,"toClaimRecord");function ME(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(ME,"readValidationFailureDetail");function qE(e,t,r){for(let i of UE){let s=Q.safeParse(t[i]);if(s.success)return s.data}let n=Q.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",ME(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===_t(r)?n.data:Q.parse(`${a}|${n.data}`)}o(qE,"readNormalizedSubjectId");function $E(e){let t=new Set;for(let r of zE){let n=OE.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o($E,"readRoles");function Tn(e,t){let r=DE(e?.data),n={subjectId:qE(e,r,t),tenantId:NE},a=$E(r);return a&&(n.roles=a),n}o(Tn,"parseGatewayPrincipal");function Tg(e){let t=Gd(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Tg,"requireGatewayPrincipal");function Ag(e,t){Cg.set(e,t)}o(Ag,"setGatewayPrincipal");function Gd(e){return Cg.get(e)}o(Gd,"readGatewayPrincipal");function An(e){let r=['realm="OAuth"',`resource_metadata="${Hd(vg(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${Hd(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${Hd(e.scope)}"`),`Bearer ${r.join(", ")}`}o(An,"buildGatewayBearerChallenge");function Hd(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(Hd,"sanitizeQuotedHeaderParameter");X();var ji=c.string().trim().min(1),LE=c.object({TOKEN_ENCRYPTION_KEY:ji,OAUTH_STATE_SIGNING_KEY:ji,TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING:ji.optional(),MCP_GATEWAY_RUNTIME_STORAGE_CONFIGURATION_ID:ji.optional()}),jE=["TOKEN_ENCRYPTION_KEY","OAUTH_STATE_SIGNING_KEY","TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING","MCP_GATEWAY_RUNTIME_STORAGE_CONFIGURATION_ID"];function HE(e){let t=Fn[e];return typeof t=="string"?t:void 0}o(HE,"readEnvValue");function GE(){let e={};for(let t of jE){let r=HE(t);r!==void 0&&(e[t]=r)}return e}o(GE,"readRawEnv");var Bd;function BE(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.map(String).join("."):"environment"}: ${t.message}`)}o(BE,"formatZodIssues");function VE(e){return new et(["Invalid MCP gateway environment configuration.","Validation failed for these environment variables:",...BE(e)].join(`
44
+ `),{cause:e})}o(VE,"createEnvValidationError");function FE(e){let t=LE.safeParse(e);if(!t.success)throw VE(t.error);return t.data}o(FE,"parseGatewayEnv");function ZE(){return Bd||(Bd=FE(GE())),Bd}o(ZE,"readEnv");function jo(){return ZE()}o(jo,"getEnv");X();X();function KE(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(KE,"parseDate");function pr(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(pr,"parseJsonValue");function Vd(e,t){return c.array(c.string()).parse(pr(e,t))}o(Vd,"parseStringArray");var se=c.union([c.date(),c.string()]).transform(e=>KE(e));var WE=c.object({current_state_hash:c.string(),phase:Ud,consumed_at:se.nullable(),expires_at:se}),JE=c.object({id:yt,revoked_at:se.nullable().optional(),expires_at:se,matched:c.enum(["current","previous"])}),YE=c.object({id:yt,matched:c.literal("current")}),XE=c.object({client_id:he,client_name:c.string(),redirect_uris:c.unknown(),token_endpoint_auth_method:$o,hashed_client_secret:c.string().nullable(),client_secret_expires_at:se.nullable(),client_expires_at:se,revoked_at:se.nullable(),created_at:se}).transform(e=>{let t={clientId:e.client_id,clientName:e.client_name,redirectUris:Vd(e.redirect_uris,"redirect_uris"),tokenEndpointAuthMethod:e.token_endpoint_auth_method,createdAt:O(e.created_at),clientExpiresAt:O(e.client_expires_at)};return e.hashed_client_secret&&(t.hashedClientSecret=e.hashed_client_secret),e.client_secret_expires_at&&(t.clientSecretExpiresAt=O(e.client_secret_expires_at)),e.revoked_at&&(t.revokedAt=O(e.revoked_at)),qi.parse(t)}),Fd=c.object({id:je,current_state_hash:c.string(),phase:Ud,principal_subject_id:Q.nullable(),principal_tenant_id:de.nullable(),principal_roles:c.unknown().nullable(),client_id:he,redirect_uri:c.string(),resource:c.string(),virtual_server_id:me,client_state:c.string().nullable(),scope:c.string(),code_challenge:c.string(),code_challenge_method:In,created_at:se,expires_at:se,consumed_at:se.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:O(e.created_at),expiresAt:O(e.expires_at)};if(e.client_state&&(t.clientState=e.client_state),e.consumed_at&&(t.consumedAt=O(e.consumed_at)),e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal_subject_id||!e.principal_tenant_id)throw new Error("Awaiting-setup pending authorization row is missing principal.");return{...t,phase:"awaiting_setup",principal:{subjectId:e.principal_subject_id,tenantId:e.principal_tenant_id,...e.principal_roles===null?{}:{roles:c.array(c.string()).parse(pr(e.principal_roles,"principal_roles"))}}}}),QE=c.object({id:je});function Eg(e){return{clientId:e.client_id,resource:e.resource,virtualServerId:e.virtual_server_id,tenantId:e.tenant_id,subjectId:e.subject_id,scope:e.scope,roles:Vd(e.roles,"roles"),createdAt:O(e.created_at),expiresAt:O(e.expires_at)}}o(Eg,"downstreamGrantAccessFields");var kg=c.object({id:yt,client_id:he,resource:c.string(),virtual_server_id:me,tenant_id:de,subject_id:Q,scope:c.string(),roles:c.unknown(),current_refresh_token_hash:c.string().nullable(),previous_refresh_token_hash:c.string().nullable(),created_at:se,expires_at:se,revoked_at:se.nullable(),revoked_reason:c.string().nullable()}).transform(e=>{let t={id:e.id,...Eg(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=O(e.revoked_at)),e.revoked_reason&&(t.revokedReason=e.revoked_reason),Lo.parse(t)}),eP=c.object({token_hash:c.string(),grant_id:yt,client_id:he,resource:c.string(),virtual_server_id:me,tenant_id:de,subject_id:Q,scope:c.string(),roles:c.unknown(),created_at:se,expires_at:se,revoked_at:se.nullable()}).transform(e=>{let t={tokenHash:e.token_hash,grantId:e.grant_id,...Eg(e)};return e.revoked_at&&(t.revokedAt=O(e.revoked_at)),Cn.parse(t)});function Pg(e){return[e.clientId,e.redirectUri,e.resource,e.virtualServerId,e.tenantId,e.subjectId,e.scope,JSON.stringify(e.roles),e.codeChallenge,e.codeChallengeMethod,new Date(e.createdAt),new Date(e.expiresAt)]}o(Pg,"authorizationTransactionValues");function tP(e,t){let r=_g.parse(t);return e.query(`INSERT INTO downstream_oauth_authorization_transactions (
45
45
  id, client_id, redirect_uri, resource, virtual_server_id, tenant_id,
46
46
  subject_id, scope, roles, code_challenge, code_challenge_method,
47
47
  created_at, expires_at
48
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, $13)`,[r.id,...sg(r)])}o(nP,"insertAuthorizationTransaction");function oP(e,t){return e.query(`INSERT INTO downstream_oauth_authorization_codes (
48
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, $13)`,[r.id,...Pg(r)])}o(tP,"insertAuthorizationTransaction");function rP(e,t){return e.query(`INSERT INTO downstream_oauth_authorization_codes (
49
49
  code_hash, transaction_id, grant_id, client_id, redirect_uri, resource,
50
50
  virtual_server_id, tenant_id, subject_id, scope, roles,
51
51
  code_challenge, code_challenge_method, created_at, expires_at
52
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12, $13, $14, $15)`,[t.codeHash,t.id,t.grantId,...sg(t)])}o(oP,"insertAuthorizationCode");function aP(e,t){return e&&!e.revokedAt?new Date(e.expiresAt).getTime()<=t.getTime()?{kind:"expired"}:void 0:{kind:"revoked"}}o(aP,"accessTokenGrantValidationFailure");var Ts=class{constructor(t){this.db=t}static{o(this,"PostgresDownstreamOAuthRepository")}async readPendingAuthorizationStatus(t){return u.array(YA).parse(await this.db.query(`SELECT current_state_hash, phase, consumed_at, expires_at
52
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12, $13, $14, $15)`,[t.codeHash,t.id,t.grantId,...Pg(t)])}o(rP,"insertAuthorizationCode");function nP(e,t){return e&&!e.revokedAt?new Date(e.expiresAt).getTime()<=t.getTime()?{kind:"expired"}:void 0:{kind:"revoked"}}o(nP,"accessTokenGrantValidationFailure");var Hi=class{constructor(t){this.db=t}static{o(this,"PostgresDownstreamOAuthRepository")}async readPendingAuthorizationStatus(t){return c.array(WE).parse(await this.db.query(`SELECT current_state_hash, phase, consumed_at, expires_at
53
53
  FROM downstream_oauth_pending_authorization_transactions
54
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 u.array(eP).parse(await this.db.query(`SELECT
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(XE).parse(await this.db.query(`SELECT
56
56
  client_id,
57
57
  client_name,
58
58
  redirect_uris,
@@ -76,14 +76,14 @@ data:
76
76
  client_expires_at,
77
77
  revoked_at,
78
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 u.array(tP).parse(await this.db.query(`INSERT INTO downstream_oauth_pending_authorization_transactions (
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(QE).parse(await this.db.query(`INSERT INTO downstream_oauth_pending_authorization_transactions (
80
80
  id, current_state_hash, phase, principal_subject_id,
81
81
  principal_tenant_id, principal_roles, client_id, redirect_uri,
82
82
  resource, virtual_server_id, client_state, scope, code_challenge,
83
83
  code_challenge_method, created_at, expires_at, consumed_at
84
84
  ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
85
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.tenantId: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=u.array(Pd).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
86
+ RETURNING id`,[t.id,t.currentStateHash,t.phase,t.phase==="awaiting_setup"?t.principal.subjectId:null,t.phase==="awaiting_setup"?t.principal.tenantId: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(Fd).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
87
87
  SET current_state_hash = $4,
88
88
  phase = $5,
89
89
  principal_subject_id = $6,
@@ -94,19 +94,19 @@ data:
94
94
  AND phase = $3
95
95
  AND consumed_at IS NULL
96
96
  AND expires_at > $9
97
- RETURNING *`,[t.id,t.currentStateHash,t.expectedPhase,t.nextStateHash,t.nextPhase,t.principal.subjectId,t.principal.tenantId,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=u.array(Pd).parse(await this.db.query(`SELECT *
97
+ RETURNING *`,[t.id,t.currentStateHash,t.expectedPhase,t.nextStateHash,t.nextPhase,t.principal.subjectId,t.principal.tenantId,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(Fd).parse(await this.db.query(`SELECT *
98
98
  FROM downstream_oauth_pending_authorization_transactions
99
99
  WHERE id = $1
100
- 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=u.array(Pd).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
100
+ 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(Fd).parse(await this.db.query(`UPDATE downstream_oauth_pending_authorization_transactions
101
101
  SET consumed_at = $3
102
102
  WHERE id = $1
103
103
  AND current_state_hash = $2
104
104
  AND consumed_at IS NULL
105
105
  AND expires_at > $3
106
- 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=>[nP(r,t),oP(r,t)])}async exchangeAuthorizationCode(t){let n=u.array(u.object({redirect_uri:u.string()})).parse(await this.db.query(`SELECT redirect_uri
106
+ 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=>[tP(r,t),rP(r,t)])}async exchangeAuthorizationCode(t){let n=c.array(c.object({redirect_uri:c.string()})).parse(await this.db.query(`SELECT redirect_uri
107
107
  FROM downstream_oauth_authorization_codes
108
108
  WHERE code_hash = $1
109
- LIMIT 1`,[t.codeHash]))[0]?.redirect_uri,a=n!==void 0&&Rs(n,t.redirectUri)?n:t.redirectUri,i=u.array(u.record(u.string(),u.unknown())).parse(await this.db.query(`WITH candidate AS (
109
+ LIMIT 1`,[t.codeHash]))[0]?.redirect_uri,a=n!==void 0&&Li(n,t.redirectUri)?n:t.redirectUri,s=c.array(c.record(c.string(),c.unknown())).parse(await this.db.query(`WITH candidate AS (
110
110
  SELECT *
111
111
  FROM downstream_oauth_authorization_codes
112
112
  WHERE code_hash = $1
@@ -212,18 +212,18 @@ data:
212
212
  END AS kind,
213
213
  inserted_grant.*
214
214
  FROM (SELECT 1) AS marker
215
- 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],c=u.enum(["exchanged","consumed","missing","expired","resource_mismatch","binding_mismatch"]).parse(i?.kind??"missing");return c!=="exchanged"?{kind:c}:{kind:"exchanged",grant:og.parse(i)}}async getGrant(t){return u.array(og).parse(await this.db.query(`SELECT *
215
+ 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:kg.parse(s)}}async getGrant(t){return c.array(kg).parse(await this.db.query(`SELECT *
216
216
  FROM downstream_oauth_grants
217
217
  WHERE id = $1
218
218
  LIMIT 1`,[t]))[0]}async saveAccessToken(t){await this.db.query(`INSERT INTO downstream_oauth_access_tokens (
219
219
  token_hash, grant_id, client_id, resource, virtual_server_id, tenant_id,
220
220
  subject_id, scope, roles, created_at, expires_at, revoked_at
221
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12)`,[t.tokenHash,t.grantId,t.clientId,t.resource,t.virtualServerId,t.tenantId,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=u.array(rP).parse(await this.db.query(`SELECT access_tokens.*
221
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12)`,[t.tokenHash,t.grantId,t.clientId,t.resource,t.virtualServerId,t.tenantId,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(eP).parse(await this.db.query(`SELECT access_tokens.*
222
222
  FROM downstream_oauth_access_tokens AS access_tokens
223
223
  JOIN downstream_oauth_grants AS grants
224
224
  ON grants.id = access_tokens.grant_id
225
225
  WHERE access_tokens.token_hash = $1
226
- 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),s=aP(a,t.now);return s||{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 u.array(QA).parse(await this.db.query(`WITH candidate AS (
226
+ 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=nP(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(YE).parse(await this.db.query(`WITH candidate AS (
227
227
  SELECT id,
228
228
  'current' AS matched
229
229
  FROM downstream_oauth_grants
@@ -245,7 +245,7 @@ data:
245
245
  AND grants.expires_at > $4
246
246
  AND ($5::text IS NULL OR grants.resource = $5)
247
247
  AND grants.current_refresh_token_hash = $1
248
- 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),s=await this.refreshTokenGrantFailure(t,a);return s||(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 u.array(XA).parse(await this.db.query(`SELECT id,
248
+ 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(JE).parse(await this.db.query(`SELECT id,
249
249
  revoked_at,
250
250
  expires_at,
251
251
  CASE
@@ -259,22 +259,22 @@ data:
259
259
  current_refresh_token_hash = $2
260
260
  OR previous_refresh_token_hash = $2
261
261
  )
262
- 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=u.array(u.object({token_hash:u.string(),client_id:Ze})).parse(await this.db.query(`SELECT token_hash, client_id
262
+ 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:he})).parse(await this.db.query(`SELECT token_hash, client_id
263
263
  FROM downstream_oauth_access_tokens
264
264
  WHERE token_hash = $1
265
265
  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
266
266
  SET revoked_at = $2
267
- WHERE token_hash = $1 AND revoked_at IS NULL`,[t.tokenHash,t.now]),{kind:"revoked_access_token"});let s=u.array(u.object({id:$t,client_id:Ze})).parse(await this.db.query(`SELECT id, client_id
267
+ WHERE token_hash = $1 AND revoked_at IS NULL`,[t.tokenHash,t.now]),{kind:"revoked_access_token"});let i=c.array(c.object({id:yt,client_id:he})).parse(await this.db.query(`SELECT id, client_id
268
268
  FROM downstream_oauth_grants
269
269
  WHERE current_refresh_token_hash = $1
270
270
  OR previous_refresh_token_hash = $1
271
271
  ORDER BY created_at DESC
272
- LIMIT 1`,[t.tokenHash]))[0];return s?this.revokeRefreshTokenGrantForOAuthToken(t,s):{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
272
+ 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
273
273
  SET revoked_at = $2,
274
274
  revoked_reason = $3
275
275
  WHERE id = $1 AND revoked_at IS NULL`,[t.grantId,t.now,t.reason]),r.query(`UPDATE downstream_oauth_access_tokens
276
276
  SET revoked_at = $2
277
- WHERE grant_id = $1 AND revoked_at IS NULL`,[t.grantId,t.now])])}};var Cs=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 sP(e){return e instanceof Cs}o(sP,"isHttpPgQuery");function iP(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(iP,"parseConnectionString");function cP(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"?e.message??"Unknown postgres error":"Unknown postgres error"}o(cP,"readErrorMessage");function uP(e){return typeof e=="object"&&e!==null&&Array.isArray(e.rows)}o(uP,"isSingleResponse");function dP(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}o(dP,"isBatchResponse");function ig(e,t={}){let{fetchEndpoint:r}=iP(e),n=t.fetchFn??fetch;async function a(d){let p=await s({query:d.query,params:d.params});if(!uP(p))throw g("internal_server_error","Unexpected postgres response shape: missing `rows`.");return p.rows}o(a,"runSingle");async function s(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(cP(l));throw g({code:"internal_server_error",privateDetail:`Postgres HTTP request failed (status ${p.status})`,cause:m})}return p.json()}o(s,"runRequest");function i(){return{query(d,p){return new Cs({query:d,params:p??[]},a)}}}o(i,"buildQueryDatabase");let c=i();return{query:c.query,async transaction(d){let l=d(c).map((h,_)=>{if(!sP(h))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 h.raw}),m=await s({queries:l.map(h=>({query:h.query,params:h.params}))});if(!dP(m))throw new Error("Unexpected postgres response shape: missing `results` for transaction.");return m.results.map(h=>h.rows)}}}o(ig,"createHttpPostgresGatewayDatabase");var lP=`
277
+ WHERE grant_id = $1 AND revoked_at IS NULL`,[t.grantId,t.now])])}};var Gi=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 oP(e){return e instanceof Gi}o(oP,"isHttpPgQuery");function aP(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(aP,"parseConnectionString");function iP(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"?e.message??"Unknown postgres error":"Unknown postgres error"}o(iP,"readErrorMessage");function sP(e){return typeof e=="object"&&e!==null&&Array.isArray(e.rows)}o(sP,"isSingleResponse");function cP(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}o(cP,"isBatchResponse");function xg(e,t={}){let{fetchEndpoint:r}=aP(e),n=t.fetchFn??fetch;async function a(d){let l=await i({query:d.query,params:d.params});if(!sP(l))throw g("internal_server_error","Unexpected postgres response shape: missing `rows`.");return l.rows}o(a,"runSingle");async function i(d){let l=await n(r,{method:"POST",headers:{"content-type":"application/json","Neon-Connection-String":e,"Neon-Raw-Text-Output":"true"},body:JSON.stringify(d)});if(!l.ok){let p;try{p=await l.json()}catch{p=void 0}let m=new Error(iP(p));throw g({code:"internal_server_error",privateDetail:`Postgres HTTP request failed (status ${l.status})`,cause:m})}return l.json()}o(i,"runRequest");function s(){return{query(d,l){return new Gi({query:d,params:l??[]},a)}}}o(s,"buildQueryDatabase");let u=s();return{query:u.query,async transaction(d){let p=d(u).map((f,_)=>{if(!oP(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:p.map(f=>({query:f.query,params:f.params}))});if(!cP(m))throw new Error("Unexpected postgres response shape: missing `results` for transaction.");return m.results.map(f=>f.rows)}}}o(xg,"createHttpPostgresGatewayDatabase");var uP=`
278
278
  DO $$
279
279
  BEGIN
280
280
  IF to_regclass('public.downstream_oauth_pending_authorization_transactions') IS NULL THEN
@@ -427,11 +427,11 @@ BEGIN
427
427
  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$;
428
428
  END IF;
429
429
  END $$;
430
- `,pP=`
430
+ `,dP=`
431
431
  DROP INDEX IF EXISTS public.downstream_oauth_cimd_metadata_cache_expiry_idx;
432
- `,mP=`
432
+ `,lP=`
433
433
  DROP TABLE IF EXISTS public.downstream_oauth_cimd_metadata_cache;
434
- `,fP=`
434
+ `,pP=`
435
435
  DO $$
436
436
  BEGIN
437
437
  IF to_regclass('public.upstream_connections') IS NULL THEN
@@ -449,9 +449,27 @@ BEGIN
449
449
  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)
450
450
  OR ("upstream_connections"."owner_mode" = 'tenant_shared' AND "upstream_connections"."tenant_id" IS NOT NULL AND "upstream_connections"."user_id" IS NULL))$check$;
451
451
  END $$;
452
- `,hP=[lP,pP,mP,fP].join(`
452
+ `,mP=[uP,dP,lP,pP].join(`
453
453
  --> statement-breakpoint
454
- `),cg=[{tag:"0000_messy_makkari",sql:`CREATE TABLE "browser_connect_ticket_consumptions" (
454
+ `),hP=`
455
+ DO $$
456
+ BEGIN
457
+ IF to_regclass('public.upstream_connections') IS NULL THEN
458
+ RETURN;
459
+ END IF;
460
+
461
+ IF EXISTS (
462
+ SELECT 1
463
+ FROM information_schema.columns
464
+ WHERE table_schema = 'public'
465
+ AND table_name = 'upstream_connections'
466
+ AND column_name = 'id'
467
+ AND data_type = 'uuid'
468
+ ) THEN
469
+ EXECUTE 'ALTER TABLE public.upstream_connections ALTER COLUMN id TYPE text USING id::text';
470
+ END IF;
471
+ END $$;
472
+ `,Og=[{tag:"0000_messy_makkari",sql:`CREATE TABLE "browser_connect_ticket_consumptions" (
455
473
  "id" uuid PRIMARY KEY NOT NULL,
456
474
  "consumed_at" timestamp with time zone NOT NULL,
457
475
  "expires_at" timestamp with time zone NOT NULL
@@ -584,7 +602,7 @@ CREATE TABLE "downstream_oauth_pending_authorization_transactions" (
584
602
  );
585
603
  --> statement-breakpoint
586
604
  CREATE TABLE "upstream_connections" (
587
- "id" uuid PRIMARY KEY NOT NULL,
605
+ "id" text PRIMARY KEY NOT NULL,
588
606
  "tenant_id" text,
589
607
  "owner_mode" text NOT NULL,
590
608
  "user_id" text,
@@ -636,44 +654,52 @@ CREATE INDEX "downstream_oauth_grants_expiry_idx" ON "downstream_oauth_grants" U
636
654
  CREATE INDEX "downstream_oauth_pending_authorization_expiry_idx" ON "downstream_oauth_pending_authorization_transactions" USING btree ("expires_at");--> statement-breakpoint
637
655
  CREATE INDEX "upstream_oauth_state_consumptions_expiry_idx" ON "upstream_oauth_state_consumptions" USING btree ("expires_at");--> statement-breakpoint
638
656
  CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING btree ("expires_at");
639
- `},{tag:"0001_self_heal_pending_authorization",sql:hP}];var Po="_runtime_applied_migrations",gP=`
640
- CREATE TABLE IF NOT EXISTS ${Po} (
657
+ `},{tag:"0001_self_heal_pending_authorization",sql:mP},{tag:"0002_upstream_connection_id_text",sql:hP}];var Go="_runtime_applied_migrations",fP=`
658
+ CREATE TABLE IF NOT EXISTS ${Go} (
641
659
  tag text PRIMARY KEY NOT NULL,
642
660
  applied_at timestamp with time zone NOT NULL DEFAULT now()
643
661
  )
644
- `,Ao;async function _P(e){if(Ao)return Ao;Ao=(async()=>{await e.query(gP),await e.query(`INSERT INTO ${Po} (tag)
662
+ `,Ho;async function gP(e){if(Ho)return Ho;Ho=(async()=>{await e.query(fP),await e.query(`INSERT INTO ${Go} (tag)
645
663
  SELECT '0000_messy_makkari'
646
664
  WHERE to_regclass('public.audit_events') IS NOT NULL
647
665
  AND NOT EXISTS (
648
- SELECT 1 FROM ${Po}
666
+ SELECT 1 FROM ${Go}
649
667
  WHERE tag = '0000_messy_makkari'
650
668
  )
651
- ON CONFLICT (tag) DO NOTHING`);let t=await e.query(`SELECT tag FROM ${Po}`),r=new Set(t.map(n=>n.tag));for(let n of cg){if(r.has(n.tag))continue;let a=n.sql.split(/-->\s*statement-breakpoint/g).map(s=>s.trim()).filter(s=>s.length>0);for(let s of a)await e.query(s);await e.query(`INSERT INTO ${Po} (tag) VALUES ($1)`,[n.tag])}})();try{await Ao}catch(t){throw Ao=void 0,t}}o(_P,"ensureGatewayMigrationsApplied");function ug(e){let t=o(()=>_P(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(ug,"createMigrationGatedDatabase");W();W();var yP=["user","tenant_shared"],yn=u.enum(yP);function ur(e,t){if(!e)throw g("forbidden","User-owned upstream connections require an authenticated tenant.");return{mode:"user",tenantId:e,subjectId:t}}o(ur,"buildUserUpstreamConnectionOwner");function Es(e){if(!e)throw g("forbidden","Tenant-shared upstream connections require an authenticated tenant.");return{mode:"tenant_shared",tenantId:e}}o(Es,"buildTenantSharedUpstreamConnectionOwner");W();W();function As(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(As,"parseSafeRelativeReturnTo");var dg=u.object({tenantId:$e.optional(),ownerMode:yn,initiatedBySubjectId:le,ownerSubjectId:le.optional(),upstreamServerId:ut,authProfileId:dt,virtualServerId:ge,returnTo:u.string().min(1).transform(e=>As(e)).optional()});function lg(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="user"&&!e.tenantId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned state requires tenantId",path:["tenantId"]}),e.ownerMode==="tenant_shared"&&(e.tenantId||t.addIssue({code:u.ZodIssueCode.custom,message:"Tenant-shared state requires tenantId",path:["tenantId"]}),e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"Tenant-shared state must not include ownerSubjectId",path:["ownerSubjectId"]}))}o(lg,"validateUpstreamOwnerState");var wn=dg.superRefine(lg),pg=dg.omit({returnTo:!0}).superRefine(lg);function xo(e){return wn.parse({tenantId:e.owner.tenantId,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(xo,"buildUpstreamOwnerState");function Sn(e){if(e.ownerMode==="tenant_shared")return Es(e.tenantId);if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");if(!e.tenantId)throw g("oauth_state_invalid","User-owned upstream state is missing the tenant.");return ur(e.tenantId,e.ownerSubjectId)}o(Sn,"resolveUpstreamConnectionOwnerFromState");var wP=["active","not_connected","reconsent_required"],SP=["basic_auth_app_password","bearer_token"],mg=u.uuid().brand(),Ps=u.uuid().brand(),xd=u.uuid().brand(),kd=u.enum(wP),vP=u.enum(SP),fg=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:le.optional()}),Od=fg.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:vP.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}),bP=u.object({id:mg,tenantId:$e.optional(),subjectId:le.optional(),ownerMode:yn,upstreamServerId:ut,authProfileId:dt,status:kd,encryptedAccessToken:u.string().optional(),encryptedRefreshToken:u.string().optional(),scopes:u.array(u.string()),expiresAt:Ne.optional(),metadata:Od.optional(),createdAt:Ne,updatedAt:Ne});function RP(e,t){e.ownerMode==="user"&&!e.subjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]}),e.ownerMode==="tenant_shared"&&!e.tenantId&&t.addIssue({code:u.ZodIssueCode.custom,message:"Tenant-shared upstream connections require tenantId",path:["tenantId"]})}o(RP,"validateUpstreamConnectionOwnerShape");var hg=bP.superRefine(RP),gg=wn.extend({id:Ps,callbackPath:u.string().min(1),expiresAt:Ne,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(fg.shape);function _g(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(_g,"readUpstreamConnectionStatus");function xs(){return mg.parse(crypto.randomUUID())}o(xs,"createUpstreamConnectionId");function yg(){return Ps.parse(crypto.randomUUID())}o(yg,"createOAuthStateId");function wg(){return xd.parse(crypto.randomUUID())}o(wg,"createBrowserConnectTicketId");var IP=u.unknown().transform(e=>cr(e,"upstream connection scopes")).pipe(u.array(u.string())),TP=u.unknown().transform(e=>{if(e!=null)return cr(e,"upstream connection metadata")}).transform(e=>{if(!e||typeof e!="object"||Array.isArray(e))return;let t=Od.safeParse(e);if(t.success)return Object.values(t.data).some(r=>r!==void 0)?t.data:void 0}),Sg=u.object({id:u.uuid(),tenant_id:$e.nullable(),owner_mode:yn,user_id:le.nullable(),upstream_server_id:ut,auth_profile_id:dt,status:kd,encrypted_access_token:u.string().nullable(),encrypted_refresh_token:u.string().nullable(),scopes:IP,expires_at:ie.nullable(),metadata:TP,created_at:ie,updated_at:ie}).transform(e=>hg.parse({id:e.id,tenantId:e.tenant_id??void 0,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?K(e.expires_at):void 0,metadata:e.metadata,createdAt:K(e.created_at),updatedAt:K(e.updated_at)}));function CP(e){let t=e.firstParam??1,r=`$${t}`,n=`$${t+1}`,a=`$${t+2}`;switch(e.owner.mode){case"user":return{whereClause:`owner_mode = ${r}
652
- AND tenant_id IS NOT DISTINCT FROM ${n}
653
- AND user_id = ${a}
654
- AND upstream_server_id = $${t+3}
655
- AND auth_profile_id = $${t+4}`,params:[e.owner.mode,e.owner.tenantId??null,e.owner.subjectId,e.upstreamServerId,e.authProfileId]};case"tenant_shared":return{whereClause:`owner_mode = ${r}
656
- AND tenant_id = ${n}
657
- AND user_id IS NULL
658
- AND upstream_server_id = ${a}
659
- AND auth_profile_id = $${t+3}`,params:[e.owner.mode,e.owner.tenantId,e.upstreamServerId,e.authProfileId]}}}o(CP,"buildOwnerLookup");function EP(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(EP,"metadataToDatabaseValue");function AP(e){if(!e)throw g("internal_server_error","Failed to persist upstream connection");return e}o(AP,"requirePersistedUpstreamConnection");var ks=class{constructor(t){this.db=t}static{o(this,"PostgresUpstreamConnectionRepository")}async get(t,r,n){let a=CP({owner:t,upstreamServerId:r,authProfileId:n});return u.array(Sg).parse(await this.db.query(`SELECT
660
- id,
661
- tenant_id,
669
+ ON CONFLICT (tag) DO NOTHING`);let t=await e.query(`SELECT tag FROM ${Go}`),r=new Set(t.map(n=>n.tag));for(let n of Og){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 ${Go} (tag) VALUES ($1)`,[n.tag])}})();try{await Ho}catch(t){throw Ho=void 0,t}}o(gP,"ensureGatewayMigrationsApplied");function Ug(e){let t=o(()=>gP(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(Ug,"createMigrationGatedDatabase");X();X();var _P=["user","tenant_shared"],Ht=c.enum(_P);function mr(e,t){if(!e)throw g("forbidden","User-owned upstream connections require an authenticated tenant.");return{mode:"user",tenantId:e,subjectId:t}}o(mr,"buildUserUpstreamConnectionOwner");function Bi(e){if(!e)throw g("forbidden","Tenant-shared upstream connections require an authenticated tenant.");return{mode:"tenant_shared",tenantId:e}}o(Bi,"buildTenantSharedUpstreamConnectionOwner");X();X();function Vi(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(Vi,"parseSafeRelativeReturnTo");var zg=c.object({tenantId:de.optional(),ownerMode:Ht,initiatedBySubjectId:Q,ownerSubjectId:Q.optional(),upstreamServerId:Ee,authProfileId:Pe,virtualServerId:me,returnTo:c.string().min(1).transform(e=>Vi(e)).optional()});function Ng(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="user"&&!e.tenantId&&t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned state requires tenantId",path:["tenantId"]}),e.ownerMode==="tenant_shared"&&(e.tenantId||t.addIssue({code:c.ZodIssueCode.custom,message:"Tenant-shared state requires tenantId",path:["tenantId"]}),e.ownerSubjectId&&t.addIssue({code:c.ZodIssueCode.custom,message:"Tenant-shared state must not include ownerSubjectId",path:["ownerSubjectId"]}))}o(Ng,"validateUpstreamOwnerState");var kn=zg.superRefine(Ng),Dg=zg.omit({returnTo:!0}).superRefine(Ng);function Bo(e){return kn.parse({tenantId:e.owner.tenantId,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(Bo,"buildUpstreamOwnerState");function En(e){if(e.ownerMode==="tenant_shared")return Bi(e.tenantId);if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");if(!e.tenantId)throw g("oauth_state_invalid","User-owned upstream state is missing the tenant.");return mr(e.tenantId,e.ownerSubjectId)}o(En,"resolveUpstreamConnectionOwnerFromState");var yP=["active","not_connected","reconsent_required"],SP=["basic_auth_app_password","bearer_token"],Mg=c.string().trim().min(1).brand(),Pn=c.uuid().brand(),Vo=c.uuid().brand(),xn=c.enum(yP),wP=c.enum(SP),qg=c.object({encryptedClientInformation:c.string().optional(),encryptedDiscoveryState:c.string().optional(),connectedBySubjectId:Q.optional()}),Zd=qg.extend({encryptedStaticSecret:c.string().optional(),staticSecretKind:wP.optional(),staticSecretLabel:c.string().min(1).optional(),staticSecretUsername:c.string().min(1).optional()}).strict(),vP=c.object({id:Mg,tenantId:de.optional(),subjectId:Q.optional(),ownerMode:Ht,upstreamServerId:Ee,authProfileId:Pe,status:xn,encryptedAccessToken:c.string().min(1).optional(),encryptedRefreshToken:c.string().min(1).optional(),scopes:c.array(c.string()),expiresAt:V.optional(),metadata:Zd.optional(),createdAt:V,updatedAt:V});function Kd(e,t){e.ownerMode==="user"&&(e.tenantId||t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned upstream connections require tenantId",path:["tenantId"]}),e.subjectId||t.addIssue({code:c.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="tenant_shared"&&(e.tenantId||t.addIssue({code:c.ZodIssueCode.custom,message:"Tenant-shared upstream connections require tenantId",path:["tenantId"]}),e.subjectId!==void 0&&t.addIssue({code:c.ZodIssueCode.custom,message:"Tenant-shared upstream connections must not include subjectId",path:["subjectId"]}))}o(Kd,"validateUpstreamConnectionOwnerShape");var Gt=vP.superRefine(Kd);function Dr(e){return JSON.stringify([e.owner.mode,e.owner.tenantId,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Dr,"readUpstreamConnectionLookupKey");var Fo=kn.extend({id:Pn,callbackPath:c.string().min(1),expiresAt:V,codeVerifier:c.string().optional(),redirectUri:c.url(),returnOrigin:c.url().optional()}).extend(qg.shape);function $g(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o($g,"readUpstreamConnectionStatus");function Fi(){return Mg.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(Fi,"createUpstreamConnectionId");function Lg(){return Pn.parse(crypto.randomUUID())}o(Lg,"createOAuthStateId");function jg(){return Vo.parse(crypto.randomUUID())}o(jg,"createBrowserConnectTicketId");var Hg=c.unknown().transform(e=>pr(e,"upstream connection scopes")).pipe(c.array(c.string())),Gg=c.unknown().transform(e=>{if(e!=null)return pr(e,"upstream connection metadata")}).transform(e=>{if(!e||typeof e!="object"||Array.isArray(e))return;let t=Zd.safeParse(e);if(t.success)return Object.values(t.data).some(r=>r!==void 0)?t.data:void 0}),RP=c.object({id:c.string().min(1),tenant_id:de.nullable(),owner_mode:Ht,user_id:Q.nullable(),upstream_server_id:Ee,auth_profile_id:Pe,status:xn,encrypted_access_token:c.string().nullable(),encrypted_refresh_token:c.string().nullable(),scopes:Hg,expires_at:se.nullable(),metadata:Gg,created_at:se,updated_at:se}).transform(e=>Gt.parse({id:e.id,tenantId:e.tenant_id??void 0,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?O(e.expires_at):void 0,metadata:e.metadata,createdAt:O(e.created_at),updatedAt:O(e.updated_at)})),bP=c.object({requested_ordinal:c.number(),id:c.string().min(1).nullable(),tenant_id:de.nullable(),owner_mode:Ht.nullable(),user_id:Q.nullable(),upstream_server_id:Ee.nullable(),auth_profile_id:Pe.nullable(),status:xn.nullable(),encrypted_access_token:c.string().nullable(),encrypted_refresh_token:c.string().nullable(),scopes:Hg.nullable(),expires_at:se.nullable(),metadata:Gg,created_at:se.nullable(),updated_at:se.nullable()}).transform(e=>{if(e.id!==null)return Gt.parse({id:e.id,tenantId:e.tenant_id??void 0,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?O(e.expires_at):void 0,metadata:e.metadata,createdAt:O(e.created_at),updatedAt:O(e.updated_at)})});function IP(e){let t=[],r=e.map((n,a)=>{let i=t.length+1;return t.push(a,n.owner.mode,n.owner.tenantId,n.owner.mode==="user"?n.owner.subjectId:null,n.upstreamServerId,n.authProfileId),`($${i}::integer, $${i+1}, $${i+2}, $${i+3}, $${i+4}, $${i+5})`});return{params:t,sql:`WITH requested(
670
+ requested_ordinal,
662
671
  owner_mode,
672
+ tenant_id,
663
673
  user_id,
664
674
  upstream_server_id,
665
- auth_profile_id,
666
- status,
667
- encrypted_access_token,
668
- encrypted_refresh_token,
669
- scopes,
670
- expires_at,
671
- metadata,
672
- created_at,
673
- updated_at
674
- FROM upstream_connections
675
- WHERE ${a.whereClause}
676
- LIMIT 1`,a.params))[0]}async upsert(t){let r=new Date,n=u.array(Sg).parse(await this.db.query(`INSERT INTO upstream_connections (
675
+ auth_profile_id
676
+ ) AS (
677
+ VALUES ${r.join(", ")}
678
+ )
679
+ SELECT
680
+ requested.requested_ordinal,
681
+ upstream_connections.id,
682
+ upstream_connections.tenant_id,
683
+ upstream_connections.owner_mode,
684
+ upstream_connections.user_id,
685
+ upstream_connections.upstream_server_id,
686
+ upstream_connections.auth_profile_id,
687
+ upstream_connections.status,
688
+ upstream_connections.encrypted_access_token,
689
+ upstream_connections.encrypted_refresh_token,
690
+ upstream_connections.scopes,
691
+ upstream_connections.expires_at,
692
+ upstream_connections.metadata,
693
+ upstream_connections.created_at,
694
+ upstream_connections.updated_at
695
+ FROM requested
696
+ LEFT JOIN upstream_connections
697
+ ON upstream_connections.owner_mode = requested.owner_mode
698
+ AND upstream_connections.tenant_id IS NOT DISTINCT FROM requested.tenant_id
699
+ AND upstream_connections.user_id IS NOT DISTINCT FROM requested.user_id
700
+ AND upstream_connections.upstream_server_id = requested.upstream_server_id
701
+ AND upstream_connections.auth_profile_id = requested.auth_profile_id
702
+ ORDER BY requested.requested_ordinal`}}o(IP,"buildBatchGetQuery");function CP(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(CP,"metadataToDatabaseValue");function TP(e){if(!e)throw g("internal_server_error","Failed to persist upstream connection");return e}o(TP,"requirePersistedUpstreamConnection");var Zi=class{constructor(t){this.db=t}static{o(this,"PostgresUpstreamConnectionRepository")}async batchGet(t){if(t.length===0)return[];let r=IP(t);return c.array(bP).parse(await this.db.query(r.sql,r.params))}async upsert(t){let r=new Date,n=c.array(RP).parse(await this.db.query(`INSERT INTO upstream_connections (
677
703
  id,
678
704
  tenant_id,
679
705
  owner_mode,
@@ -727,7 +753,7 @@ CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING
727
753
  expires_at,
728
754
  metadata,
729
755
  created_at,
730
- updated_at`,[t.id,t.tenantId??null,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,EP(t.metadata),r]));return AP(n[0])}};W();var PP=60*60*24*1e3,xP=u.object({kind:u.enum(["available","consumed","missing"]),record:u.unknown().nullable()}),kP=u.object({inserted:u.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}},u.boolean())});function vg(e,t){let r=e[0];if(!r)throw g("internal_server_error",`Postgres ${t} query returned no result row`);return r}o(vg,"requireSingleRow");function OP(e){return gg.parse(cr(e,"upstream OAuth state record"))}o(OP,"parseStoredOAuthStateRecord");var Os=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 (
756
+ updated_at`,[t.id,t.tenantId??null,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,CP(t.metadata),r]));return TP(n[0])}};X();var AP=60*60*24*1e3,kP=c.object({kind:c.enum(["available","consumed","missing"]),record:c.unknown().nullable()}),EP=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 Bg(e,t){let r=e[0];if(!r)throw g("internal_server_error",`Postgres ${t} query returned no result row`);return r}o(Bg,"requireSingleRow");function PP(e){return Fo.parse(pr(e,"upstream OAuth state record"))}o(PP,"parseStoredOAuthStateRecord");var Ki=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 (
731
757
  id,
732
758
  record,
733
759
  expires_at,
@@ -737,7 +763,7 @@ CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING
737
763
  ON CONFLICT (id) DO UPDATE
738
764
  SET record = EXCLUDED.record,
739
765
  expires_at = EXCLUDED.expires_at,
740
- 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()+PP),a=vg(u.array(xP).parse(await this.db.query(`WITH expired_state_cleanup AS (
766
+ 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()+AP),a=Bg(c.array(kP).parse(await this.db.query(`WITH expired_state_cleanup AS (
741
767
  DELETE FROM upstream_oauth_states
742
768
  WHERE id = $1
743
769
  AND expires_at <= $2
@@ -788,7 +814,7 @@ CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING
788
814
  WHEN EXISTS (SELECT 1 FROM candidate) THEN 'consumed'
789
815
  ELSE 'missing'
790
816
  END AS kind,
791
- (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:OP(a.record)}}return{kind:a.kind}}},Us=class{constructor(t){this.db=t}static{o(this,"PostgresBrowserConnectTicketStore")}async consume(t,r){let n=new Date;return vg(u.array(kP).parse(await this.db.query(`WITH expired_consumption_cleanup AS (
817
+ (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:PP(a.record)}}return{kind:a.kind}}},Wi=class{constructor(t){this.db=t}static{o(this,"PostgresBrowserConnectTicketStore")}async consume(t,r){let n=new Date;return Bg(c.array(EP).parse(await this.db.query(`WITH expired_consumption_cleanup AS (
792
818
  DELETE FROM browser_connect_ticket_consumptions
793
819
  WHERE id = $1
794
820
  AND expires_at <= $2
@@ -806,11 +832,11 @@ CREATE INDEX "upstream_oauth_states_expiry_idx" ON "upstream_oauth_states" USING
806
832
  ON CONFLICT (id) DO NOTHING
807
833
  RETURNING id
808
834
  )
809
- SELECT EXISTS (SELECT 1 FROM inserted_consumption) AS inserted`,[t,n,r])),"browser connect ticket consume").inserted?{kind:"available"}:{kind:"consumed"}}};var UP="__zuploMcpGatewayStorageBackend";function NP(e){return{upstreamConnectionRepository:new ks(e),downstreamOAuthRepository:new Ts(e),oauthStateStore:new Os(e),browserConnectTicketStore:new Us(e)}}o(NP,"createPostgresStorageBackend");var Ud;function $P(){let e=Is().TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING;if(!e)throw g("internal_server_error","TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING is required for the MCP gateway HTTP postgres backend.");return e}o($P,"requireDatabaseUrl");function zP(){let e=ig($P()),t=ug(e);return NP(t)}o(zP,"buildProductionStorageBackend");function H(){let e=globalThis[UP];return e||(Ud||(Ud=zP()),Ud)}o(H,"getStorage");W();import{errors as Ag,jwtVerify as Pg,SignJWT as xg}from"jose";import{base64url as MP}from"jose";var DP=new TextEncoder,Nd=32;function bg(e,t={}){let r=[qP(e),DP.encode(e)],n;for(let a of r)if(a){if(a.byteLength>=Nd){n=a;break}(n===void 0||a.byteLength>n.byteLength)&&(n=a)}if(n===void 0||n.byteLength<Nd){let a=t.name??"secret key material",s=n?.byteLength??0;throw new Error(`${a} must decode to at least ${Nd} bytes (got ${s}). Generate a high-entropy value with for example: openssl rand -base64 32 | tr '+/' '-_' | tr -d '='.`)}return n}o(bg,"decodeConfiguredSecretKeyMaterial");function qP(e){try{return MP.decode(e)}catch{return}}o(qP,"tryDecodeBase64Url");var Rg=new Map,Ig=new Map;function LP(e){let t=Rg.get(e);return t||(t=bg(Is()[e],{name:e}),Rg.set(e,t)),t}o(LP,"getMasterKeyMaterial");async function bt(e){let t=Ig.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(LP(e.envVar));return Ig.set(e.purpose,r),r}o(bt,"readCachedDerivedKey");var jP="SHA-256";var HP="zuplo-mcp-gateway:",GP=new TextEncoder,Tg=new WeakMap;async function dr(e,t){let r=Tg.get(e);r||(r=new Map,Tg.set(e,r));let n=r.get(t);if(n)return n;let a=await BP(e,t);return r.set(t,a),a}o(dr,"deriveGatewaySigningKey");async function BP(e,t){let r=Cg(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=GP.encode(`${HP}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:jP,salt:new Uint8Array,info:Cg(a)},n,32*8);return new Uint8Array(s)}o(BP,"hkdfExpand");function Cg(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Cg,"copyToArrayBuffer");var Ns="HS256",kg=15*60,VP=15*60,$s="zuplo-mcp-gateway",zs="zuplo-mcp-gateway",FP=pg.extend({id:Ps}),ZP=FP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Og=wn.extend({id:xd,purpose:u.literal("browser_connect")}),KP=wn.extend({purpose:u.literal("browser_connect")}),WP=Og.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Ug=kg*1e3;async function Ng(){return bt({purpose:"oauth-state",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>dr(e,"oauth-state"),"derive")})}o(Ng,"getOAuthStateKey");async function $g(){return bt({purpose:"browser-connect",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>dr(e,"browser-connect"),"derive")})}o($g,"getBrowserConnectKey");async function zg(e){let t=Math.floor(Date.now()/1e3)+kg;return new xg(e).setProtectedHeader({alg:Ns,typ:"JWT"}).setIssuer($s).setAudience(zs).setIssuedAt().setExpirationTime(t).sign(await Ng())}o(zg,"signOAuthState");async function Ms(e){try{let{payload:t}=await Pg(e,await Ng(),{algorithms:[Ns],issuer:$s,audience:zs});return ZP.parse(t)}catch(t){throw t instanceof Ag.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(Ms,"verifyOAuthState");async function Mg(e){let t=Math.floor(Date.now()/1e3)+VP,r=KP.parse(e),n=Og.parse({...r,id:wg()});return new xg(n).setProtectedHeader({alg:Ns,typ:"JWT"}).setIssuer($s).setAudience(zs).setIssuedAt().setExpirationTime(t).sign(await $g())}o(Mg,"signBrowserConnectTicket");async function Ds(e){try{let{payload:t}=await Pg(e,await $g(),{algorithms:[Ns],issuer:$s,audience:zs});return WP.parse(t)}catch(t){throw t instanceof Ag.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(Ds,"verifyBrowserConnectTicket");async function qs(e){if((await H().browserConnectTicketStore.consume(e.id,new Date(e.exp*1e3))).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(qs,"consumeBrowserConnectTicket");function JP(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(JP,"buildConnectRequiredMessage");async function Dg(e){let t=Q(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 Mg({...xo(e),purpose:"browser_connect"})),r.toString()}o(Dg,"buildGatewayBrowserTicketUrl");function YP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(YP,"buildGatewayConnectPath");async function $d(e){return Dg({...e,path:YP(e.upstreamServerId),redirect:!0})}o($d,"buildGatewayConnectUrl");async function qg(e){return Dg({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(qg,"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 $d(t),message:JP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(vn,"buildRedirectConnectRequiredResponse");function Lg(e){return jg({...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(Lg,"buildAdminConnectRequiredResponse");function jg(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(jg,"buildAdminSetupRequiredResponse");function Hg(e){return jg({...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(Hg,"buildAdminStaticSecretRequiredResponse");W();import{base64url as lr}from"jose";var XP="SHA-256",Rn="AES-GCM",QP=12,Md="zuplo-secret",Dd=1,Gg="env:TOKEN_ENCRYPTION_KEY",ex=u.object({version:u.literal(Dd),keyId:u.literal(Gg),algorithm:u.literal(Rn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function bn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(bn,"copyToArrayBuffer");async function zd(){return bt({purpose:"token-encryption",envVar:"TOKEN_ENCRYPTION_KEY",derive:o(async e=>{let t=await crypto.subtle.digest(XP,bn(e));return crypto.subtle.importKey("raw",t,{name:Rn},!1,["encrypt","decrypt"])},"derive")})}o(zd,"getEncryptionKey");function Bg(e){return bn(new TextEncoder().encode(`${Md}:v${e.version}:${e.keyId}`))}o(Bg,"getAssociatedData");function tx(e){return`${Md}:v${e.version}:${lr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(tx,"encodeEnvelope");function rx(e){let t=`${Md}:v${Dd}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(lr.decode(r));return ex.parse(JSON.parse(n))}o(rx,"decodeEnvelope");async function kr(e){let t=await zd(),r=crypto.getRandomValues(new Uint8Array(QP)),n={version:Dd,keyId:Gg},a=await crypto.subtle.encrypt({name:Rn,iv:r,additionalData:Bg(n)},t,new TextEncoder().encode(e));return tx({...n,algorithm:Rn,iv:lr.encode(r),ciphertext:lr.encode(new Uint8Array(a))})}o(kr,"encryptSecret");async function zt(e){let t=rx(e);if(t){let i=await zd(),c=await crypto.subtle.decrypt({name:Rn,iv:bn(lr.decode(t.iv)),additionalData:Bg(t)},i,bn(lr.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 zd(),s=await crypto.subtle.decrypt({name:Rn,iv:bn(lr.decode(r))},a,bn(lr.decode(n)));return new TextDecoder().decode(s)}o(zt,"decryptSecret");function nx(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="tenant_static_secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(nx,"requireTenantStaticSecretConfig");function Vg(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(Vg,"hasUsableTenantStaticSecret");async function ox(e){if(!Vg(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await zt(e.connection.metadata.encryptedStaticSecret)}}o(ox,"resolveTenantStaticSecretCredential");async function Fg(e){let t=Ge(e.upstreamServerId);nx(e.upstreamServerId,e.authProfileId);let r=await H().upstreamConnectionRepository.get(e.owner,e.upstreamServerId,e.authProfileId);if(Vg(r))return{kind:"authorized",credential:await ox({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:Hg(n)}}o(Fg,"resolveTenantStaticSecretCredentialForRequest");W();async function qd(e){let t=H().upstreamConnectionRepository,r=await t.get(e.owner,e.upstreamServerId,e.authProfileId);return t.upsert({id:r?.id??xs(),tenantId:e.owner.tenantId,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(qd,"upsertStaticSecretConnection");var ax=u.string().trim().min(1).max(320),sx=u.string().min(1).max(4096),ix=u.string().trim().min(1).max(4096);function Ld(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="user_static_secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Ld,"requireUserStaticSecretConfig");function cx(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(cx,"encodeBase64Utf8");function ux(e){return`Basic ${cx(`${e.username}:${e.appPassword}`)}`}o(ux,"buildBasicAuthHeader");function Zg(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(Zg,"hasEncryptedUserStaticSecret");async function dx(e){if(!Zg(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 zt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:ux({username:e.connection.metadata.staticSecretUsername,appPassword:await zt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(dx,"resolveUserStaticSecretCredential");async function Kg(e){if(Ld(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=ax.parse(e.username),n=sx.parse(e.appPassword);return qd({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await kr(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(Kg,"saveUserStaticSecretCredential");async function Ls(e){let t=Ld(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=ix.parse(e.token);return qd({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await kr(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Ls,"saveUserStaticBearerTokenCredential");function jd(e,t){return Ld(e,t)}o(jd,"readUserStaticSecretCaptureConfig");async function Wg(e){let t=Ge(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r=await H().upstreamConnectionRepository.get(e.owner,e.upstreamServerId,e.authProfileId);if(Zg(r))return{kind:"authorized",credential:await dx({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(Wg,"resolveUserStaticSecretCredentialForRequest");function Jg(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return qg({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(Jg,"buildUserStaticSecretConnectUrl");var Hd;Hd=globalThis.crypto;async function lx(e){return(await Hd).getRandomValues(new Uint8Array(e))}o(lx,"getRandomValues");async function px(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await lx(e-n.length);for(let s of a)s<r&&(n+=t[s%t.length])}return n}o(px,"random");async function mx(e){return await px(e)}o(mx,"generateVerifier");async function fx(e){let t=await(await Hd).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(fx,"generateChallenge");async function Gd(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await mx(e),r=await fx(t);return{code_verifier:t,code_challenge:r}}o(Gd,"pkceChallenge");W();var Te=Bl().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Kl.custom,message:"URL must be parseable",fatal:!0}),Hl}).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"}),js=fe({resource:f().url(),authorization_servers:R(Te).optional(),jwks_uri:f().url().optional(),scopes_supported:R(f()).optional(),bearer_methods_supported:R(f()).optional(),resource_signing_alg_values_supported:R(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:Y().optional(),authorization_details_types_supported:R(f()).optional(),dpop_signing_alg_values_supported:R(f()).optional(),dpop_bound_access_tokens_required:Y().optional()}),ko=fe({issuer:f(),authorization_endpoint:Te,token_endpoint:Te,registration_endpoint:Te.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),service_documentation:Te.optional(),revocation_endpoint:Te.optional(),revocation_endpoint_auth_methods_supported:R(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:R(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(f()).optional(),code_challenge_methods_supported:R(f()).optional(),client_id_metadata_document_supported:Y().optional()}),hx=fe({issuer:f(),authorization_endpoint:Te,token_endpoint:Te,userinfo_endpoint:Te.optional(),jwks_uri:Te,registration_endpoint:Te.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),acr_values_supported:R(f()).optional(),subject_types_supported:R(f()),id_token_signing_alg_values_supported:R(f()),id_token_encryption_alg_values_supported:R(f()).optional(),id_token_encryption_enc_values_supported:R(f()).optional(),userinfo_signing_alg_values_supported:R(f()).optional(),userinfo_encryption_alg_values_supported:R(f()).optional(),userinfo_encryption_enc_values_supported:R(f()).optional(),request_object_signing_alg_values_supported:R(f()).optional(),request_object_encryption_alg_values_supported:R(f()).optional(),request_object_encryption_enc_values_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),display_values_supported:R(f()).optional(),claim_types_supported:R(f()).optional(),claims_supported:R(f()).optional(),service_documentation:f().optional(),claims_locales_supported:R(f()).optional(),ui_locales_supported:R(f()).optional(),claims_parameter_supported:Y().optional(),request_parameter_supported:Y().optional(),request_uri_parameter_supported:Y().optional(),require_request_uri_registration:Y().optional(),op_policy_uri:Te.optional(),op_tos_uri:Te.optional(),client_id_metadata_document_supported:Y().optional()}),Hs=I({...hx.shape,...ko.pick({code_challenge_methods_supported:!0}).shape}),Oo=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Wl.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Xg=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),Yg=Te.optional().or(P("").transform(()=>{})),gx=I({redirect_uris:R(Te),token_endpoint_auth_method:f().optional(),grant_types:R(f()).optional(),response_types:R(f()).optional(),client_name:f().optional(),client_uri:Te.optional(),logo_uri:Yg,scope:f().optional(),contacts:R(f()).optional(),tos_uri:Yg,policy_uri:f().optional(),jwks_uri:Te.optional(),jwks:Fl().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Bd=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),Uo=gx.merge(Bd),V2=I({error:f(),error_description:f().optional()}).strip(),F2=I({token:f(),token_type_hint:f().optional()}).strip();function Qg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Qg,"resourceUrlFromServerUrl");function e_({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+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return a.startsWith(s)}o(e_,"checkResourceAllowed");var pe=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}},No=class extends pe{static{o(this,"InvalidRequestError")}};No.errorCode="invalid_request";var Or=class extends pe{static{o(this,"InvalidClientError")}};Or.errorCode="invalid_client";var Ur=class extends pe{static{o(this,"InvalidGrantError")}};Ur.errorCode="invalid_grant";var Nr=class extends pe{static{o(this,"UnauthorizedClientError")}};Nr.errorCode="unauthorized_client";var $o=class extends pe{static{o(this,"UnsupportedGrantTypeError")}};$o.errorCode="unsupported_grant_type";var zo=class extends pe{static{o(this,"InvalidScopeError")}};zo.errorCode="invalid_scope";var Mo=class extends pe{static{o(this,"AccessDeniedError")}};Mo.errorCode="access_denied";var Mt=class extends pe{static{o(this,"ServerError")}};Mt.errorCode="server_error";var Do=class extends pe{static{o(this,"TemporarilyUnavailableError")}};Do.errorCode="temporarily_unavailable";var qo=class extends pe{static{o(this,"UnsupportedResponseTypeError")}};qo.errorCode="unsupported_response_type";var Lo=class extends pe{static{o(this,"UnsupportedTokenTypeError")}};Lo.errorCode="unsupported_token_type";var jo=class extends pe{static{o(this,"InvalidTokenError")}};jo.errorCode="invalid_token";var Ho=class extends pe{static{o(this,"MethodNotAllowedError")}};Ho.errorCode="method_not_allowed";var Go=class extends pe{static{o(this,"TooManyRequestsError")}};Go.errorCode="too_many_requests";var $r=class extends pe{static{o(this,"InvalidClientMetadataError")}};$r.errorCode="invalid_client_metadata";var Bo=class extends pe{static{o(this,"InsufficientScopeError")}};Bo.errorCode="insufficient_scope";var Vo=class extends pe{static{o(this,"InvalidTargetError")}};Vo.errorCode="invalid_target";var t_={[No.errorCode]:No,[Or.errorCode]:Or,[Ur.errorCode]:Ur,[Nr.errorCode]:Nr,[$o.errorCode]:$o,[zo.errorCode]:zo,[Mo.errorCode]:Mo,[Mt.errorCode]:Mt,[Do.errorCode]:Do,[qo.errorCode]:qo,[Lo.errorCode]:Lo,[jo.errorCode]:jo,[Ho.errorCode]:Ho,[Go.errorCode]:Go,[$r.errorCode]:$r,[Bo.errorCode]:Bo,[Vo.errorCode]:Vo};var Dt=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function _x(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(_x,"isClientAuthMethod");var Vd="code",Fd="S256";function yx(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_x(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(yx,"selectClientAuthMethod");function wx(e,t,r,n){let{client_id:a,client_secret:s}=t;switch(e){case"client_secret_basic":Sx(a,s,r);return;case"client_secret_post":vx(a,s,n);return;case"none":bx(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(wx,"applyClientAuthentication");function Sx(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(Sx,"applyBasicAuth");function vx(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(vx,"applyPostAuth");function bx(e,t){t.set("client_id",e)}o(bx,"applyPublicAuth");async function n_(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Xg.parse(JSON.parse(r)),{error:a,error_description:s,error_uri:i}=n,c=t_[a]||Mt;return new c(s||"",i)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Mt(a)}}o(n_,"parseErrorResponse");async function pr(e,t){try{return await Zd(e,t)}catch(r){if(r instanceof Or||r instanceof Nr)return await e.invalidateCredentials?.("all"),await Zd(e,t);if(r instanceof Ur)return await e.invalidateCredentials?.("tokens"),await Zd(e,t);throw r}}o(pr,"auth");async function Zd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:s}){let i=await e.discoveryState?.(),c,d,p,l=a;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(d=i.authorizationServerUrl,c=i.resourceMetadata,p=i.authorizationServerMetadata??await a_(d,{fetchFn:s}),!c)try{c=await o_(t,{resourceMetadataUrl:l},s)}catch{}(p!==i.authorizationServerMetadata||c!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let T=await Ax(t,{resourceMetadataUrl:l,fetchFn:s});d=T.authorizationServerUrl,p=T.authorizationServerMetadata,c=T.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await Rx(t,e,c),h=n||c?.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 T=p?.client_id_metadata_document_supported===!0,U=e.clientMetadataUrl;if(U&&!Wd(U))throw new $r(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${U}`);if(T&&U)_={client_id:U},await e.saveClientInformation?.(_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Be=await Ux(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:s});await e.saveClientInformation(Be),_=Be}}let w=!e.redirectUrl;if(r!==void 0||w){let T=await Ox(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}let y=await e.tokens();if(y?.refresh_token)try{let T=await kx(d,{metadata:p,clientInformation:_,refreshToken:y.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof pe)||T instanceof Mt))throw T}let S=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:b}=await Px(d,{metadata:p,clientInformation:_,state:S,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(v),"REDIRECT"}o(Zd,"authInternal");function Wd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Wd,"isHttpsUrl");async function Rx(e,t,r){let n=Qg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!e_({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(Rx,"selectResourceURL");function Jd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=Kd(e,"resource_metadata")||void 0,s;if(a)try{s=new URL(a)}catch{}let i=Kd(e,"scope")||void 0,c=Kd(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:c}}o(Jd,"extractWWWAuthenticateParams");function Kd(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(Kd,"extractFieldFromWwwAuth");async function o_(e,t,r=fetch){let n=await Cx(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 js.parse(await n.json())}o(o_,"discoverOAuthProtectedResourceMetadata");async function Yd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Yd(e,void 0,r):void 0;throw n}}o(Yd,"fetchWithCorsRetry");function Ix(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(Ix,"buildWellKnownPath");async function r_(e,t,r=fetch){return await Yd(e,{"MCP-Protocol-Version":t},r)}o(r_,"tryMetadataDiscovery");function Tx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(Tx,"shouldAttemptFallback");async function Cx(e,t,r,n){let a=new URL(e),s=n?.protocolVersion??Vt,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let d=Ix(t,a.pathname);i=new URL(d,n?.metadataServerUrl??a),i.search=a.search}let c=await r_(i,s,r);if(!n?.metadataUrl&&Tx(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await r_(d,s,r)}return c}o(Cx,"discoverMetadataWithFallback");function Ex(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(Ex,"buildDiscoveryUrls");async function a_(e,{fetchFn:t=fetch,protocolVersion:r=Vt}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=Ex(e);for(let{url:s,type:i}of a){let c=await Yd(s,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 ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?ko.parse(await c.json()):Hs.parse(await c.json())}}}o(a_,"discoverAuthorizationServerMetadata");async function Ax(e,t){let r,n;try{r=await o_(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 a_(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(Ax,"discoverOAuthServerInfo");async function Px(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:s,resource:i}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Vd))throw new Error(`Incompatible auth server: does not support response type ${Vd}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Fd))throw new Error(`Incompatible auth server: does not support code challenge method ${Fd}`)}else c=new URL("/authorize",e);let d=await Gd(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",Vd),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",Fd),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),i&&c.searchParams.set("resource",i.href),{authorizationUrl:c,codeVerifier:p}}o(Px,"startAuthorization");function xx(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(xx,"prepareAuthorizationCodeRequest");async function s_(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:a,resource:s,fetchFn:i}){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(s&&r.set("resource",s.href),a)await a(d,r,c,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],m=yx(n,l);wx(m,n,d,r)}let p=await(i??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await n_(p);return Oo.parse(await p.json())}o(s_,"executeTokenRequest");async function kx(e,{metadata:t,clientInformation:r,refreshToken:n,resource:a,addClientAuthentication:s,fetchFn:i}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await s_(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:s,resource:a,fetchFn:i});return{refresh_token:n,...d}}o(kx,"refreshAuthorization");async function Ox(e,t,{metadata:r,resource:n,authorizationCode:a,fetchFn:s}={}){let i=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(i)),!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=xx(a,p,e.redirectUrl)}let d=await e.clientInformation();return s_(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}o(Ox,"fetchToken");async function Ux(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:a}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i=await(a??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await n_(i);return Uo.parse(await i.json())}o(Ux,"registerClient");var Nx=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),$x=[{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 i_(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(i_,"parseIpv4Octets");function zx([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(zx,"ipv4RangeMatches");function c_(e){let t=i_(e);return t!==void 0&&$x.some(r=>zx(t,r))}o(c_,"isPrivateIpv4");function Xd(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(Xd,"parseIpv6Word");function Mx(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(Mx,"formatIpv4FromWords");function Dx(e){let t=e.slice(7),r=i_(t);if(r!==void 0)return r.join(".");let[n,a,s]=t.split(":"),i=Xd(n),c=Xd(a);return s===void 0&&i!==void 0&&c!==void 0?Mx(i,c):void 0}o(Dx,"parseIpv6MappedIpv4");function qx(e){return Xd(e.split(":").find(Boolean))}o(qx,"readFirstIpv6Hextet");function Lx(e){let t=rt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=Dx(t);return n===void 0||c_(n)}let r=qx(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(Lx,"isPrivateIpv6");function Qd(e){let t=rt(e);return Nx.has(t)||t.endsWith(".internal")||c_(t)||Lx(t)}o(Qd,"isBlockedOutboundHostname");function u_(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);let r=Ue(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=rt(t.hostname);if(!r&&Qd(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(u_,"validateConfiguredOutboundUrl");function d_(e){let t=new URL(e);if(t.protocol!=="https:")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 r=rt(t.hostname);if(Qd(r))throw g("invalid_request",`Blocked identity provider host: ${r}`);return t}o(d_,"validateIdentityProviderUrl");function Gs(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(Qd(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(Gs,"validateCimdClientMetadataUrl");function l_(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(l_,"mergeAbortSignals");async function jx(e){try{await e.cancel()}catch{}}o(jx,"cancelReader");async function Bs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],a=0,s=await r.read();for(;!s.done;){let d=s.value;if(a+=d.byteLength,a>t.maxBytes)throw await jx(r),t.createLimitError();n.push(d),s=await r.read()}let i=new Uint8Array(a),c=0;for(let d of n)i.set(d,c),c+=d.byteLength;return i}o(Bs,"readBoundedByteStream");var Hx=2,Gx=1024*1024,Bx=1e4,Vx=new Set([301,302,303,307,308]),Fx=["authorization","proxy-authorization","cookie","cookie2"];function el(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(el,"readRequestUrl");function In(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(In,"readRequestMethod");function Zx(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(Zx,"assertContentLengthWithinLimit");async function Kx(e,t,r){return Zx(e,t,r),Bs(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(Kx,"readBoundedResponseBody");function Wx(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(Wx,"responseFromBufferedBody");function Jx(e,t){if(!Vx.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(Jx,"resolveRedirectUrl");function p_(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(p_,"validateOutboundUrl");function Yx(e,t){throw ae(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(Yx,"normalizeFetchError");function Fo(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&&Re(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Fo,"logOutboundFailure");async function Xx(e,t,r,n,a,s,i){let c=In(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Fo(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:et(s),error:d,extra:{abortReason:i()}}),Yx(d,a)}}o(Xx,"fetchWithNormalizedError");function Qx(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(Qx,"assertRedirectAllowed");function ek(e,t){let r=new Headers(e);for(let n of Fx)r.delete(n);for(let n of t)r.delete(n);return r}o(ek,"stripCrossOriginHeaders");function tk(e,t,r,n,a){let s={...e,method:t,redirect:"manual",signal:r};return n&&(s.headers=ek(e.headers,a)),s}o(tk,"buildRedirectInit");function rk(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(rk,"buildInitialRequestInit");function nk(e){let t=In(e.currentInput,e.currentInit);Qx({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=p_(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),a=r.origin!==n.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:tk(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(nk,"followRedirect");async function tl(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??Hx,s=r.maxResponseBytes??Gx,i=r.timeoutMs??Bx,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=l_(l,t.signal),h=!1,_=setTimeout(()=>{h=!0,l.abort()},i),w=e,y=rk(e,t,l.signal),S;try{S=p_(el(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw Fo(p,{event:"outbound_url_blocked",problemCode:n,method:In(e,t),host:et(el(e)),error:b}),clearTimeout(_),m?.(),b}let v=0;try{for(;;){let b=await Xx(p,c,w,y,n,S,()=>h?`timeout_after_${i}ms`:void 0),T=Jx(b,S);if(T!==void 0)try{let U=nk({currentInput:w,currentInit:y,currentUrl:S,redirectUrl:T,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});w=U.currentInput,y=U.currentInit,S=U.currentUrl,v=U.redirects;continue}catch(U){throw Fo(p,{event:"outbound_redirect_blocked",problemCode:n,method:In(w,y),host:et(S),error:U,extra:{redirects:v,maxRedirects:a,redirectTargetHost:et(T)}}),U}try{return Wx(b,await Kx(b,s,n))}catch(U){throw Fo(p,{event:"outbound_response_size_exceeded",problemCode:n,method:In(w,y),host:et(S),error:U,extra:{maxResponseBytes:s,status:b.status}}),U}}}finally{clearTimeout(_),m?.()}}o(tl,"runSafeOutboundExchange");async function rl(e,t,r){let n=await tl(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Fo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:In(e,t),host:et(el(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(rl,"runSafeOutboundJsonExchange");function Vs(e,t={},r={}){return tl(e,t,{...r,validateUrl:u_})}o(Vs,"fetchConfiguredOutbound");function m_(e,t={},r={}){return rl(e,t,{...r,validateUrl:d_})}o(m_,"fetchIdentityProviderJson");function f_(e,t={},r={}){return rl(e,t,{...r,validateUrl:Gs})}o(f_,"fetchCimdClientMetadataJson");W();function nl(e){return`Zuplo MCP Gateway - ${e}`}o(nl,"buildGatewayOAuthClientName");function h_(e,t){let r=new URL(e,Q(t));return Ue(r)&&rt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(h_,"buildGatewayOAuthRedirectUri");function ol(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(ol,"buildOAuthClientMetadataDocumentUrl");function g_(e){return Q(e)}o(g_,"requireOAuthClientMetadataOrigin");function __(e,t,r){let n=Ge(t),a=xr(t,r);return{client_id:ol({origin:e,upstreamServerId:t,authProfileId:r}),client_name:nl(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(__,"buildOAuthClientMetadataDocument");var ok=u.union([Uo,Bd]),ak=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:js.optional(),authorizationServerMetadata:u.union([ko,Hs]).optional()}).passthrough(),sk="Bearer";function ik(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(ik,"splitScopes");function ck(e){return ws.parse(e)}o(ck,"parsePkceCodeVerifier");function uk(e){if(typeof e.expires_in=="number")return K(new Date(Date.now()+e.expires_in*1e3))}o(uk,"readTokenExpiry");async function y_(e){if(e!==void 0)return kr(JSON.stringify(e))}o(y_,"encryptJson");async function w_(e,t){if(!e)return;let r=await zt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(w_,"decryptJson");function dk(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(dk,"toOAuthDiscoveryState");function lk(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(lk,"clientInformationAllowsRedirectUri");function pk(e,t,r){let n=Ge(e),a=xr(e,t),s;return a.scopes.length>0&&(s=a.scopes.join(a.scopeDelimiter)),{client_name:nl(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:s,token_endpoint_auth_method:"none"}}o(pk,"buildOAuthClientMetadata");function mk(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 Uo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(mk,"buildManualOAuthClientInformation");function fk(e,t,r){let n=ol({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return Wd(n)?n:void 0}o(fk,"buildClientMetadataUrl");function S_(e){for(let t of e)if(t!==void 0)return t}o(S_,"firstDefined");function hk(e){let t=xr(e.target.upstreamServerId,e.target.authProfileId),r=pk(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:mk({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=fk(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(hk,"buildInitialOAuthClientSetup");function gk(e,t){if(t===void 0)return S_([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(gk,"readEncryptedClientInformation");function _k(e){return S_([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(_k,"readEncryptedDiscoveryState");var zr=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=hk({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=gk(t,this.configuredClientInformation),this.encryptedDiscoveryState=_k(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return zg({id:t.id,...xo({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 y_(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await y_(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Oo.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??xs(),tenantId:this.target.owner.tenantId,ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await kr(r.access_token),encryptedRefreshToken:r.refresh_token?await kr(r.refresh_token):void 0,scopes:ik(r.scope??this.clientMetadataValue.scope),expiresAt:uk(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="tenant_shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await H().upstreamConnectionRepository.upsert(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:ck(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",s=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(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:yg(),...xo({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:K(new Date(Date.now()+Ug)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="tenant_shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await H().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 w_(this.encryptedClientInformation,ok)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!lk(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=dk(await w_(this.encryptedDiscoveryState,ak))}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=Oo.parse({access_token:await zt(this.connection.encryptedAccessToken),token_type:sk,refresh_token:this.connection.encryptedRefreshToken?await zt(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,tenantId:this.connection.tenantId,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 H().upstreamConnectionRepository.upsert(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var yk=1e4,wk=256*1024,Sk=2;function vk(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(vk,"hasUsableAccessToken");var bk="does not support dynamic client registration";function Rk(e){return e instanceof Error&&e.message.includes(bk)}o(Rk,"isDynamicClientRegistrationUnsupported");function Ik(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(Ik,"readOAuthFetchRequest");function Tk(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(Tk,"responseLooksJson");function v_(e){return async(t,r)=>{let n=Ik(t),a=await Vs(t,r,{maxRedirects:Sk,maxResponseBytes:wk,problemCode:"upstream_token_exchange_failed",timeoutMs:yk}),s=await a.clone().text();if(!Tk(a,s))return a;try{JSON.parse(s)}catch(i){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,i)}return a}}o(v_,"createUpstreamOAuthFetch");async function b_(e,t){try{return await pr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:v_(t.upstreamServerId)})}catch(r){throw Rk(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(b_,"runUpstreamOAuth");async function Ck(e,t){return pr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:v_(t.upstreamServerId)})}o(Ck,"exchangeUpstreamAuthorizationCode");async function R_(e,t){let r=await b_(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(R_,"requireUpstreamAuthorizationRedirect");async function I_(e){if(vk(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await b_(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 kk({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(I_,"authorizeUpstreamOAuthSession");async function Ek(e){let t=await Ms(e.stateToken),r=await H().oauthStateStore.consumeForCallback(t.id),n=Ak(r);return Pk({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),xk(n),n}o(Ek,"consumeStoredCallbackState");function Ak(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(Ak,"readConsumedCallbackState");function Pk(e){if(![e.storedState.tenantId===e.signedState.tenantId,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(Pk,"assertStoredCallbackStateMatches");function xk(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(xk,"assertStoredCallbackStateFresh");async function kk(e){if(e.owner.mode==="tenant_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),Lg(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(kk,"buildOAuthConnectRequiredResponse");async function T_(e){let t=await Ek({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Sn(t),n=await H().upstreamConnectionRepository.get(r,t.upstreamServerId,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 s=new zr(a),i=await Ck(s,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(i==="AUTHORIZED")return t;throw i!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${i}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(T_,"finishUpstreamOAuthCallback");async function C_(e){let t=Ge(e.upstreamServerId),r=xr(e.upstreamServerId,e.authProfileId),n=h_(r.redirectPath,e.request.url),a=await H().upstreamConnectionRepository.get(e.owner,e.upstreamServerId,e.authProfileId);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:Q(e.request.url)}}}o(C_,"prepareUpstreamOAuthRequest");async function E_(e){let t=await C_(e),r=new zr({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return R_(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(E_,"startUpstreamConnect");async function A_(e){let t=await C_(e),r=new zr({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return I_({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(A_,"authorizeUpstreamRequest");function Ok(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(Ok,"resolveStaticSecretCredential");async function P_(e){let{routeAuth:t}=e;switch(t.authMode){case"tenant_shared_oauth":case"user_oauth":return A_({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId});case"tenant_static_secret":return Fg({owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId});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:Ok(n.secret,t.upstreamServerId)}}case"user_static_secret":return Wg({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(P_,"resolveUpstreamCredentialForRoute");async function x_(e){let t=ur(e.principal.tenantId,e.principal.subjectId),r=tt().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user_static_secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await Ls({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(x_,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function k_(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=vt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await E_(r);break;case"user_static_secret_capture":t=await Jg(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(k_,"startUpstreamConnectForRequest");async function O_(e){let r=(await Ms(e.callbackRequest.state)).authProfileId,n=ir({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(vt(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return T_({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Ge(e.callbackRequest.upstreamServerId)})}o(O_,"finishUpstreamCallbackForRequest");var Fs=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=Kt,n){let a=this._client,s={...n,task:n?.task??(a.isToolTask(t.name)?{}:void 0)},i=a.requestStream({method:"tools/call",params:t},r,s),c=a.getToolOutputValidator(t.name);for await(let d of i){if(d.type==="result"&&c){let p=d.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new E(A.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 E(A.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof E){yield{type:"error",error:l};return}yield{type:"error",error:new E(A.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 Zs(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 s=n[a];r[a]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[a]=s.default),r[a]!==void 0&&Zs(s,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Zs(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Zs(r,t)}}o(Zs,"applyElicitationDefaults");function Uk(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(Uk,"getSupportedElicitationModes");var Ks=class extends Fr{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 dn,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Wi,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Fi,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Mi,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Fs(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_a(this._capabilities,t)}setRequestHandler(t,r){let a=jr(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let s;if(Gt(a)){let c=a;s=c._zod?.def?.value??c.value}else{let c=a;s=c._def?.value??c.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let c=o(async(d,p)=>{let l=xe(Xi,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new E(A.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:_}=Uk(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new E(A.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!_)throw new E(A.InvalidParams,"Client does not support URL-mode elicitation requests");let w=await Promise.resolve(r(d,p));if(m.task){let b=xe(At,w);if(!b.success){let T=b.error instanceof Error?b.error.message:String(b.error);throw new E(A.InvalidParams,`Invalid task creation result: ${T}`)}return b.data}let y=xe(Wt,w);if(!y.success){let b=y.error instanceof Error?y.error.message:String(y.error);throw new E(A.InvalidParams,`Invalid elicitation result: ${b}`)}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{Zs(v,S.content)}catch{}return S},"wrappedHandler");return super.setRequestHandler(t,c)}if(i==="sampling/createMessage"){let c=o(async(d,p)=>{let l=xe(Yi,d);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new E(A.InvalidParams,`Invalid sampling request: ${S}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let S=xe(At,h);if(!S.success){let v=S.error instanceof Error?S.error.message:String(S.error);throw new E(A.InvalidParams,`Invalid task creation result: ${v}`)}return S.data}let w=m.tools||m.toolChoice?Bn:gr,y=xe(w,h);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new E(A.InvalidParams,`Invalid sampling result: ${S}`)}return y.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:Vt,capabilities:this._capabilities,clientInfo:this._clientInfo}},Pi,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Ft.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){ts(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&rs(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Et,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Qi,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Et,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Vi,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},qi,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Oi,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Ui,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},zi,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Et,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Et,r)}async callTool(t,r=Kt,n){if(this.isToolTaskRequired(t.name))throw new E(A.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),s=this.getToolOutputValidator(t.name);if(s){if(!a.structuredContent&&!a.isError)throw new E(A.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(a.structuredContent)try{let i=s(a.structuredContent);if(!i.valid)throw new E(A.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof E?i:new E(A.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}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},Ki,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let s=lp.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:c}=s.data,{onChanged:d}=n,p=o(async()=>{if(!i){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 Ws(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(Ws,"normalizeHeaders");function U_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...Ws(t.headers),...Ws(n.headers)}:t.headers};return e(r,a)}:e}o(U_,"createFetchWithInit");var Js=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 al(e){}o(al,"noop");function N_(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=al,onError:r=al,onRetry:n=al,onComment:a}=e,s="",i=!0,c,d="",p="";function l(y){let S=i?y.replace(/^\xEF\xBB\xBF/,""):y,[v,b]=Nk(`${s}${S}`);for(let T of v)m(T);s=b,i=!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),b=y[S+1]===" "?2:1,T=y.slice(S+b);h(v,T,y);return}h(y,"",y)}o(m,"parseLine");function h(y,S,v){switch(y){case"event":p=S;break;case"data":d=`${d}${S}
810
- `;break;case"id":c=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new Js(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:v}));break;default:r(new Js(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:S,line:v}));break}}o(h,"processField");function _(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
811
- `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(_,"dispatchEvent");function w(y={}){s&&y.consume&&m(s),i=!0,c=void 0,d="",p="",s=""}return o(w,"reset"),{feed:l,reset:w}}o(N_,"createParser");function Nk(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),s=e.indexOf(`
812
- `,n),i=-1;if(a!==-1&&s!==-1?i=Math.min(a,s):a!==-1?a===e.length-1?i=-1:i=a:s!==-1&&(i=s),i===-1){r=e.slice(n);break}else{let c=e.slice(n,i);t.push(c),n=i+1,e[n-1]==="\r"&&e[n]===`
813
- `&&n++}}return[t,r]}o(Nk,"splitLines");var Ys=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(s){a=N_({onEvent:o(i=>{s.enqueue(i)},"onEvent"),onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:r,onComment:n})},transform(s){a.feed(s)}})}};var $k={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},mr=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Xs=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=U_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$k}async _authThenStart(){if(!this._authProvider)throw new Dt("No auth provider");let t;try{t=await pr(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 Dt;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=Ws(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 mr(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(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},a)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:a,replayMessageId:s}=r,i,c=!1,d=!1;o(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ys({onRetry:o(_=>{this._serverRetryMs=_},"onRetry")})).getReader();for(;;){let{value:_,done:w}=await l.read();if(w)break;if(_.id&&(i=_.id,c=!0,a?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let y=hr.parse(JSON.parse(_.data));nt(y)&&(d=!0,s!==void 0&&(y.id=s)),this.onmessage?.(y)}catch(y){this.onerror?.(y)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:s},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:i,onresumptiontoken:a,replayMessageId:s},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 Dt("No auth provider");if(await pr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Dt("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:mt(t)?t.id:void 0}).catch(h=>this.onerror?.(h));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,i),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 mr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:w}=Jd(c);if(this._resourceMetadataUrl=_,this._scope=w,await pr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Dt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:w,error:y}=Jd(c);if(y==="insufficient_scope"){let S=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new mr(403,"Server returned 403 after trying upscoping");if(w&&(this._scope=w),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=S??void 0,await pr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Dt;return this.send(t)}}throw new mr(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),op(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(),_=Array.isArray(h)?h.map(w=>hr.parse(w)):[hr.parse(h)];for(let w of _)this.onmessage?.(w)}else throw await c.body?.cancel(),new mr(-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 mr(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 $_(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($_,"resolveNativeMcpRequestHeaders");var zk={name:"zuplo-mcp-gateway",version:"0.1.0"},Mk=5,Dk=500,D_=3e4,qk=2*1024*1024,Lk=2;function z_(){return performance.now()/1e3}o(z_,"nowSeconds");function jk(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(jk,"readServerPort");function Hk(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:jk(e)}}o(Hk,"buildNativeMcpOperationContext");function Tn(e){return Uh(e)}o(Tn,"withTraceMeta");function sl(e){if(e>Dk)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(sl,"assertImportedCapabilityBudget");function M_(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(M_,"buildRequestInit");function Gk(e){return(t,r)=>Vs(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:Lk,maxResponseBytes:qk,problemCode:"upstream_capability_invocation_failed",timeoutMs:D_})}o(Gk,"createNativeMcpFetch");function Bk(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},D_);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(Bk,"withNativeMcpRequestTimeout");function Vk(e,t=[]){let r=$_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],s={fetch:Gk(a)};if(!e)return{...s,...M_(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...s,...M_(r)};case"bearer_token":return{...s,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...s,requestInit:{headers:{...r,...e.headers}}}}}o(Vk,"buildNativeMcpTransportOptions");async function Cn(e,t,r){let{transport:n}=Ge(e),a=new URL(n.baseUrl),s=new Xs(a,Vk(r,n.requestHeaders)),i=new Ks(zk,{capabilities:{}});return Bk((async()=>{let c=z_();await i.connect(s);let d=s.sessionId,p=Hk(a,d);try{return await t(i,p)}finally{if(s.sessionId)try{await s.terminateSession()}catch{}await i.close(),d&&Nh(p,z_()-c)}})())}o(Cn,"withNativeMcpClient");async function Fk(e,t,r){let n=[],a,s=0;do{if(s>=Mk)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let i=await t(a);s+=1,n.push(...r(i)),a=i.nextCursor}while(a);return n}o(Fk,"collectPaginatedSdkItems");async function il(e){return e.enabled?Fk(e.label,e.fetchPage,e.readItems):[]}o(il,"listNativeMcpCapabilityItems");async function q_(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ar({methodName:"tools/list",...r},()=>il({enabled:!!n?.tools,label:"Tool list",fetchPage:o(s=>t.listTools(Tn(s?{cursor:s}:void 0)),"fetchPage"),readItems:o(s=>s.tools,"readItems")}));return sl(a.length),{tools:a}},e.credential)}o(q_,"listNativeMcpTools");async function L_(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ar({methodName:"prompts/list",...r},()=>il({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(s=>t.listPrompts(Tn(s?{cursor:s}:void 0)),"fetchPage"),readItems:o(s=>s.prompts,"readItems")}));return sl(a.length),{prompts:a}},e.credential)}o(L_,"listNativeMcpPrompts");async function j_(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ar({methodName:"resources/list",...r},()=>il({enabled:!!n?.resources,label:"Resource list",fetchPage:o(s=>t.listResources(Tn(s?{cursor:s}:void 0)),"fetchPage"),readItems:o(s=>s.resources,"readItems")}));return sl(a.length),{resources:a}},e.credential)}o(j_,"listNativeMcpResources");async function H_(e){return Cn(e.upstreamServerId,(t,r)=>Ar({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(Tn(e.params))),e.credential)}o(H_,"callNativeMcpTool");async function G_(e){return Cn(e.upstreamServerId,(t,r)=>Ar({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(Tn(e.params))),e.credential)}o(G_,"getNativeMcpPrompt");async function B_(e){return Cn(e.upstreamServerId,(t,r)=>Ar({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(Tn(e.params))),e.credential)}o(B_,"readNativeMcpResource");var Zo=class extends E{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(A.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function Zk(e){return{content:[{type:"text",text:e}],isError:!0}}o(Zk,"buildToolErrorResult");function Kk(e){return e.authUrl?new Bt([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new Zo(e)}o(Kk,"toConnectRequiredError");function Wk(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(Wk,"buildCredentialResolvedAttributes");function Jk(e){He(e.context,{eventType:L.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Wk(e.credential)})}o(Jk,"emitCredentialResolvedAnalyticsEvent");function Yk(e){He(e.context,{eventType:L.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(Yk,"emitCredentialMissingAnalyticsEvent");function Xk(e){let t=new Map;return r=>{let n=`${r.upstreamServerId}:${r.authProfileId}:${r.ownerMode}`,a=t.get(n);if(a)return a;let s=(async()=>{let i=await P_({request:e.request,routeAuth:r});if(i.kind==="connect_required")throw Yk({context:e.context,payload:i.payload,routeBinding:r}),Kk(i.payload);return Jk({context:e.context,credential:i.credential,routeBinding:r}),i.credential})();return t.set(n,s),s}}o(Xk,"createCredentialResolver");var V_=500;function Qk(e){return e.length<=V_?e:`${e.slice(0,V_)}...`}o(Qk,"truncateAnalyticsDetail");function eO(e){He(e.context,{eventType:L.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(eO,"emitToolInvocationCompletedAnalyticsEvent");function tO(e){return e instanceof Bt||e instanceof Zo?{eventType:L.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof E&&e.code===A.InvalidParams?{eventType:L.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:L.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(tO,"classifyToolInvocationFailure");function rO(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=tO(e.error);He(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:Qk(t)}})}o(rO,"emitToolInvocationFailedAnalyticsEvent");var nO=256*1024;function oO(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new E(A.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>nO)throw new E(A.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(oO,"assertToolArgumentsWithinLimit");function cl(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 E(A.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(cl,"findBindingForPublishedCapability");function En(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new E(A.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(En,"requireSingleTransparentBinding");function aO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:En(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new E(A.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:cl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(aO,"resolvePublishedToolRoute");function sO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:En(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new E(A.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:cl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(sO,"resolvePublishedPromptRoute");function iO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:En(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new E(A.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:cl({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(iO,"resolvePublishedResourceRoute");function F_(e){let t=Xk({context:e.context,request:e.request});return{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{tools:e.publishedVirtualServer.catalog.tools.filter(n=>n.enabled!==!1).map(ms)};let r=En(e);return q_({upstreamServerId:r.upstreamServerId,credential:await t(r)})},async callTool(r){let n=aO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:r.name});try{oO(r);let a=await t(n.binding),s=await H_({upstreamServerId:n.binding.upstreamServerId,params:{...r,name:n.upstreamName},credential:a});return eO({context:e.context,routeBinding:n.binding,toolName:r.name,result:s}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:r.name,upstreamName:n.upstreamName,upstreamServerId:n.binding.upstreamServerId,authProfileId:n.binding.authProfileId,isError:s.isError===!0},"Upstream tool invocation completed"),s}catch(a){if(rO({context:e.context,routeBinding:n.binding,toolName:r.name,error:a}),a instanceof Bt||a instanceof Zo)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:r.name,upstreamServerId:n.binding.upstreamServerId,authProfileId:n.binding.authProfileId,ownerMode:n.binding.ownerMode,hasAuthUrl:a instanceof Bt},"Upstream tool invocation requires user to complete a connect flow"),a;let s={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:r.name,upstreamName:n.upstreamName,upstreamServerId:n.binding.upstreamServerId,authProfileId:n.binding.authProfileId};return a instanceof E&&(s.mcpErrorCode=a.code),a instanceof Error?(s.errorName=a.name,s.errorMessage=a.message,a.cause instanceof Error&&(s.causeName=a.cause.name,s.causeMessage=a.cause.message)):s.errorMessage=String(a),e.context.log.warn(s,"Upstream tool invocation failed; returning generic gateway error to MCP client"),Zk(Le("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{prompts:e.publishedVirtualServer.catalog.prompts.filter(n=>n.enabled!==!1).map(fs)};let r=En(e);return L_({upstreamServerId:r.upstreamServerId,credential:await t(r)})},async getPrompt(r){let n=sO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:r.name});return G_({upstreamServerId:n.binding.upstreamServerId,params:{...r,name:n.upstreamName},credential:await t(n.binding)})},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resources:e.publishedVirtualServer.catalog.resources.filter(n=>n.enabled!==!1).map(hs)};let r=En(e);return j_({upstreamServerId:r.upstreamServerId,credential:await t(r)})},async readResource(r){let n=iO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:r.uri});return B_({upstreamServerId:n.binding.upstreamServerId,params:{...r,uri:n.upstreamUri},credential:await t(n.binding)})}}}o(F_,"createCapabilityDispatcher");var cO="0.1.0",K_="POST",uO="POST, OPTIONS";function ul(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:K_}})}o(ul,"jsonRpcMethodNotAllowedResponse");function dO(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"]=uO;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(dO,"buildOptionsResponse");function An(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(An,"readJsonRpcRequestId");function dl(e){return e&&typeof e=="object"?e.params:void 0}o(dl,"readMcpRequestParams");function Z_(e,t){return e.headers.get(t)??void 0}o(Z_,"readMcpHeader");function lO(e){return{mcpProtocolVersion:Z_(e,"mcp-protocol-version")??Er,mcpSessionId:Z_(e,"mcp-session-id")}}o(lO,"buildServerTelemetryBase");function pO(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Er),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(pO,"ensureProtocolVersionHeader");async function ll(e,t){if(e.method==="OPTIONS")return dO(e);if(e.method==="GET")return ul("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return ul("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return ul("Only POST is supported by this virtual MCP server.");let r=mn(t),n=Sh(r.virtualServerId),a=zh(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 s=lO(e),i=F_({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=Q(e.url),d=new os({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new ns(n.catalog.serverInfo??{name:r.virtualServerId,version:cO},{capabilities:{prompts:{},resources:{},tools:{}}});p.setRequestHandler(Zi,async m=>Pr({methodName:"tools/list",params:dl(m),jsonRpcRequestId:An(m),...s},()=>i.listTools())),p.setRequestHandler(Hn,async m=>Pr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:An(m),...s},()=>i.callTool(m.params))),p.setRequestHandler(Di,async m=>Pr({methodName:"prompts/list",params:dl(m),jsonRpcRequestId:An(m),...s},()=>i.listPrompts())),p.setRequestHandler(Li,async m=>Pr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:An(m),...s},()=>i.getPrompt(m.params))),p.setRequestHandler(ki,async m=>Pr({methodName:"resources/list",params:dl(m),jsonRpcRequestId:An(m),...s},()=>i.listResources())),p.setRequestHandler($i,async m=>Pr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:An(m),...s},()=>i.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return pO(l)}o(ll,"virtualServerHandler");async function mO(e,t){return Ht("handler.mcp-virtual-server"),ll(e,t)}o(mO,"McpVirtualServerHandler");import{base64url as pl}from"jose";var fO="sha256:",hO=32;function W_(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(W_,"copyToArrayBuffer");function gO(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(gO,"constantTimeEqual");function qt(){let e=crypto.getRandomValues(new Uint8Array(hO));return pl.encode(e)}o(qt,"createOpaqueToken");async function ce(e){let t=await crypto.subtle.digest("SHA-256",W_(new TextEncoder().encode(e)));return`${fO}${pl.encode(new Uint8Array(t))}`}o(ce,"hashOpaqueValue");async function J_(e){let t=await ce(e.value);return gO(t,e.expectedHash)}o(J_,"verifyOpaqueValue");async function Y_(e){let t=await crypto.subtle.digest("SHA-256",W_(new TextEncoder().encode(e)));return pl.encode(new Uint8Array(t))}o(Y_,"calculatePkceS256Challenge");function _O(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(_O,"readBearerToken");function yO(e,t,r){return je(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(yO,"gatewayAuthenticationRequiredResponse");async function wO(e,t,r){let n=await H().downstreamOAuthRepository.validateAccessToken({tokenHash:await ce(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(wO,"validateGatewayAccessToken");function SO(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(SO,"assertAccessTokenResource");function vO(e,t,r){return je(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":_n({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${oe} scope required by this MCP resource.`,scope:oe})}})}o(vO,"insufficientScopeResponse");function bO(e){return{subjectId:e.subjectId,tenantId:e.tenantId,roles:e.roles}}o(bO,"principalFromAccessToken");function RO(e){let t=ae(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"),je(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":_n({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(RO,"gatewayTokenRejectedResponse");async function ml(e,t){let r=mn(t),n=Eo(r.virtualServerId,e.url),a=_O(e),s=_n({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"),yO(e,t,s);try{let i=await wO(a,t,r.virtualServerId);if(SO({accessToken:i,resource:n,virtualServerId:r.virtualServerId},t),i.scope!==oe)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:i.scope,requiredScope:oe,virtualServerId:r.virtualServerId,clientId:i.clientId},"Gateway access token does not have the required MCP scope"),vO(e,t,r.virtualServerId);let c=bO(i);return Xh(t,c),Ju(t,c),e}catch(i){return RO({request:e,context:t,error:i,virtualServerId:r.virtualServerId})}}o(ml,"gatewayTokenInbound");var Pn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},IO="oauth-protected-resource-metadata",TO="/.well-known/oauth-protected-resource/";function CO(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(CO,"readRouteOperationId");function EO(e){return e.hasGatewayRouteContext?Pn.VIRTUAL_MCP_SERVER:e.routeOperationId===IO||e.routeOperationId===void 0&&e.routePath.startsWith(TO)?Pn.OAUTH_PROTECTED_RESOURCE_METADATA:Pn.OTHER}o(EO,"classifyAnalyticsRouteSurface");function AO(e){let t=e.route.path;return{routePath:t,routeSurface:EO({routePath:t,routeOperationId:CO(e),hasGatewayRouteContext:Ro(e)!==void 0})}}o(AO,"readAnalyticsRequestContext");function PO(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Pn.VIRTUAL_MCP_SERVER}o(PO,"isIntentionalMethodRejection");function xO(e){return PO(e)||e.response.status===401&&e.routeSurface===Pn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(xO,"classifyRequestCompletedOutcome");async function fl(e,t){let r=Date.now(),n=AO(t);return t.addResponseSendingFinalHook(a=>{let s=xO({response:a,routeSurface:n.routeSurface});He(t,{eventType:L.MCP_GATEWAY_REQUEST_COMPLETED,outcome:s,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(fl,"analyticsContextInbound");function kO(e){return e instanceof Response}o(kO,"isResponse");var X_="/mcp/";function OO(e){let t=e.route.path;if(!t.startsWith(X_))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(X_.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(OO,"readVirtualServerIdFromRoute");async function Ko(e,t){let n={virtualServerId:ge.parse(OO(t))};Rh(t,n),nh(t,n);let a=await fl(e,t);return kO(a)?a:ml(a,t)}o(Ko,"mcpOAuthInboundPolicy");var UO=o(async(e,t,r,n)=>(Ht("policy.inbound.mcp-auth0-oauth"),Ko(e,t)),"McpAuth0OAuthInboundPolicy");function NO(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 ys({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,devTenantId:e.devTenantId})}o(NO,"buildAuth0McpOAuthRuntimeConfig");var $O={policyType:"mcp-auth0-oauth-inbound",displayName:"MCP OAuth (Auth0)",getConfig(e){return NO(e)}};us($O);var zO=o(async(e,t,r,n)=>(Ht("policy.inbound.mcp-oauth"),Ko(e,t)),"McpOAuthInboundPolicy"),MO={policyType:"mcp-oauth-inbound",displayName:"MCP OAuth",getConfig(e){return ys(e)}};us(MO);function DO(e){let t=vt(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(DO,"buildRouteAuthBaseFromConnection");function ey(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=vt(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:pn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(ey,"buildRouteAuthBaseFromPolicyOptions");function ty(e,t){let n=tt().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(s=>s.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return DO({connection:a,virtualServerId:t})}o(ty,"resolveRouteAuthBase");function Q_(e,t){switch(e){case"user":return ur(t.tenantId,t.subjectId);case"tenant_shared":return Es(t.tenantId)}}o(Q_,"buildOwnerForPrincipal");function Qs(e,t){switch(e.ownerMode){case"tenant_shared":return{...e,owner:Q_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Q_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Qs,"resolveRouteAuthForPrincipal");function qO(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 is.parse(r)}o(qO,"readSingleAuthMode");function ry(e){return St.parse(e)}o(ry,"buildToolNamePrefixFromConnectionId");async function hl(e,t,r,n){let a=ps(r,n),s=qO({policyName:n,connection:a}),i=mn(t),c=ey({connection:a,virtualServerId:i.virtualServerId,authMode:s});if(c.ownerMode==="none")return fd(t,{...c,connectionPolicyName:n,toolNamePrefix:ry(a.id)}),e;let d=Yh(t);return d.tenantId?(fd(t,{...Qs(c,d),connectionPolicyName:n,toolNamePrefix:ry(a.id)}),e):je(e,t,{code:"forbidden",detail:"Upstream credentials for this virtual server require an authenticated tenant.",headers:{"WWW-Authenticate":_n({virtualServerId:i.virtualServerId,requestUrl:e.url,error:"insufficient_scope",errorDescription:"The access token is missing tenant context required by this virtual server.",scope:oe})}})}o(hl,"mcpUpstreamConnectionPolicy");var LO=o(async(e,t,r,n)=>(Ht("policy.inbound.mcp-upstream-connection"),hl(e,t,r,n)),"McpUpstreamConnectionInboundPolicy");W();W();var ny="application/json",jO="application/x-www-form-urlencoded";function HO(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(HO,"normalizeContentType");function GO(e,t){return e===t?!0:t===ny&&e.endsWith("+json")}o(GO,"contentTypeMatches");function BO(e,t){if(!t||t.length===0)return;let r=HO(e.headers.get("content-type"));if(!t.some(n=>GO(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(BO,"assertExpectedContentType");function VO(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(VO,"assertContentLengthWithinLimit");async function oy(e,t){let r=t.label??"Request body";BO(e,t.expectedContentTypes),VO(e,t.maxBytes,r);let n=await Bs(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(oy,"readBoundedTextBody");async function ay(e,t){let r=await oy(e,{...t,expectedContentTypes:[ny]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(ay,"readBoundedJsonBody");async function ei(e,t){let r=await oy(e,{...t,expectedContentTypes:[jO]});return new URLSearchParams(r)}o(ei,"readBoundedFormUrlEncodedBody");var sy=Symbol("Html");function FO(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(FO,"escapeHtml");function ZO(e){return e===null||typeof e!="object"?!1:e[sy]===!0}o(ZO,"isHtml");function iy(e){return e==null||e===!1?"":Array.isArray(e)?e.map(iy).join(""):ZO(e)?e.value:FO(String(e))}o(iy,"renderValue");function pt(e){return{[sy]:!0,value:e}}o(pt,"trustedHtml");var me=pt("");function k(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=iy(t[n]),r+=e[n+1]??"";return pt(r)}o(k,"html");function Lt(e){return e.value}o(Lt,"renderHtml");var KO="text/html; charset=utf-8";function cy(e,t=200){return new Response(Lt(e),{status:t,headers:{"content-type":KO,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(cy,"apiKeyLoginHtmlResponse");function gl(e=401){return cy(k`<!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(gl,"apiKeyLoginFailureResponse");function uy(e){return cy(k`<!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(uy,"renderApiKeyLoginForm");W();W();import{errors as Sy,jwtVerify as vy,SignJWT as by}from"jose";W();import{errors as a0,jwtVerify as s0,SignJWT as i0}from"jose";function fr(e){let t=_e().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(fr,"requireBrowserLoginField");function ti(e){if(!e.tenantId)throw g("identity_context_missing","Gateway OAuth browser login requires a tenant-scoped principal.");return{...e,tenantId:e.tenantId}}o(ti,"requireTenantScopedBrowserPrincipal");W();import{createRemoteJWKSet as WO,errors as Wo,jwtVerify as JO}from"jose";var YO=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()}),XO=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function QO(e){let t=XO.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(QO,"readIdpErrorFields");function e0(e){return e instanceof Wo.JWTExpired?"expired":e instanceof Wo.JWTClaimValidationFailed?"claim":e instanceof Wo.JWSSignatureVerificationFailed?"signature":e instanceof Wo.JWKSNoMatchingKey?"jwks_no_match":e instanceof Wo.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(e0,"readJwtFailureKind");var t0=u.object({sub:le,nonce:u.string().min(1)}).catchall(u.unknown()),_l;function r0(e){return e instanceof Error&&"cause"in e?e.cause:e}o(r0,"readErrorCause");function n0(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(n0,"readRuntimeGatewayCode");function o0(){if(!_l){let e=_e();_l=WO(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return _l}o(o0,"readFederatedJwks");async function dy(e){let t=_e(),r=fr("tokenUrl"),n=fr("clientId"),a=fr("clientSecret"),s=new URL("/oauth/callback",lt(e.requestUrl)).toString(),i=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:s,client_id:n,client_secret:a});try{let{response:c,json:d}=await m_(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:i},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!c.ok){let h=QO(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:et(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=YO.parse(d),l;try{({payload:l}=await JO(p.id_token,o0(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let _={};throw Re(_,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:e0(h),idpHost:et(r),expectedIssuer:t.oidc.issuer,..._},"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:et(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=t0.parse(l);return ti(gn({sub:m.sub,data:m},e.requestUrl))}catch(c){let d=ae(c)??n0(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",r0(c))}}o(dy,"exchangeFederatedAuthorizationCode");var wl="zuplo_mcp_session",ly="HS256",py="zuplo-mcp-gateway",my="zuplo-mcp-gateway",c0=u.object({purpose:u.literal("gateway_browser_session"),sub:le,tenantId:$e,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 u0(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(),s=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(s))}catch{t.set(a,s)}}return t}o(u0,"parseCookieHeader");async function fy(){return bt({purpose:"browser-session",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>dr(e,"browser-session"),"derive")})}o(fy,"getBrowserSessionKey");function yl(e){let t=new URL(Q(e)),r=[`${wl}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(yl,"buildBrowserSessionEvictionCookie");function d0(e){let t=new URL(Q(e.requestUrl)),r=[`${wl}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(d0,"serializeSessionCookie");function hy(e={}){return new URL(fr("url")).origin}o(hy,"readBrowserLoginOrigin");function Sl(){return _e().browserLogin.stateTtlSeconds}o(Sl,"readBrowserLoginStateTtlSeconds");function gy(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ti(gn(e.user,e.url))}o(gy,"resolveCurrentRequestPrincipal");async function ri(e,t={}){let r=u0(e.headers.get("cookie")).get(wl);if(!r)return{};try{let{payload:n}=await s0(r,await fy(),{algorithms:[ly],issuer:py,audience:my}),a=c0.parse(n);if(a.browserLoginOrigin!==hy(t))return{evictCookie:yl(e.url)};let s={subjectId:a.sub,tenantId:a.tenantId};return a.roles&&a.roles.length>0&&(s.roles=a.roles),{principal:s}}catch(n){return n instanceof a0.JWTExpired?{evictCookie:yl(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:yl(e.url)})}}o(ri,"readBrowserSession");async function Jo(e){let t=_e().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,tenantId:e.principal.tenantId,browserLoginOrigin:hy({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new i0(r).setProtectedHeader({alg:ly,typ:"JWT"}).setIssuer(py).setAudience(my).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await fy());return d0({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(Jo,"createBrowserSessionCookie");async function _y(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(_y,"resolveApiKeyBrowserLoginPrincipal");async function yy(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await ri(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 dy({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(yy,"resolveBrowserLoginCallbackPrincipal");function wy(e){let t=_e().browserLogin,r=new URL(fr("url")),n=new URL("/oauth/callback",lt(e.requestUrl));return Vh(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",fr("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(wy,"buildBrowserLoginUrl");var l0=5*60,p0=["mcp_user"],ni="HS256",oi="zuplo-mcp-gateway",ai="zuplo-mcp-gateway",m0=u.object({purpose:u.literal("gateway_browser_login"),transactionId:sr,stateId:vs,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),f0=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:sr,stateId:vs,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function Ry(){return bt({purpose:"browser-login",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>dr(e,"browser-login"),"derive")})}o(Ry,"getBrowserLoginKey");async function Iy(){return bt({purpose:"authorization-csrf",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>dr(e,"authorization-csrf"),"derive")})}o(Iy,"getCsrfKey");function h0(e){return[...new Set([...p0,...e.roles??[]])]}o(h0,"buildRoles");function Ty(e){return{repository:e.repository??H().downstreamOAuthRepository,now:e.now??new Date,ttlSeconds:Sl()}}o(Ty,"readPendingTransactionDependencies");function g0(e,t){return e.subjectId===t.subjectId&&e.tenantId===t.tenantId}o(g0,"principalsMatch");function Cy(e){return{subjectId:e.subjectId,tenantId:e.tenantId,...e.roles===void 0?{}:{roles:e.roles}}}o(Cy,"toPendingPrincipal");function Ey(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:K(e.now),expiresAt:K(ar(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:Cy(e.principal)}}o(Ey,"createTransactionRecord");async function Ay(e){if((await e.repository.savePendingAuthorizationTransaction(e.record)).kind==="already_exists")throw g("oauth_state_reused","Authorization transaction state already exists.")}o(Ay,"savePendingTransaction");async function _0(e){return new by({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:ni,typ:"JWT"}).setIssuer(oi).setAudience(ai).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Ry())}o(_0,"signBrowserLoginState");async function Py(e){return new by({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Sd()}).setProtectedHeader({alg:ni,typ:"JWT"}).setIssuer(oi).setAudience(ai).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Iy())}o(Py,"signCsrfToken");async function si(e){try{let{payload:t}=await vy(e,await Ry(),{algorithms:[ni],issuer:oi,audience:ai}),r=m0.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof Sy.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(si,"verifyBrowserLoginStateToken");async function y0(e){try{let{payload:t}=await vy(e,await Iy(),{algorithms:[ni],issuer:oi,audience:ai});return{transactionId:f0.parse(t).transactionId}}catch(t){throw t instanceof Sy.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(y0,"verifyCsrfToken");function ii(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(ii,"pendingStateErrorCode");function w0(e){if(e.kind!=="available")throw g(ii(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(w0,"requireAwaitingSetup");function S0(e){if(e.kind!=="available")throw g(ii(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(S0,"requireAwaitingLogin");function v0(e){if(!g0(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(v0,"requireCurrentPrincipalMatches");async function xy(e){let t=e.repository??H().downstreamOAuthRepository,r=e.now??new Date,n=Sl(),a=wd(),s=Sd(),i=await _0({transactionId:a,stateId:s,ttlSeconds:n}),c=Ey({id:a,transaction:e.transaction,currentStateHash:await ce(i),phase:"awaiting_login",now:r,ttlSeconds:n});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return await Ay({repository:t,record:c}),{transaction:c,browserLoginStateToken:i,browserLoginUrl:wy({state:i,nonce:s,virtualServerId:c.virtualServerId,requestUrl:e.requestUrl})}}o(xy,"startAwaitingLogin");async function ky(e){let{repository:t,now:r,ttlSeconds:n}=Ty(e),a=wd(),s=await Py({transactionId:a,ttlSeconds:n}),i=Ey({id:a,transaction:e.transaction,currentStateHash:await ce(s),phase:"awaiting_setup",principal:e.principal,now:r,ttlSeconds:n});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return await Ay({repository:t,record:i}),{transaction:i,csrfToken:s}}o(ky,"startAwaitingSetup");async function vl(e){let{repository:t,now:r,ttlSeconds:n}=Ty(e),a=await si(e.browserLoginStateToken),s=await Py({transactionId:a.transactionId,ttlSeconds:n}),i=await t.advancePendingAuthorizationTransaction({id:a.transactionId,expectedPhase:"awaiting_login",currentStateHash:await ce(e.browserLoginStateToken),nextStateHash:await ce(s),nextPhase:"awaiting_setup",principal:Cy(e.principal),now:r});if(i.kind!=="advanced")throw g(ii(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:s}}o(vl,"completeLogin");async function Oy(e){let t=e.repository??H().downstreamOAuthRepository,r=e.now??new Date,n=await si(e.browserLoginStateToken);return S0(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await ce(e.browserLoginStateToken),now:r}))}o(Oy,"getAwaitingLogin");async function bl(e){let t=await Rl(e);return v0({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(bl,"getSetup");async function Rl(e){let t=e.repository??H().downstreamOAuthRepository,r=e.now??new Date,n=await y0(e.csrfToken);return w0(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await ce(e.csrfToken),now:r}))}o(Rl,"getSetupTransaction");async function b0(e){let t=qt(),r=await ce(t),n=Bh(),a=K(ar(e.now,l0)),s={id:e.transaction.id,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,tenantId:e.transaction.principal.tenantId,subjectId:e.transaction.principal.subjectId,scope:e.transaction.scope,roles:h0(e.transaction.principal),codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:K(e.now),expiresAt:a};await e.repository.issueAuthorizationCode({...s,codeHash:r,grantId:n});let i=new URL(e.transaction.redirectUri);return i.searchParams.set("code",t),e.transaction.clientState&&i.searchParams.set("state",e.transaction.clientState),i}o(b0,"createAuthorizationCodeRedirect");function R0(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(R0,"buildClientCancelRedirect");async function I0(e){let t=await bl(e),r=await e.repository.consumePendingAuthorizationTransaction({id:t.id,currentStateHash:await ce(e.csrfToken),now:e.now});if(r.kind!=="consumed")throw g(ii(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(I0,"consumeSetup");async function Uy(e){let t=e.repository??H().downstreamOAuthRepository,r=e.now??new Date;return{repository:t,now:r,transaction:await I0({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t})}}o(Uy,"consumeSetupForDecision");async function Ny(e){let{repository:t,now:r,transaction:n}=await Uy(e);return b0({repository:t,transaction:n,now:r})}o(Ny,"approve");async function $y(e){let{transaction:t}=await Uy(e);return R0({redirectUri:t.redirectUri,clientState:t.clientState})}o($y,"cancel");W();var T0={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},z=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=T0[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var C0=1e4,E0=5*1024,A0=2,P0=90*24*60*60,Il=["authorization_code","refresh_token"],Tl=["code"],x0=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(Il)).min(1).max(2).optional(),response_types:u.array(u.enum(Tl)).min(1).max(1).optional(),scope:u.literal(oe).optional(),token_endpoint_auth_method:Co.default("client_secret_basic")});function k0(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(k0,"isCimdClientIdCandidate");function Yo(e,t="invalid_request"){if(O0(e))throw new z(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new z(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new z(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||Ue(r)))throw new z(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(Yo,"assertValidRedirectUri");function O0(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(O0,"hasForbiddenRawRedirectUriCharacter");async function U0(e){let{response:t,json:r}=await f_(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:A0,maxResponseBytes:E0,timeoutMs:C0});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=qh.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(U0,"fetchCimdMetadata");async function N0(e){let t=Gs(e),r=await U0({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(N0,"resolveCimdClient");async function Xo(e,t,r){let n=Ze.parse(t),a=await e.getDcrClient(n);if(a){let s={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&&(s.hashedClientSecret=a.hashedClientSecret),s}if(!_e().gateway.cimdEnabled||!k0(n))throw new z("invalid_client",n.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.");try{return await N0(n)}catch{throw new z("invalid_client","OAuth client is not registered.")}}o(Xo,"resolveClient");function ci(e,t){if(!e.metadata.redirect_uris.some(r=>Rs(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(ci,"assertRedirectRegistered");function $0(e){let t=zy(e.grant_types),r=e.response_types??[...Tl];if(!z0(t))throw new z("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!M0(r))throw new z("invalid_client_metadata","response_types must be code.");if(!D0(e.scope))throw new z("invalid_client_metadata",`Only the ${oe} scope is supported.`)}o($0,"assertSupportedDcrRequest");function zy(e){return e===void 0?[...Il]:Array.from(new Set(e))}o(zy,"normalizeGrantTypes");function z0(e){return e.length===0?!1:e.every(t=>Il.includes(t))}o(z0,"isSupportedGrantTypes");function M0(e){return e.length===Tl.length&&e[0]==="code"}o(M0,"isSupportedResponseTypes");function D0(e){return e===void 0||e===oe}o(D0,"isSupportedDcrScope");function Qo(e){if(e===void 0||e===oe)return oe;throw new z("invalid_request",`Only the ${oe} scope is supported.`)}o(Qo,"assertSupportedOAuthScope");function xn(e,t){let r;try{r=new URL(t)}catch{throw new z("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new z("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Ue(r))throw new z("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=Q(e),a=vh(),s=a?[...a.byVirtualServerId.values()].find(i=>new URL(i.routePath,n).toString()===t):void 0;if(!s)throw new z("invalid_target","resource must match a published virtual MCP server.");return s}o(xn,"resolveResource");async function My(e,t={}){let n=(q0(t)?{repository:t}:t).repository??H().downstreamOAuthRepository,a;try{a=x0.parse(e)}catch(h){if(h instanceof u.ZodError){let _=h.issues.some(w=>w.path[0]==="redirect_uris");throw new z(_?"invalid_redirect_uri":"invalid_client_metadata",h.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:h})}throw h}$0(a);for(let h of a.redirect_uris)Yo(h,"invalid_redirect_uri");let s=new Date,i=Ze.parse(`dcr:${crypto.randomUUID()}`),c=ar(s,P0),d=Math.floor(s.getTime()/1e3),p=Math.floor(c.getTime()/1e3),l={client_id:i,client_name:a.client_name??"Dynamically registered MCP client",redirect_uris:a.redirect_uris,grant_types:zy(a.grant_types),response_types:["code"],scope:oe,token_endpoint_auth_method:a.token_endpoint_auth_method,client_id_issued_at:d},m={clientId:i,clientName:String(l.client_name),redirectUris:a.redirect_uris,tokenEndpointAuthMethod:a.token_endpoint_auth_method,createdAt:K(s),clientExpiresAt:K(c)};if(a.token_endpoint_auth_method!=="none"){let h=qt();m.hashedClientSecret=await ce(h),m.clientSecretExpiresAt=K(c),l.client_secret=h,l.client_secret_expires_at=p,l.client_secret_issued_at=d}return await n.saveDcrClient(m),l}o(My,"registerDownstreamClient");function q0(e){return typeof e.getDcrClient=="function"}o(q0,"isOAuthRepository");var L0=8;function El(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(El,"safeIconSrc");function j0(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(j0,"safeGatewayConnectHref");function H0(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(H0,"parseIconSize");function G0(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(G0,"selectIconCandidates");function B0(e){return El(e.src)?e.sizes&&e.sizes.length>0?Math.max(...e.sizes.map(H0)):0:-1}o(B0,"readIconScore");function Ly(e,t){if(!e||e.length===0)return;let r=G0(e,t),n,a=-1;for(let s of r){let i=B0(s);i>a&&(n=s,a=i)}return n}o(Ly,"pickIcon");var V0='<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>',Dy=pt(V0),F0=pt('<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>'),Z0=pt('<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>'),jy=pt('<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>'),qy=pt('<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 K0(e,t){let r=Ly(e,"light");if(!r)return k`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${Dy}</span>`;let n=El(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">${Dy}</span>`}o(K0,"renderIconFrame");function di(e,t){let r=Ly(e,"light");if(!r)return me;let n=El(r.src);return n?k`<img class="inline-icon" src="${n}" alt="${t}" loading="lazy" decoding="async">`:me}o(di,"renderInlineIcon");function W0(e){switch(e){case"user":return"your account";case"tenant_shared":return"shared by your team";case"none":return"gateway-managed"}}o(W0,"ownerModeLabel");function J0(e){return e.endsWith("_oauth")||e==="oauth"?"OAuth":e.includes("static_secret")?"static credential":e.replaceAll("_"," ")}o(J0,"authModeLabel");function Y0(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(Y0,"statusBadge");function X0(e){if(!e)return me;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>`:me}o(X0,"annotationBadges");function Hy(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(Hy,"summarizeCapabilities");function Q0(e){let t=e.annotations?.title??e.title??e.name,r=e.description?k`<span class="capability-row__description">${e.description}</span>`:me;return k`<li class="capability-row">${di(e.icons,t)}<span class="capability-row__name">${t}</span>${X0(e.annotations)}${r}</li>`}o(Q0,"renderToolRow");function eU(e){let t=e.title??e.name,r=e.description?k`<span class="capability-row__description">${e.description}</span>`:me;return k`<li class="capability-row">${di(e.icons,t)}<span class="capability-row__name">${t}</span>${r}</li>`}o(eU,"renderPromptRow");function tU(e){let t=e.title??e.name,r=e.mimeType===void 0?me:k` · ${e.mimeType}`,n=e.description===void 0?me:k` — ${e.description}`,a=k`<span class="capability-row__description"><code>${e.uri}</code>${r}${n}</span>`;return k`<li class="capability-row">${di(e.icons,t)}<span class="capability-row__name">${t}</span>${a}</li>`}o(tU,"renderResourceRow");function Cl(e,t,r,n){if(t===0)return me;let a=r.slice(0,L0),s=t-a.length,i=s>0?k`<li class="capability-row capability-row--more">+ ${s} more</li>`:me;return k`<section class="capability-section"><h4 class="capability-section__title">${e} <span class="muted">(${t})</span></h4><ul class="capability-list">${a.map(n)}${i}</ul></section>`}o(Cl,"renderCapabilitySection");function ui(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(ui,"countPill");function rU(e){let t=Hy(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(ui(t.tools===1?"tool":"tools",t.tools)),t.prompts>0&&n.push(ui(t.prompts===1?"prompt":"prompts",t.prompts)),t.resources>0&&n.push(ui(t.resources===1?"resource":"resources",t.resources)),t.destructiveTools>0&&n.push(ui("destructive",t.destructiveTools,!0));let a=[Cl("Tools",t.tools,e.tools,Q0),Cl("Prompts",t.prompts,e.prompts,eU),Cl("Resources",t.resources,e.resources,tU)];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">${jy}</span></summary><div class="capabilities-detail">${a}</div></details>`}o(rU,"renderUpstreamCapabilities");function nU(e){if(!e||e.length===0)return me;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">${jy}</span></summary><div class="scopes-list">${t}</div></details>`}o(nU,"renderUpstreamScopes");function oU(e,t){if(e.ownerMode!=="user")return me;let r=j0(e.connectUrl,t);if(!r)return me;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?me:k` title="${a}"`}>${n}</a>`}o(oU,"renderActionButton");function aU(e,t){let r=oU(e,t);return Lt(r)!==""?r:Y0(e.status)}o(aU,"renderUpstreamControl");function sU(e,t){let n=e.ownerMode==="user"&&e.status!=="active"?pt('<article class="upstream-card upstream-card--needs-action">'):pt('<article class="upstream-card">'),a=e.description?k`<p class="upstream-card__description">${e.description}</p>`:me,s=e.transportHost?k`<code class="upstream-card__host">${e.transportHost}</code><span class="upstream-card__sep" aria-hidden="true">·</span>`:me,i=k`<div class="upstream-card__head">${K0(e.serverIcons,e.upstreamDisplayName)}<div class="upstream-card__main"><div class="upstream-card__title-row"><h3 class="upstream-card__title">${e.upstreamDisplayName}</h3>${aU(e,t)}</div><div class="upstream-card__meta">${s}<span>${J0(e.authMode)}</span><span class="upstream-card__sep" aria-hidden="true">·</span><span>${W0(e.ownerMode)}</span></div>${a}</div></div>`,c=rU(e.capabilities),d=nU(e.scopesRequested);return k`${n}${i}${c}${d}</article>`}o(sU,"renderUpstreamCard");function iU(e){return e.reduce((t,r)=>{let n=Hy(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(iU,"aggregateCapabilities");function cU(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(cU,"deriveMode");function uU(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"),s=n.length===1?"the service":`the ${n.length} services`,i=a?k`Re-authorize ${s} below to refresh access. Authorization will continue automatically once each is ready.`:k`Connect ${s} below before continuing. Authorization will continue automatically once each is ready.`;return k`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${F0}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${i}</p></div></div>`}let t=iU(e.upstreams);if(t.destructiveTools===0)return me;let r=t.destructiveTools===1?"tool can":"tools can";return k`<div class="banner banner--alert" role="alert"><span class="banner__icon" aria-hidden="true">${Z0}</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(uU,"renderBanner");function dU(e){return e.mode==="grant"?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">Authorize</button></form>`:k`<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(dU,"renderActions");var lU=`
835
+ SELECT EXISTS (SELECT 1 FROM inserted_consumption) AS inserted`,[t,n,r])),"browser connect ticket consume").inserted?{kind:"available"}:{kind:"consumed"}}};var xP={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},U=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=xP[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};X();var Fg=c.object({bucketId:c.string().trim().min(1),configurationId:c.string().trim().min(1)}),Jd=c.discriminatedUnion("mode",[c.object({mode:c.literal("user"),tenantId:de,subjectId:Q}).strict(),c.object({mode:c.literal("tenant_shared"),tenantId:de}).strict()]),Zg=c.object({owner:Jd,upstreamServerId:Ee,authProfileId:Pe}).strict(),Kg=c.object({items:c.array(Zg).min(1).max(100)}).strict(),Yd=c.object({items:c.array(c.object({key:c.object({ownerMode:Ht,tenantId:de,subjectId:Q.optional(),upstreamServerId:Ee,authProfileId:Pe}).strict(),connection:Gt.strict().optional()}).strict())}).strict(),Wg=Gt.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Kd),Jg=Gt.strict(),Yg=c.object({owner:Jd,upstreamServerId:Ee,authProfileId:Pe}).strict(),Xg=c.object({owner:Jd,upstreamServerId:Ee,authProfileId:Pe,connection:Gt.strict().optional(),connectionStatus:c.object({connected:c.boolean(),status:xn,updatedAt:Gt.shape.updatedAt.optional()}).strict()}).strict(),OP=c.enum(["none","client_secret_basic","client_secret_post"]),Mr=c.object({clientId:he,clientName:c.string().min(1),tokenEndpointAuthMethod:OP}).strict(),Xd=c.discriminatedUnion("method",[c.object({method:c.literal("none"),clientId:he}).strict(),c.object({method:c.enum(["client_secret_basic","client_secret_post"]),clientId:he,clientSecretHashInput:c.string().min(1)}).strict()]),Qd=c.object({id:je,currentStateHash:c.string().min(1),clientId:he,redirectUri:c.string().min(1),resource:c.string().min(1),virtualServerId:me,clientState:c.string().optional(),scope:c.string(),codeChallenge:c.string().min(1),codeChallengeMethod:c.literal("S256"),createdAt:V,expiresAt:V,consumedAt:V.optional()}).strict(),Vg=Qd.omit({id:!0,consumedAt:!0}).extend({transactionId:je,client:Mr.optional()}).strict(),el=c.object({tenantId:de,subjectId:Q,roles:c.array(c.string()).optional()}).strict(),UP=Qd.extend({phase:c.literal("awaiting_login")}).strict(),Wd=Qd.extend({phase:c.literal("awaiting_setup"),principal:el}).strict(),zP=c.discriminatedUnion("phase",[UP,Wd]),tl=c.object({transaction:zP,client:Mr}).strict(),Qg=qi.omit({revokedAt:!0}).strict(),e_=c.discriminatedUnion("kind",[c.object({kind:c.literal("registered"),client:Mr}).strict(),c.object({kind:c.literal("already_exists")}).strict()]),t_=c.discriminatedUnion("phase",[Vg.extend({phase:c.literal("awaiting_login")}).strict(),Vg.extend({phase:c.literal("awaiting_setup"),principal:el}).strict()]),r_=c.discriminatedUnion("kind",[tl.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()]),n_=c.object({transactionId:je,currentStateHash:c.string().min(1),now:V}).strict(),o_=c.discriminatedUnion("kind",[tl.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()]),a_=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:el,now:V}).strict(),i_=c.discriminatedUnion("kind",[tl.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()]),s_=c.discriminatedUnion("decision",[c.object({decision:c.literal("approve"),transactionId:je,currentStateHash:c.string().min(1),currentPrincipal:c.object({tenantId:de,subjectId:Q}).strict(),authorizationCodeHash:c.string().min(1),authorizationCodeExpiresAt:V,grantId:yt,now:V}).strict(),c.object({decision:c.literal("cancel"),transactionId:je,currentStateHash:c.string().min(1),currentPrincipal:c.object({tenantId:de,subjectId:Q}).strict(),now:V}).strict()]),c_=c.discriminatedUnion("kind",[c.object({kind:c.literal("approved"),transaction:Wd,client:Mr}).strict(),c.object({kind:c.literal("cancelled"),transaction:Wd,client:Mr}).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()]),u_=c.object({clientAuth:Xd,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:V,accessTokenExpiresAt:V,now:V}).strict(),d_=c.discriminatedUnion("kind",[c.object({kind:c.literal("exchanged"),client:Mr,grant:Lo.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()]),l_=c.object({clientAuth:Xd,currentRefreshTokenHash:c.string().min(1),nextRefreshTokenHash:c.string().min(1),accessTokenHash:c.string().min(1),resource:c.string().min(1).optional(),accessTokenExpiresAt:V,now:V}).strict(),p_=c.discriminatedUnion("kind",[c.object({kind:c.literal("rotated"),client:Mr,grant:Lo.strict(),accessToken:Cn.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()]),m_=c.object({clientAuth:Xd,tokenHash:c.string().min(1),now:V}).strict(),h_=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()]),f_=c.object({tokenHash:c.string().min(1),now:V}).strict(),g_=c.discriminatedUnion("kind",[c.object({kind:c.literal("valid"),record:Cn.strict()}).strict(),c.object({kind:c.literal("missing")}).strict(),c.object({kind:c.literal("expired")}).strict(),c.object({kind:c.literal("revoked")}).strict()]),__=c.object({accessTokenHash:c.string().min(1),resource:c.string().min(1),virtualServerId:me,upstreamConnectionKeys:c.array(Zg).max(100),now:V}).strict(),y_=c.discriminatedUnion("kind",[c.object({kind:c.literal("authorized"),principal:c.object({tenantId:de,subjectId:Q,roles:c.array(c.string())}).strict(),accessToken:Cn.strict(),upstreamConnections:Yd.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()]),S_=c.object({record:Fo}).strict(),w_=c.object({kind:c.literal("saved")}).strict(),v_=c.object({id:Pn,now:V}).strict(),R_=c.discriminatedUnion("kind",[c.object({kind:c.literal("available"),record:Fo}).strict(),c.object({kind:c.literal("consumed")}).strict(),c.object({kind:c.literal("missing")}).strict()]),b_=c.object({id:Vo,expiresAt:V,now:V}).strict(),I_=c.discriminatedUnion("kind",[c.object({kind:c.literal("available")}).strict(),c.object({kind:c.literal("consumed")}).strict()]);var C_=100;function Y(e){return encodeURIComponent(e)}o(Y,"encodePathSegment");function T_(e){return e!==null&&typeof e=="object"}o(T_,"isProblemDetailsShape");function NP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/upstream-connections/batch-get"].join("/")}o(NP,"buildBatchGetUpstreamConnectionsPath");function DP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/upstream-connections/upsert"].join("/")}o(DP,"buildUpsertUpstreamConnectionPath");function MP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/authorization/read-setup"].join("/")}o(MP,"buildReadAuthorizationSetupPath");function qP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/oauth/register-client"].join("/")}o(qP,"buildRegisterClientPath");function $P(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/authorization/start"].join("/")}o($P,"buildStartAuthorizationPath");function LP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/authorization/read-pending"].join("/")}o(LP,"buildReadPendingAuthorizationPath");function jP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/authorization/advance-pending"].join("/")}o(jP,"buildAdvancePendingAuthorizationPath");function HP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/authorization/decide-setup"].join("/")}o(HP,"buildDecideAuthorizationSetupPath");function GP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/token/exchange-authorization-code"].join("/")}o(GP,"buildExchangeAuthorizationCodePath");function BP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/token/refresh"].join("/")}o(BP,"buildRefreshTokenPath");function VP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/token/revoke"].join("/")}o(VP,"buildRevokeOAuthTokenPath");function FP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/token/validate-access-token"].join("/")}o(FP,"buildValidateAccessTokenPath");function ZP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/mcp/authorize-and-load-connections"].join("/")}o(ZP,"buildAuthorizeAndLoadConnectionsPath");function KP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/upstream-oauth-state/save"].join("/")}o(KP,"buildSaveUpstreamOAuthStatePath");function WP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/upstream-oauth-state/consume"].join("/")}o(WP,"buildConsumeUpstreamOAuthStatePath");function JP(e){return["/zups/v2/buckets",Y(e.bucketId),"mcp/configurations",Y(e.configurationId),"storage/browser-connect-ticket/consume"].join("/")}o(JP,"buildConsumeBrowserConnectTicketPath");function YP(e,t){return e.ownerMode===t.owner.mode&&e.tenantId===t.owner.tenantId&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(YP,"responseKeyMatchesLookup");function XP(e,t){return e.owner.mode===t.owner.mode&&e.owner.tenantId===t.owner.tenantId&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(XP,"authorizationSetupMatchesLookup");function E_(e,t){return e.ownerMode===t.owner.mode&&e.tenantId===t.owner.tenantId&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(E_,"connectionMatchesLookup");function QP(e,t){return e.ownerMode===t.ownerMode&&(e.tenantId??"")===(t.tenantId??"")&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&nl(e.scopes,t.scopes)&&rl(e.expiresAt,t.expiresAt)&&tx(e.metadata,t.metadata)}o(QP,"connectionMatchesUpsertRecord");function rl(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(rl,"optionalTimestampInstantsMatch");function ex(e,t){return Date.parse(e)<=Date.parse(t)}o(ex,"timestampInstantIsAtOrBefore");function nl(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(nl,"stringArraysMatch");function tx(e,t){let r=A_(e),n=A_(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(tx,"metadataMatches");function A_(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(A_,"definedMetadataEntries");function Se(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(Se,"throwInvalidStorageResponse");async function rx(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){Se("Gateway Service storage response did not match the runtime storage contract.",r)}}o(rx,"parseRuntimeHttpStorageResponse");function P_(e,t){e.length!==t.length&&Se("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];YP(n.key,a)||Se("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!E_(n.connection,a)&&Se("Gateway Service storage response connection did not match the response key.")}}o(P_,"validateUpstreamConnectionItemsMatchLookups");function nx(e,t){XP(e,t)||Se("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!E_(e.connection,t)&&Se("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||!rl(e.connectionStatus.updatedAt,a))&&Se("Gateway Service storage response authorization setup status did not match the connection.")}o(nx,"validateAuthorizationSetupResponseMatchesLookup");function ox(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&Se("Gateway Service storage response registered client did not match the request.")}o(ox,"validateRegisterClientResponseMatchesRequest");function ax(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)&&Se("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.tenantId!==t.principal.tenantId||e.transaction.principal.subjectId!==t.principal.subjectId)&&Se("Gateway Service storage response started authorization principal did not match the request."))}o(ax,"validateStartAuthorizationResponseMatchesRequest");function k_(e,t){e.kind!=="available"&&e.kind!=="advanced"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&Se("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.tenantId!==t.principal.tenantId||e.transaction.principal.subjectId!==t.principal.subjectId)&&Se("Gateway Service storage response advanced authorization did not match the request."))}o(k_,"validatePendingAuthorizationResponseMatchesRequest");function ix(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.tenantId!==t.currentPrincipal.tenantId||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&Se("Gateway Service storage response authorization setup transaction did not match the request.")}o(ix,"validateAuthorizationSetupDecisionResponseMatchesRequest");function sx(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||!rl(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&Se("Gateway Service storage response authorization-code exchange did not match the request.")}o(sx,"validateExchangeAuthorizationCodeResponseMatchesRequest");function cx(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)&&Se("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!ex(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!lx(e.accessToken,e.grant))&&Se("Gateway Service storage response token refresh access token did not match the request."))}o(cx,"validateRefreshTokenResponseMatchesRequest");function ux(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&Se("Gateway Service storage response access token did not match the request.")}o(ux,"validateAccessTokenValidationResponseMatchesRequest");function dx(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.tenantId!==e.accessToken.tenantId||e.principal.subjectId!==e.accessToken.subjectId||!nl(e.principal.roles,e.accessToken.roles))&&Se("Gateway Service storage response MCP authorization did not match the request."),P_(e.upstreamConnections,t.upstreamConnectionKeys))}o(dx,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function lx(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.tenantId===t.tenantId&&e.subjectId===t.subjectId&&e.scope===t.scope&&nl(e.roles,t.roles)}o(lx,"accessTokenMatchesGrant");async function px(e){try{return await e.clone().json()}catch{return}}o(px,"readProblemDetails");async function mx(e){let t=await px(e),r=T_(t)&&typeof t.status=="number"?t.status:e.status,n=T_(t)&&zo(t.code)?t.code:md(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(mx,"throwRuntimeHttpStorageError");var Ji=class{static{o(this,"RuntimeHttpStorageClient")}#r;#n;#e;constructor(t){this.#r=t.baseUrl??gp.instance.zuploEdgeApiUrl,this.#n=t.fetch??fetch,this.#e=Fg.parse(t.identity)}async#t(t){let r=t.requestSchema.parse(t.input),n=new URL(t.path,this.#r),a=new Headers({"Content-Type":"application/json"});_p(a);let i=await this.#n(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await mx(i),{request:r,response:await rx(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let u=Dr(s),d=n.get(u);if(d!==void 0)return d;let l=r.length;return r.push(s),n.set(u,l),l}),i=[];for(let s=0;s<r.length;s+=C_){let u=r.slice(s,s+C_);i.push(...await this.#o(u))}return a.map(s=>i[s])}async upsertUpstreamConnection(t){let{request:r,response:n}=await this.#t({input:t,path:DP(this.#e),requestSchema:Wg,responseSchema:Jg});return QP(n,r)||Se("Gateway Service storage response connection did not match the request."),n}async readAuthorizationSetup(t){let{request:r,response:n}=await this.#t({input:t,path:MP(this.#e),requestSchema:Yg,responseSchema:Xg});return nx(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#t({input:t,path:qP(this.#e),requestSchema:Qg,responseSchema:e_});return ox(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#t({input:t,path:$P(this.#e),requestSchema:t_,responseSchema:r_});return ax(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#t({input:t,path:LP(this.#e),requestSchema:n_,responseSchema:o_});return k_(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#t({input:t,path:jP(this.#e),requestSchema:a_,responseSchema:i_});return k_(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#t({input:t,path:HP(this.#e),requestSchema:s_,responseSchema:c_});return ix(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#t({input:t,path:KP(this.#e),requestSchema:S_,responseSchema:w_});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#t({input:t,path:WP(this.#e),requestSchema:v_,responseSchema:R_});return n.kind==="available"&&n.record.id!==r.id&&Se("Gateway Service storage response upstream OAuth state did not match the request."),n}async consumeBrowserConnectTicket(t){let{response:r}=await this.#t({input:t,path:JP(this.#e),requestSchema:b_,responseSchema:I_});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#t({input:t,path:GP(this.#e),requestSchema:u_,responseSchema:d_});return sx(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#t({input:t,path:BP(this.#e),requestSchema:l_,responseSchema:p_});return cx(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#t({input:t,path:VP(this.#e),requestSchema:m_,responseSchema:h_});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#t({input:t,path:FP(this.#e),requestSchema:f_,responseSchema:g_});return ux(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#t({input:t,path:ZP(this.#e),requestSchema:__,responseSchema:y_});return dx(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#t({input:r,path:NP(this.#e),requestSchema:Kg,responseSchema:Yd});return P_(n.items,t),n.items.map(a=>a.connection)}};var ol=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpUpstreamConnectionRepository")}batchGet(t){return this.client.batchGetUpstreamConnections(t)}upsert(t){return this.client.upsertUpstreamConnection(t)}},al=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpDownstreamOAuthRepository")}#r=new Map;#n=new Map;async getDcrClient(t){return this.#r.get(t)}async saveDcrClient(t){if((await this.client.registerClient(t)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");this.#r.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 U("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new U("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:O(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:O(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.#n.set(r.record.id,{currentStateHash:t.currentStateHash,now:t.now,transaction:r.record}),{kind:"consumed",record:r.record})}async issueAuthorizationCode(t){let r=this.#n.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:{tenantId:r.transaction.principal.tenantId,subjectId:r.transaction.principal.subjectId},authorizationCodeHash:t.codeHash,authorizationCodeExpiresAt:t.expiresAt,grantId:t.grantId,now:O(r.now)});if(this.#n.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:O(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:O(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:O(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.#r.has(t.clientId)||this.#r.set(t.clientId,{clientId:t.clientId,clientName:t.clientName,redirectUris:[],tokenEndpointAuthMethod:t.tokenEndpointAuthMethod,clientExpiresAt:O(new Date(864e10)),createdAt:O(new Date(0))})}},il=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:O(new Date)})}},sl=class{constructor(t){this.client=t}static{o(this,"RuntimeHttpBrowserConnectTicketStore")}consume(t,r){return this.client.consumeBrowserConnectTicket({id:t,expiresAt:O(r),now:O(new Date)})}};function x_(e){let t=new Ji(e);return{upstreamConnectionRepository:new ol(t),downstreamOAuthRepository:new al(t),oauthStateStore:new il(t),browserConnectTicketStore:new sl(t)}}o(x_,"createRuntimeHttpStorageBackend");var hx="__zuploMcpGatewayStorageBackend",cl;function fx(e){return{upstreamConnectionRepository:new Zi(e),downstreamOAuthRepository:new Hi(e),oauthStateStore:new Ki(e),browserConnectTicketStore:new Wi(e)}}o(fx,"createPostgresStorageBackend");function gx(){let e=Fn.ZUPLO_SERVICE_BUCKET_ID;if(!e)throw new et("ZUPLO_SERVICE_BUCKET_ID env not configured");let t=jo().MCP_GATEWAY_RUNTIME_STORAGE_CONFIGURATION_ID;if(!t)throw new et("MCP_GATEWAY_RUNTIME_STORAGE_CONFIGURATION_ID env not configured");return{bucketId:e,configurationId:t}}o(gx,"requireRuntimeHttpStorageIdentity");function _x(e){let t=xg(e),r=Ug(t);return fx(r)}o(_x,"buildPostgresStorageBackend");function yx(){let e=jo().TEST_ONLY_DO_NOT_USE_DB_CONNECTION_STRING;return e?_x(e):x_({identity:gx()})}o(yx,"buildProductionStorageBackend");function q(){let e=globalThis[hx];return e||(cl||(cl=yx()),cl)}o(q,"getStorage");function ul(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(ul,"readBearerToken");function Sx(e,t,r){return Ze(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(Sx,"gatewayAuthenticationRequiredResponse");async function wx(e,t,r){let n=await q().downstreamOAuthRepository.validateAccessToken({tokenHash:await F(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(wx,"validateGatewayAccessToken");function vx(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(vx,"assertAccessTokenResource");function Rx(e,t,r){return Ze(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":An({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ue} scope required by this MCP resource.`,scope:ue})}})}o(Rx,"insufficientScopeResponse");function bx(e){return{subjectId:e.subjectId,tenantId:e.tenantId,roles:e.roles}}o(bx,"principalFromAccessToken");function Ix(e){let t=le(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"),Ze(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":An({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(Ix,"gatewayTokenRejectedResponse");async function dl(e,t){let r=Rn(t),n=Nr(r.virtualServerId,e.url),a=ul(e),i=An({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"),Sx(e,t,i);try{let s=await wx(a,t,r.virtualServerId);if(vx({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ue)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ue,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),Rx(e,t,r.virtualServerId);let u=bx(s);return Ag(t,u),pd(t,u),e}catch(s){return Ix({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(dl,"gatewayTokenInbound");var Cx=2,O_=4,Tx=24,Ax=16,U_=512,kx=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,Ex=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,Px=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,xx=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,Ox=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,Ux=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function z_(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(z_,"readRoute");function zx(e){let t=z_(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(zx,"readRoutePath");function Nx(e){let t=z_(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(Nx,"readRouteOperationId");function Dx(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(Dx,"deriveStatusClass");function Mx(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="tenant_shared"?"tenant_shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(Mx,"deriveOriginAttributionMode");function qx(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(qx,"deriveClientKind");function $x(e,t){return t==="success"?"none":e===H.MCP_GATEWAY_REQUEST_RECEIVED||e===H.MCP_GATEWAY_REQUEST_REJECTED||e===H.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===H.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===H.MCP_GATEWAY_POLICY_DECISION?"policy":e===H.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===H.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===H.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o($x,"deriveFailureStage");function Lx(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===H.MCP_GATEWAY_POLICY_DECISION||e===H.MCP_GATEWAY_GUARDRAIL_DECISION||e===H.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===H.MCP_GATEWAY_CAPABILITY_FAILED||e===H.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===H.MCP_GATEWAY_REQUEST_REJECTED||e===H.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(Lx,"deriveFailureOrigin");function jx(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===H.MCP_GATEWAY_POLICY_DECISION?"policy":e===H.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===H.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===H.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===H.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o(jx,"deriveReasonClass");function Hx(e){return e.length<=U_?e:`${e.slice(0,U_)}...`}o(Hx,"truncateAnalyticsString");function Gx(e){return Hx(e.replace(Ex,"$1[REDACTED]$3").replace(xx,"$1$2[REDACTED]").replace(Px,"$1$2[REDACTED]").replace(Ox,"Bearer [REDACTED]").replace(Ux,"Basic [REDACTED]"))}o(Gx,"redactAnalyticsString");function N_(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Gx(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=O_?"[DEPTH_LIMIT]":e.slice(0,Ax).map(r=>N_(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=O_?"[DEPTH_LIMIT]":D_(e,t+1)}}o(N_,"sanitizeAnalyticsValue");function D_(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,Tx)){if(kx.test(n)){r[n]="[REDACTED]";continue}let i=N_(a,t);i!==void 0&&(r[n]=i)}return Object.keys(r).length===0?void 0:r}o(D_,"sanitizeMcpGatewayAnalyticsAttributes");function z(e){return e===void 0?null:e}o(z,"nullable");function Bx(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(Bx,"readEnvironment");function Vx(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(Vx,"readRequestId");function Fx(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(Fx,"attributesToJsonString");function Zx(e,t){let r=Gd(e),n=Do(e),a=D_(t.attributes),i=Vx(e),s=t.ownerMode??t.routeBinding?.ownerMode??null,u=t.upstreamAuthMode??t.routeBinding?.authMode??null,d=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId??null,l=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId??null,p=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName??null,m=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId??null,f=t.clientKind??qx(t.clientName)??null,_=Mx(s??void 0,u??void 0)??null,S=Dx(t.httpStatusCode)??null,y=t.reasonClass??jx(t.eventType,t.outcome),w=t.failureOrigin??Lx(t.eventType,t.outcome),v=t.failureStage??$x(t.eventType,t.outcome);return{schemaVersion:Cx,outcome:t.outcome,tenantId:z(r?.tenantId),subjectId:z(r?.subjectId),environment:Bx(e),traceId:t.traceId??i,spanId:z(t.spanId),parentEventId:z(t.parentEventId),mcpSessionId:z(t.mcpSessionId),routeSurface:z(t.routeSurface),routePath:zx(e)??null,operationId:Nx(e)??null,virtualServerName:d,virtualServerTitle:z(t.virtualServerTitle),upstreamServerName:l,upstreamServerTitle:p,upstreamBindingId:z(t.upstreamBindingId),clientName:z(t.clientName),clientTitle:z(t.clientTitle),clientVersion:z(t.clientVersion),clientKind:f,authProfileId:m,upstreamAuthMode:u,ownerMode:s,authMethod:z(t.authMethod),originAttributionMode:_,httpMethod:z(t.httpMethod),httpStatusCode:z(t.httpStatusCode),statusClass:S,mcpMethod:z(t.mcpMethod),mcpProtocolVersion:z(t.mcpProtocolVersion),mcpStatus:z(t.mcpStatus),mcpErrorType:z(t.mcpErrorType),applicationError:z(t.applicationError),applicationErrorCode:z(t.applicationErrorCode),toolResultIsError:z(t.toolResultIsError),capabilityType:z(t.capabilityType),capabilityName:z(t.capabilityName),capabilityTitle:z(t.capabilityTitle),upstreamCapabilityName:z(t.upstreamCapabilityName),upstreamCapabilityTitle:z(t.upstreamCapabilityTitle),capabilitySchemaHash:z(t.capabilitySchemaHash),policyId:z(t.policyId),policyAction:z(t.policyAction),guardrailType:z(t.guardrailType),guardrailDirection:z(t.guardrailDirection),guardrailFindingCount:z(t.guardrailFindingCount),redactionCount:z(t.redactionCount),requestMutated:z(t.requestMutated),responseMutated:z(t.responseMutated),latencyMs:z(t.latencyMs),gatewayLatencyMs:z(t.gatewayLatencyMs),upstreamLatencyMs:z(t.upstreamLatencyMs),authLatencyMs:z(t.authLatencyMs),policyLatencyMs:z(t.policyLatencyMs),requestBytes:z(t.requestBytes),responseBytes:z(t.responseBytes),estimatedInputTokens:z(t.estimatedInputTokens),estimatedOutputTokens:z(t.estimatedOutputTokens),estimatedContextTokens:z(t.estimatedContextTokens),contextPressureBucket:z(t.contextPressureBucket),responseMimeTypes:z(t.responseMimeTypes),base64Suspected:z(t.base64Suspected),truncated:z(t.truncated),isLargePayloadRequest:z(t.isLargePayloadRequest),isLargePayloadResponse:z(t.isLargePayloadResponse),payloadCaptureMode:z(t.payloadCaptureMode),reasonCode:z(t.reasonCode),reasonClass:y,errorType:t.errorType??t.reasonCode??null,failureOrigin:w,failureStage:v,customMetadataJson:z(t.customMetadataJson),attributesJson:Fx(a)}}o(Zx,"buildMcpGatewayAnalyticsMetadata");function We(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,Zx(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(We,"emitMcpGatewayAnalyticsEvent");function Je(e){let t=ct().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(Je,"getUpstreamServerConfig");function Kx(e){let t=ct().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(Kx,"resolveUpstreamAuthProfileId");function hr(e){Kx(e);let t=ct().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(hr,"getUpstreamAuthConfig");function qr(e,t){let r=hr({upstreamServerId:e,authProfileId:t});if(!Bf(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(qr,"requireUpstreamOAuthConfig");var Wx={tenant_shared_oauth:{authMode:"tenant_shared_oauth",ownerMode:"tenant_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"},tenant_static_secret:{authMode:"tenant_static_secret",ownerMode:"tenant_shared",connectSupport:"none",connectUnsupportedDetail:"Tenant static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"tenant_static_secret_connection"},user_static_secret:{authMode:"user_static_secret",ownerMode:"user",connectSupport:"user_static_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_static_secret_connection"}};function kt(e){return Wx[e]}o(kt,"describeUpstreamAuthMode");function Yi(e){return kt(e).ownerMode}o(Yi,"resolveOwnerModeForUpstreamAuthMode");X();import{errors as G_,jwtVerify as B_,SignJWT as V_}from"jose";import{base64url as Jx}from"jose";var Yx=new TextEncoder,ll=32;function M_(e,t={}){let r=[Xx(e),Yx.encode(e)],n;for(let a of r)if(a){if(a.byteLength>=ll){n=a;break}(n===void 0||a.byteLength>n.byteLength)&&(n=a)}if(n===void 0||n.byteLength<ll){let a=t.name??"secret key material",i=n?.byteLength??0;throw new Error(`${a} must decode to at least ${ll} bytes (got ${i}). Generate a high-entropy value with for example: openssl rand -base64 32 | tr '+/' '-_' | tr -d '='.`)}return n}o(M_,"decodeConfiguredSecretKeyMaterial");function Xx(e){try{return Jx.decode(e)}catch{return}}o(Xx,"tryDecodeBase64Url");var q_=new Map,$_=new Map;function Qx(e){let t=q_.get(e);return t||(t=M_(jo()[e],{name:e}),q_.set(e,t)),t}o(Qx,"getMasterKeyMaterial");async function Et(e){let t=$_.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Qx(e.envVar));return $_.set(e.purpose,r),r}o(Et,"readCachedDerivedKey");var eO="SHA-256";var tO="zuplo-mcp-gateway:",rO=new TextEncoder,L_=new WeakMap;async function fr(e,t){let r=L_.get(e);r||(r=new Map,L_.set(e,r));let n=r.get(t);if(n)return n;let a=await nO(e,t);return r.set(t,a),a}o(fr,"deriveGatewaySigningKey");async function nO(e,t){let r=j_(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=rO.encode(`${tO}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:eO,salt:new Uint8Array,info:j_(a)},n,32*8);return new Uint8Array(i)}o(nO,"hkdfExpand");function j_(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(j_,"copyToArrayBuffer");var Xi="HS256",F_=15*60,oO=15*60,Qi="zuplo-mcp-gateway",es="zuplo-mcp-gateway",aO=Dg.extend({id:Pn}),iO=aO.extend({exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),Z_=kn.extend({id:Vo,purpose:c.literal("browser_connect")}),sO=kn.extend({purpose:c.literal("browser_connect")}),cO=Z_.extend({exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),K_=F_*1e3;async function W_(){return Et({purpose:"oauth-state",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>fr(e,"oauth-state"),"derive")})}o(W_,"getOAuthStateKey");async function J_(){return Et({purpose:"browser-connect",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>fr(e,"browser-connect"),"derive")})}o(J_,"getBrowserConnectKey");async function Y_(e){let t=Math.floor(Date.now()/1e3)+F_;return new V_(e).setProtectedHeader({alg:Xi,typ:"JWT"}).setIssuer(Qi).setAudience(es).setIssuedAt().setExpirationTime(t).sign(await W_())}o(Y_,"signOAuthState");async function ts(e){try{let{payload:t}=await B_(e,await W_(),{algorithms:[Xi],issuer:Qi,audience:es});return iO.parse(t)}catch(t){throw t instanceof G_.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(ts,"verifyOAuthState");async function X_(e){let t=Math.floor(Date.now()/1e3)+oO,r=sO.parse(e),n=Z_.parse({...r,id:jg()});return new V_(n).setProtectedHeader({alg:Xi,typ:"JWT"}).setIssuer(Qi).setAudience(es).setIssuedAt().setExpirationTime(t).sign(await J_())}o(X_,"signBrowserConnectTicket");async function rs(e){try{let{payload:t}=await B_(e,await J_(),{algorithms:[Xi],issuer:Qi,audience:es});return cO.parse(t)}catch(t){throw t instanceof G_.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(rs,"verifyBrowserConnectTicket");async function ns(e){if((await q().browserConnectTicketStore.consume(e.id,new Date(e.exp*1e3))).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(ns,"consumeBrowserConnectTicket");function uO(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(uO,"buildConnectRequiredMessage");async function Q_(e){let t=ne(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 X_({...Bo(e),purpose:"browser_connect"})),r.toString()}o(Q_,"buildGatewayBrowserTicketUrl");function dO(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(dO,"buildGatewayConnectPath");async function pl(e){return Q_({...e,path:dO(e.upstreamServerId),redirect:!0})}o(pl,"buildGatewayConnectUrl");async function ey(e){return Q_({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(ey,"buildGatewayAppPasswordCaptureUrl");async function On(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:uO(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(On,"buildRedirectConnectRequiredResponse");function ty(e){return ry({...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(ty,"buildAdminConnectRequiredResponse");function ry(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(ry,"buildAdminSetupRequiredResponse");function ny(e){return ry({...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(ny,"buildAdminStaticSecretRequiredResponse");X();import{base64url as gr}from"jose";var lO="SHA-256",zn="AES-GCM",pO=12,hl="zuplo-secret",fl=1,oy="env:TOKEN_ENCRYPTION_KEY",mO=c.object({version:c.literal(fl),keyId:c.literal(oy),algorithm:c.literal(zn),iv:c.string().min(1),ciphertext:c.string().min(1)}).strict();function Un(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Un,"copyToArrayBuffer");async function ml(){return Et({purpose:"token-encryption",envVar:"TOKEN_ENCRYPTION_KEY",derive:o(async e=>{let t=await crypto.subtle.digest(lO,Un(e));return crypto.subtle.importKey("raw",t,{name:zn},!1,["encrypt","decrypt"])},"derive")})}o(ml,"getEncryptionKey");function ay(e){return Un(new TextEncoder().encode(`${hl}:v${e.version}:${e.keyId}`))}o(ay,"getAssociatedData");function hO(e){return`${hl}:v${e.version}:${gr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(hO,"encodeEnvelope");function fO(e){let t=`${hl}:v${fl}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(gr.decode(r));return mO.parse(JSON.parse(n))}o(fO,"decodeEnvelope");async function $r(e){let t=await ml(),r=crypto.getRandomValues(new Uint8Array(pO)),n={version:fl,keyId:oy},a=await crypto.subtle.encrypt({name:zn,iv:r,additionalData:ay(n)},t,new TextEncoder().encode(e));return hO({...n,algorithm:zn,iv:gr.encode(r),ciphertext:gr.encode(new Uint8Array(a))})}o($r,"encryptSecret");async function Bt(e){let t=fO(e);if(t){let s=await ml(),u=await crypto.subtle.decrypt({name:zn,iv:Un(gr.decode(t.iv)),additionalData:ay(t)},s,Un(gr.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 ml(),i=await crypto.subtle.decrypt({name:zn,iv:Un(gr.decode(r))},a,Un(gr.decode(n)));return new TextDecoder().decode(i)}o(Bt,"decryptSecret");function gO(e,t){let r=hr({upstreamServerId:e,authProfileId:t});if(r.mode!=="tenant_static_secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(gO,"requireTenantStaticSecretConfig");function iy(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(iy,"hasUsableTenantStaticSecret");async function _O(e){if(!iy(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Bt(e.connection.metadata.encryptedStaticSecret)}}o(_O,"resolveTenantStaticSecretCredential");async function sy(e){let t=Je(e.upstreamServerId);gO(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await q().upstreamConnectionRepository.batchGet([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(iy(r))return{kind:"authorized",credential:await _O({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:ny(n)}}o(sy,"resolveTenantStaticSecretCredentialForRequest");X();async function gl(e){return q().upstreamConnectionRepository.upsert({id:Fi(),tenantId:e.owner.tenantId,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(gl,"upsertStaticSecretConnection");var yO=c.string().trim().min(1).max(320),SO=c.string().min(1).max(4096),wO=c.string().trim().min(1).max(4096);function _l(e,t){let r=hr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user_static_secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(_l,"requireUserStaticSecretConfig");function vO(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(vO,"encodeBase64Utf8");function RO(e){return`Basic ${vO(`${e.username}:${e.appPassword}`)}`}o(RO,"buildBasicAuthHeader");function cy(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(cy,"hasEncryptedUserStaticSecret");async function bO(e){if(!cy(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 Bt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:RO({username:e.connection.metadata.staticSecretUsername,appPassword:await Bt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(bO,"resolveUserStaticSecretCredential");async function uy(e){if(_l(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=yO.parse(e.username),n=SO.parse(e.appPassword);return gl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await $r(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(uy,"saveUserStaticSecretCredential");async function os(e){let t=_l(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=wO.parse(e.token);return gl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await $r(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(os,"saveUserStaticBearerTokenCredential");function yl(e,t){return _l(e,t)}o(yl,"readUserStaticSecretCaptureConfig");async function dy(e){let t=Je(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 q().upstreamConnectionRepository.batchGet([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(cy(r))return{kind:"authorized",credential:await bO({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 On(n)}}o(dy,"resolveUserStaticSecretCredentialForRequest");function ly(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return ey({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(ly,"buildUserStaticSecretConnectUrl");var Sl;Sl=globalThis.crypto;async function IO(e){return(await Sl).getRandomValues(new Uint8Array(e))}o(IO,"getRandomValues");async function CO(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await IO(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(CO,"random");async function TO(e){return await CO(e)}o(TO,"generateVerifier");async function AO(e){let t=await(await Sl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(AO,"generateChallenge");async function wl(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await TO(e),r=await AO(t);return{code_verifier:t,code_challenge:r}}o(wl,"pkceChallenge");X();var Oe=vp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Cp.custom,message:"URL must be parseable",fatal:!0}),Sp}).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"}),as=we({resource:h().url(),authorization_servers:b(Oe).optional(),jwks_uri:h().url().optional(),scopes_supported:b(h()).optional(),bearer_methods_supported:b(h()).optional(),resource_signing_alg_values_supported:b(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:te().optional(),authorization_details_types_supported:b(h()).optional(),dpop_signing_alg_values_supported:b(h()).optional(),dpop_bound_access_tokens_required:te().optional()}),Zo=we({issuer:h(),authorization_endpoint:Oe,token_endpoint:Oe,registration_endpoint:Oe.optional(),scopes_supported:b(h()).optional(),response_types_supported:b(h()),response_modes_supported:b(h()).optional(),grant_types_supported:b(h()).optional(),token_endpoint_auth_methods_supported:b(h()).optional(),token_endpoint_auth_signing_alg_values_supported:b(h()).optional(),service_documentation:Oe.optional(),revocation_endpoint:Oe.optional(),revocation_endpoint_auth_methods_supported:b(h()).optional(),revocation_endpoint_auth_signing_alg_values_supported:b(h()).optional(),introspection_endpoint:h().optional(),introspection_endpoint_auth_methods_supported:b(h()).optional(),introspection_endpoint_auth_signing_alg_values_supported:b(h()).optional(),code_challenge_methods_supported:b(h()).optional(),client_id_metadata_document_supported:te().optional()}),kO=we({issuer:h(),authorization_endpoint:Oe,token_endpoint:Oe,userinfo_endpoint:Oe.optional(),jwks_uri:Oe,registration_endpoint:Oe.optional(),scopes_supported:b(h()).optional(),response_types_supported:b(h()),response_modes_supported:b(h()).optional(),grant_types_supported:b(h()).optional(),acr_values_supported:b(h()).optional(),subject_types_supported:b(h()),id_token_signing_alg_values_supported:b(h()),id_token_encryption_alg_values_supported:b(h()).optional(),id_token_encryption_enc_values_supported:b(h()).optional(),userinfo_signing_alg_values_supported:b(h()).optional(),userinfo_encryption_alg_values_supported:b(h()).optional(),userinfo_encryption_enc_values_supported:b(h()).optional(),request_object_signing_alg_values_supported:b(h()).optional(),request_object_encryption_alg_values_supported:b(h()).optional(),request_object_encryption_enc_values_supported:b(h()).optional(),token_endpoint_auth_methods_supported:b(h()).optional(),token_endpoint_auth_signing_alg_values_supported:b(h()).optional(),display_values_supported:b(h()).optional(),claim_types_supported:b(h()).optional(),claims_supported:b(h()).optional(),service_documentation:h().optional(),claims_locales_supported:b(h()).optional(),ui_locales_supported:b(h()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:Oe.optional(),op_tos_uri:Oe.optional(),client_id_metadata_document_supported:te().optional()}),is=I({...kO.shape,...Zo.pick({code_challenge_methods_supported:!0}).shape}),Ko=I({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:Tp.number().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),my=I({error:h(),error_description:h().optional(),error_uri:h().optional()}),py=Oe.optional().or(E("").transform(()=>{})),EO=I({redirect_uris:b(Oe),token_endpoint_auth_method:h().optional(),grant_types:b(h()).optional(),response_types:b(h()).optional(),client_name:h().optional(),client_uri:Oe.optional(),logo_uri:py,scope:h().optional(),contacts:b(h()).optional(),tos_uri:py,policy_uri:h().optional(),jwks_uri:Oe.optional(),jwks:bp().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),vl=I({client_id:h(),client_secret:h().optional(),client_id_issued_at:K().optional(),client_secret_expires_at:K().optional()}).strip(),Wo=EO.merge(vl),U4=I({error:h(),error_description:h().optional()}).strip(),z4=I({token:h(),token_type_hint:h().optional()}).strip();function hy(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(hy,"resourceUrlFromServerUrl");function fy({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(fy,"checkResourceAllowed");var _e=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}},Jo=class extends _e{static{o(this,"InvalidRequestError")}};Jo.errorCode="invalid_request";var Lr=class extends _e{static{o(this,"InvalidClientError")}};Lr.errorCode="invalid_client";var jr=class extends _e{static{o(this,"InvalidGrantError")}};jr.errorCode="invalid_grant";var Hr=class extends _e{static{o(this,"UnauthorizedClientError")}};Hr.errorCode="unauthorized_client";var Yo=class extends _e{static{o(this,"UnsupportedGrantTypeError")}};Yo.errorCode="unsupported_grant_type";var Xo=class extends _e{static{o(this,"InvalidScopeError")}};Xo.errorCode="invalid_scope";var Qo=class extends _e{static{o(this,"AccessDeniedError")}};Qo.errorCode="access_denied";var Vt=class extends _e{static{o(this,"ServerError")}};Vt.errorCode="server_error";var ea=class extends _e{static{o(this,"TemporarilyUnavailableError")}};ea.errorCode="temporarily_unavailable";var ta=class extends _e{static{o(this,"UnsupportedResponseTypeError")}};ta.errorCode="unsupported_response_type";var ra=class extends _e{static{o(this,"UnsupportedTokenTypeError")}};ra.errorCode="unsupported_token_type";var na=class extends _e{static{o(this,"InvalidTokenError")}};na.errorCode="invalid_token";var oa=class extends _e{static{o(this,"MethodNotAllowedError")}};oa.errorCode="method_not_allowed";var aa=class extends _e{static{o(this,"TooManyRequestsError")}};aa.errorCode="too_many_requests";var Gr=class extends _e{static{o(this,"InvalidClientMetadataError")}};Gr.errorCode="invalid_client_metadata";var ia=class extends _e{static{o(this,"InsufficientScopeError")}};ia.errorCode="insufficient_scope";var sa=class extends _e{static{o(this,"InvalidTargetError")}};sa.errorCode="invalid_target";var gy={[Jo.errorCode]:Jo,[Lr.errorCode]:Lr,[jr.errorCode]:jr,[Hr.errorCode]:Hr,[Yo.errorCode]:Yo,[Xo.errorCode]:Xo,[Qo.errorCode]:Qo,[Vt.errorCode]:Vt,[ea.errorCode]:ea,[ta.errorCode]:ta,[ra.errorCode]:ra,[na.errorCode]:na,[oa.errorCode]:oa,[aa.errorCode]:aa,[Gr.errorCode]:Gr,[ia.errorCode]:ia,[sa.errorCode]:sa};var Ft=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function PO(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(PO,"isClientAuthMethod");var Rl="code",bl="S256";function xO(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&PO(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(xO,"selectClientAuthMethod");function OO(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":UO(a,i,r);return;case"client_secret_post":zO(a,i,n);return;case"none":NO(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(OO,"applyClientAuthentication");function UO(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(UO,"applyBasicAuth");function zO(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(zO,"applyPostAuth");function NO(e,t){t.set("client_id",e)}o(NO,"applyPublicAuth");async function yy(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=my.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,u=gy[a]||Vt;return new u(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Vt(a)}}o(yy,"parseErrorResponse");async function _r(e,t){try{return await Il(e,t)}catch(r){if(r instanceof Lr||r instanceof Hr)return await e.invalidateCredentials?.("all"),await Il(e,t);if(r instanceof jr)return await e.invalidateCredentials?.("tokens"),await Il(e,t);throw r}}o(_r,"auth");async function Il(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),u,d,l,p=a;if(!p&&s?.resourceMetadataUrl&&(p=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,u=s.resourceMetadata,l=s.authorizationServerMetadata??await wy(d,{fetchFn:i}),!u)try{u=await Sy(t,{resourceMetadataUrl:p},i)}catch{}(l!==s.authorizationServerMetadata||u!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:p?.toString(),resourceMetadata:u,authorizationServerMetadata:l})}else{let C=await jO(t,{resourceMetadataUrl:p,fetchFn:i});d=C.authorizationServerUrl,l=C.authorizationServerMetadata,u=C.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:p?.toString(),resourceMetadata:u,authorizationServerMetadata:l})}let m=await DO(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 C=l?.client_id_metadata_document_supported===!0,N=e.clientMetadataUrl;if(N&&!Tl(N))throw new Gr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${N}`);if(C&&N)_={client_id:N},await e.saveClientInformation?.(_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Ye=await FO(d,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:i});await e.saveClientInformation(Ye),_=Ye}}let S=!e.redirectUrl;if(r!==void 0||S){let C=await VO(e,d,{metadata:l,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(C),"AUTHORIZED"}let y=await e.tokens();if(y?.refresh_token)try{let C=await BO(d,{metadata:l,clientInformation:_,refreshToken:y.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(C),"AUTHORIZED"}catch(C){if(!(!(C instanceof _e)||C instanceof Vt))throw C}let w=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:R}=await HO(d,{metadata:l,clientInformation:_,state:w,redirectUrl:e.redirectUrl,scope:f,resource:m});return await e.saveCodeVerifier(R),await e.redirectToAuthorization(v),"REDIRECT"}o(Il,"authInternal");function Tl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Tl,"isHttpsUrl");async function DO(e,t,r){let n=hy(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!fy({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(DO,"selectResourceURL");function Al(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=Cl(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=Cl(e,"scope")||void 0,u=Cl(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:u}}o(Al,"extractWWWAuthenticateParams");function Cl(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(Cl,"extractFieldFromWwwAuth");async function Sy(e,t,r=fetch){let n=await $O(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 as.parse(await n.json())}o(Sy,"discoverOAuthProtectedResourceMetadata");async function kl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?kl(e,void 0,r):void 0;throw n}}o(kl,"fetchWithCorsRetry");function MO(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(MO,"buildWellKnownPath");async function _y(e,t,r=fetch){return await kl(e,{"MCP-Protocol-Version":t},r)}o(_y,"tryMetadataDiscovery");function qO(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(qO,"shouldAttemptFallback");async function $O(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??Xt,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=MO(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let u=await _y(s,i,r);if(!n?.metadataUrl&&qO(u,a.pathname)){let d=new URL(`/.well-known/${t}`,a);u=await _y(d,i,r)}return u}o($O,"discoverMetadataWithFallback");function LO(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(LO,"buildDiscoveryUrls");async function wy(e,{fetchFn:t=fetch,protocolVersion:r=Xt}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=LO(e);for(let{url:i,type:s}of a){let u=await kl(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"?Zo.parse(await u.json()):is.parse(await u.json())}}}o(wy,"discoverAuthorizationServerMetadata");async function jO(e,t){let r,n;try{r=await Sy(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 wy(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(jO,"discoverOAuthServerInfo");async function HO(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(Rl))throw new Error(`Incompatible auth server: does not support response type ${Rl}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(bl))throw new Error(`Incompatible auth server: does not support code challenge method ${bl}`)}else u=new URL("/authorize",e);let d=await wl(),l=d.code_verifier,p=d.code_challenge;return u.searchParams.set("response_type",Rl),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",p),u.searchParams.set("code_challenge_method",bl),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:l}}o(HO,"startAuthorization");function GO(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(GO,"prepareAuthorizationCodeRequest");async function vy(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 p=t?.token_endpoint_auth_methods_supported??[],m=xO(n,p);OO(m,n,d,r)}let l=await(s??fetch)(u,{method:"POST",headers:d,body:r});if(!l.ok)throw await yy(l);return Ko.parse(await l.json())}o(vy,"executeTokenRequest");async function BO(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 vy(e,{metadata:t,tokenRequestParams:u,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(BO,"refreshAuthorization");async function VO(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 l=await e.codeVerifier();u=GO(a,l,e.redirectUrl)}let d=await e.clientInformation();return vy(t,{metadata:r,tokenRequestParams:u,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(VO,"fetchToken");async function FO(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 yy(s);return Wo.parse(await s.json())}o(FO,"registerClient");var ZO=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),KO=[{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 Ry(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(Ry,"parseIpv4Octets");function WO([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(WO,"ipv4RangeMatches");function by(e){let t=Ry(e);return t!==void 0&&KO.some(r=>WO(t,r))}o(by,"isPrivateIpv4");function El(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(El,"parseIpv6Word");function JO(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(JO,"formatIpv4FromWords");function YO(e){let t=e.slice(7),r=Ry(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=El(n),u=El(a);return i===void 0&&s!==void 0&&u!==void 0?JO(s,u):void 0}o(YO,"parseIpv6MappedIpv4");function XO(e){return El(e.split(":").find(Boolean))}o(XO,"readFirstIpv6Hextet");function QO(e){let t=ut(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=YO(t);return n===void 0||by(n)}let r=XO(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(QO,"isPrivateIpv6");function Pl(e){let t=ut(e);return ZO.has(t)||t.endsWith(".internal")||by(t)||QO(t)}o(Pl,"isBlockedOutboundHostname");function Iy(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=ut(t.hostname);if(!r&&Pl(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(Iy,"validateConfiguredOutboundUrl");function Cy(e){let t=new URL(e);if(t.protocol!=="https:")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 r=ut(t.hostname);if(Pl(r))throw g("invalid_request",`Blocked identity provider host: ${r}`);return t}o(Cy,"validateIdentityProviderUrl");function ss(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(Pl(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(ss,"validateCimdClientMetadataUrl");function Ty(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(Ty,"mergeAbortSignals");async function eU(e){try{await e.cancel()}catch{}}o(eU,"cancelReader");async function cs(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 eU(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(cs,"readBoundedByteStream");var tU=2,rU=1024*1024,nU=1e4,oU=new Set([301,302,303,307,308]),aU=["authorization","proxy-authorization","cookie","cookie2"];function xl(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(xl,"readRequestUrl");function Nn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Nn,"readRequestMethod");function iU(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(iU,"assertContentLengthWithinLimit");async function sU(e,t,r){return iU(e,t,r),cs(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(sU,"readBoundedResponseBody");function cU(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(cU,"responseFromBufferedBody");function uU(e,t){if(!oU.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(uU,"resolveRedirectUrl");function Ay(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(Ay,"validateOutboundUrl");function dU(e,t){throw le(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(dU,"normalizeFetchError");function ca(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&&ke(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(ca,"logOutboundFailure");async function lU(e,t,r,n,a,i,s){let u=Nn(r,n);try{return await t(r,n)}catch(d){let l=d instanceof DOMException&&d.name==="AbortError";ca(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:u,host:st(i),error:d,extra:{abortReason:s()}}),dU(d,a)}}o(lU,"fetchWithNormalizedError");function pU(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(pU,"assertRedirectAllowed");function mU(e,t){let r=new Headers(e);for(let n of aU)r.delete(n);for(let n of t)r.delete(n);return r}o(mU,"stripCrossOriginHeaders");function hU(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=mU(e.headers,a)),i}o(hU,"buildRedirectInit");function fU(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(fU,"buildInitialRequestInit");function gU(e){let t=Nn(e.currentInput,e.currentInit);pU({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Ay(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:hU(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(gU,"followRedirect");async function Ol(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??tU,i=r.maxResponseBytes??rU,s=r.timeoutMs??nU,u=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],l=r.context,p=new AbortController,m=Ty(p,t.signal),f=!1,_=setTimeout(()=>{f=!0,p.abort()},s),S=e,y=fU(e,t,p.signal),w;try{w=Ay(xl(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(R){throw ca(l,{event:"outbound_url_blocked",problemCode:n,method:Nn(e,t),host:st(xl(e)),error:R}),clearTimeout(_),m?.(),R}let v=0;try{for(;;){let R=await lU(l,u,S,y,n,w,()=>f?`timeout_after_${s}ms`:void 0),C=uU(R,w);if(C!==void 0)try{let N=gU({currentInput:S,currentInit:y,currentUrl:w,redirectUrl:C,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:d});S=N.currentInput,y=N.currentInit,w=N.currentUrl,v=N.redirects;continue}catch(N){throw ca(l,{event:"outbound_redirect_blocked",problemCode:n,method:Nn(S,y),host:st(w),error:N,extra:{redirects:v,maxRedirects:a,redirectTargetHost:st(C)}}),N}try{return cU(R,await sU(R,i,n))}catch(N){throw ca(l,{event:"outbound_response_size_exceeded",problemCode:n,method:Nn(S,y),host:st(w),error:N,extra:{maxResponseBytes:i,status:R.status}}),N}}}finally{clearTimeout(_),m?.()}}o(Ol,"runSafeOutboundExchange");async function Ul(e,t,r){let n=await Ol(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw ca(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Nn(e,t),host:st(xl(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(Ul,"runSafeOutboundJsonExchange");function us(e,t={},r={}){return Ol(e,t,{...r,validateUrl:Iy})}o(us,"fetchConfiguredOutbound");function ky(e,t={},r={}){return Ul(e,t,{...r,validateUrl:Cy})}o(ky,"fetchIdentityProviderJson");function Ey(e,t={},r={}){return Ul(e,t,{...r,validateUrl:ss})}o(Ey,"fetchCimdClientMetadataJson");X();function zl(e){return`Zuplo MCP Gateway - ${e}`}o(zl,"buildGatewayOAuthClientName");function Py(e,t){let r=new URL(e,ne(t));return Le(r)&&ut(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(Py,"buildGatewayOAuthRedirectUri");function Nl(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(Nl,"buildOAuthClientMetadataDocumentUrl");function xy(e){return ne(e)}o(xy,"requireOAuthClientMetadataOrigin");function Oy(e,t,r){let n=Je(t),a=qr(t,r);return{client_id:Nl({origin:e,upstreamServerId:t,authProfileId:r}),client_name:zl(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(Oy,"buildOAuthClientMetadataDocument");var _U=c.union([Wo,vl]),yU=c.object({authorizationServerUrl:c.url(),resourceMetadataUrl:c.url().optional(),resourceMetadata:as.optional(),authorizationServerMetadata:c.union([Zo,is]).optional()}).passthrough(),SU="Bearer";function wU(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(wU,"splitScopes");function vU(e){return Ni.parse(e)}o(vU,"parsePkceCodeVerifier");function RU(e){if(typeof e.expires_in=="number")return O(new Date(Date.now()+e.expires_in*1e3))}o(RU,"readTokenExpiry");async function Uy(e){if(e!==void 0)return $r(JSON.stringify(e))}o(Uy,"encryptJson");async function zy(e,t){if(!e)return;let r=await Bt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(zy,"decryptJson");function bU(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(bU,"toOAuthDiscoveryState");function IU(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(IU,"clientInformationAllowsRedirectUri");function CU(e,t,r){let n=Je(e),a=qr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:zl(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(CU,"buildOAuthClientMetadata");function TU(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 Wo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(TU,"buildManualOAuthClientInformation");function AU(e,t,r){let n=Nl({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return Tl(n)?n:void 0}o(AU,"buildClientMetadataUrl");function Ny(e){for(let t of e)if(t!==void 0)return t}o(Ny,"firstDefined");function kU(e){let t=qr(e.target.upstreamServerId,e.target.authProfileId),r=CU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:TU({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=AU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(kU,"buildInitialOAuthClientSetup");function EU(e,t){if(t===void 0)return Ny([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(EU,"readEncryptedClientInformation");function PU(e){return Ny([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(PU,"readEncryptedDiscoveryState");var Br=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=kU({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=EU(t,this.configuredClientInformation),this.encryptedDiscoveryState=PU(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return Y_({id:t.id,...Bo({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 Uy(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Uy(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ko.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??Fi(),tenantId:this.target.owner.tenantId,ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await $r(r.access_token),encryptedRefreshToken:r.refresh_token?await $r(r.refresh_token):void 0,scopes:wU(r.scope??this.clientMetadataValue.scope),expiresAt:RU(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="tenant_shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await q().upstreamConnectionRepository.upsert(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:vU(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:Lg(),...Bo({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:O(new Date(Date.now()+K_)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="tenant_shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await q().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 zy(this.encryptedClientInformation,_U)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!IU(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=bU(await zy(this.encryptedDiscoveryState,yU))}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=Ko.parse({access_token:await Bt(this.connection.encryptedAccessToken),token_type:SU,refresh_token:this.connection.encryptedRefreshToken?await Bt(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,tenantId:this.connection.tenantId,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 q().upstreamConnectionRepository.upsert(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var xU=1e4,OU=256*1024,UU=2;function zU(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(zU,"hasUsableAccessToken");var NU="does not support dynamic client registration";function DU(e){return e instanceof Error&&e.message.includes(NU)}o(DU,"isDynamicClientRegistrationUnsupported");function MU(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(MU,"readOAuthFetchRequest");function qU(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(qU,"responseLooksJson");function Dy(e){return async(t,r)=>{let n=MU(t),a=await us(t,r,{maxRedirects:UU,maxResponseBytes:OU,problemCode:"upstream_token_exchange_failed",timeoutMs:xU}),i=await a.clone().text();if(!qU(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(Dy,"createUpstreamOAuthFetch");async function My(e,t){try{return await _r(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Dy(t.upstreamServerId)})}catch(r){throw DU(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(My,"runUpstreamOAuth");async function $U(e,t){return _r(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Dy(t.upstreamServerId)})}o($U,"exchangeUpstreamAuthorizationCode");async function qy(e,t){let r=await My(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(qy,"requireUpstreamAuthorizationRedirect");async function $y(e){if(zU(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await My(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 BU({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($y,"authorizeUpstreamOAuthSession");async function LU(e){let t=await ts(e.stateToken),r=await q().oauthStateStore.consumeForCallback(t.id),n=jU(r);return HU({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),GU(n),n}o(LU,"consumeStoredCallbackState");function jU(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(jU,"readConsumedCallbackState");function HU(e){if(![e.storedState.tenantId===e.signedState.tenantId,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(HU,"assertStoredCallbackStateMatches");function GU(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(GU,"assertStoredCallbackStateFresh");async function BU(e){if(e.owner.mode==="tenant_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),ty(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),On(t)}o(BU,"buildOAuthConnectRequiredResponse");async function Ly(e){let t=await LU({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=En(t),[n]=await q().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 Br(a),s=await $U(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(Ly,"finishUpstreamOAuthCallback");async function jy(e){let t=Je(e.upstreamServerId),r=qr(e.upstreamServerId,e.authProfileId),n=Py(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await q().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:ne(e.request.url)}}}o(jy,"prepareUpstreamOAuthRequest");async function Hy(e){let t=await jy(e),r=new Br({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return qy(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Hy,"startUpstreamConnect");async function Gy(e){let t=await jy(e),r=new Br({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return $y({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Gy,"authorizeUpstreamRequest");function VU(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(VU,"resolveStaticSecretCredential");async function By(e){let{routeAuth:t}=e;switch(t.authMode){case"tenant_shared_oauth":case"user_oauth":return Gy({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"tenant_static_secret":return sy({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=hr({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:VU(n.secret,t.upstreamServerId)}}case"user_static_secret":return dy({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(By,"resolveUpstreamCredentialForRoute");async function Vy(e){let t=mr(e.principal.tenantId,e.principal.subjectId),r=ct().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user_static_secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await os({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(Vy,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function Fy(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=kt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await Hy(r);break;case"user_static_secret_capture":t=await ly(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(Fy,"startUpstreamConnectForRequest");async function Zy(e){let r=(await ts(e.callbackRequest.state)).authProfileId,n=hr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(kt(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Ly({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Je(e.callbackRequest.upstreamServerId)})}o(Zy,"finishUpstreamCallbackForRequest");var ds=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=tr,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 l=d.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new A(k.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let p=u(l.structuredContent);if(!p.valid){yield{type:"error",error:new A(k.InvalidParams,`Structured content does not match the tool's output schema: ${p.errorMessage}`)};return}}catch(p){if(p instanceof A){yield{type:"error",error:p};return}yield{type:"error",error:new A(k.InvalidParams,`Failed to validate structured content: ${p instanceof Error?p.message:String(p)}`)};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 ls(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&&ls(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&ls(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&ls(r,t)}}o(ls,"applyElicitationDefaults");function FU(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(FU,"getSupportedElicitationModes");var ps=class extends tn{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 Sn,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",lc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",cc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Qs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ds(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ua(this._capabilities,t)}setRequestHandler(t,r){let a=Jr(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(Jt(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,l)=>{let p=Me(hc,d);if(!p.success){let R=p.error instanceof Error?p.error.message:String(p.error);throw new A(k.InvalidParams,`Invalid elicitation request: ${R}`)}let{params:m}=p.data;m.mode=m.mode??"form";let{supportsFormMode:f,supportsUrlMode:_}=FU(this._capabilities.elicitation);if(m.mode==="form"&&!f)throw new A(k.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!_)throw new A(k.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(r(d,l));if(m.task){let R=Me(Nt,S);if(!R.success){let C=R.error instanceof Error?R.error.message:String(R.error);throw new A(k.InvalidParams,`Invalid task creation result: ${C}`)}return R.data}let y=Me(rr,S);if(!y.success){let R=y.error instanceof Error?y.error.message:String(y.error);throw new A(k.InvalidParams,`Invalid elicitation result: ${R}`)}let w=y.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{ls(v,w.content)}catch{}return w},"wrappedHandler");return super.setRequestHandler(t,u)}if(s==="sampling/createMessage"){let u=o(async(d,l)=>{let p=Me(mc,d);if(!p.success){let w=p.error instanceof Error?p.error.message:String(p.error);throw new A(k.InvalidParams,`Invalid sampling request: ${w}`)}let{params:m}=p.data,f=await Promise.resolve(r(d,l));if(m.task){let w=Me(Nt,f);if(!w.success){let v=w.error instanceof Error?w.error.message:String(w.error);throw new A(k.InvalidParams,`Invalid task creation result: ${v}`)}return w.data}let S=m.tools||m.toolChoice?ro:vr,y=Me(S,f);if(!y.success){let w=y.error instanceof Error?y.error.message:String(y.error);throw new A(k.InvalidParams,`Invalid sampling result: ${w}`)}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:Xt,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vs,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Qt.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){_i(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&yi(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},zt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},fc,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},zt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},sc,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},tc,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ks,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Ws,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Xs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},zt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},zt,r)}async callTool(t,r=tr,n){if(this.isToolTaskRequired(t.name))throw new A(k.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(k.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(k.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof A?s:new A(k.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},dc,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=Hp.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,l=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"),p=o(()=>{if(u){let m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);let f=setTimeout(l,u);this._listChangedDebounceTimers.set(t,f)}else l()},"handler");this.setNotificationHandler(r,p)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function ms(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(ms,"normalizeHeaders");function Ky(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...ms(t.headers),...ms(n.headers)}:t.headers};return e(r,a)}:e}o(Ky,"createFetchWithInit");var hs=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 Dl(e){}o(Dl,"noop");function Wy(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=Dl,onError:r=Dl,onRetry:n=Dl,onComment:a}=e,i="",s=!0,u,d="",l="";function p(y){let w=s?y.replace(/^\xEF\xBB\xBF/,""):y,[v,R]=ZU(`${i}${w}`);for(let C of v)m(C);i=R,s=!1}o(p,"feed");function m(y){if(y===""){_();return}if(y.startsWith(":")){a&&a(y.slice(y.startsWith(": ")?2:1));return}let w=y.indexOf(":");if(w!==-1){let v=y.slice(0,w),R=y[w+1]===" "?2:1,C=y.slice(w+R);f(v,C,y);return}f(y,"",y)}o(m,"parseLine");function f(y,w,v){switch(y){case"event":l=w;break;case"data":d=`${d}${w}
836
+ `;break;case"id":u=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new hs(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:v}));break;default:r(new hs(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:w,line:v}));break}}o(f,"processField");function _(){d.length>0&&t({id:u,event:l||void 0,data:d.endsWith(`
837
+ `)?d.slice(0,-1):d}),u=void 0,d="",l=""}o(_,"dispatchEvent");function S(y={}){i&&y.consume&&m(i),s=!0,u=void 0,d="",l="",i=""}return o(S,"reset"),{feed:p,reset:S}}o(Wy,"createParser");function ZU(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
838
+ `,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]===`
839
+ `&&n++}}return[t,r]}o(ZU,"splitLines");var fs=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=Wy({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 KU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},yr=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},gs=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=Ky(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??KU}async _authThenStart(){if(!this._authProvider)throw new Ft("No auth provider");let t;try{t=await _r(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 Ft;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=ms(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 yr(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 p=t.pipeThrough(new TextDecoderStream).pipeThrough(new fs({onRetry:o(_=>{this._serverRetryMs=_},"onRetry")})).getReader();for(;;){let{value:_,done:S}=await p.read();if(S)break;if(_.id&&(s=_.id,u=!0,a?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let y=wr.parse(JSON.parse(_.data));dt(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(p){if(this.onerror?.(new Error(`SSE stream disconnected: ${p}`)),(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 Ft("No auth provider");if(await _r(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:wt(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 yr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:S}=Al(u);if(this._resourceMetadataUrl=_,this._scope=S,await _r(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft;return this._hasCompletedAuthFlow=!0,this.send(t)}if(u.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:S,error:y}=Al(u);if(y==="insufficient_scope"){let w=u.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new yr(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=w??void 0,await _r(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ft;return this.send(t)}}throw new yr(u.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,u.status===202){await u.body?.cancel(),Np(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let p=(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(p)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(S=>wr.parse(S)):[wr.parse(f)];for(let S of _)this.onmessage?.(S)}else throw await u.body?.cancel(),new yr(-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 yr(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 Jy(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(Jy,"resolveNativeMcpRequestHeaders");var WU={name:"zuplo-mcp-gateway",version:"0.1.0"},JU=5,YU=500,Qy=3e4,XU=2*1024*1024,QU=2;function Yy(){return performance.now()/1e3}o(Yy,"nowSeconds");function e0(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(e0,"readServerPort");function t0(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:e0(e)}}o(t0,"buildNativeMcpOperationContext");function Dn(e){return dg(e)}o(Dn,"withTraceMeta");function Ml(e){if(e>YU)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Ml,"assertImportedCapabilityBudget");function Xy(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(Xy,"buildRequestInit");function r0(e){return(t,r)=>us(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:QU,maxResponseBytes:XU,problemCode:"upstream_capability_invocation_failed",timeoutMs:Qy})}o(r0,"createNativeMcpFetch");function n0(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},Qy);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(n0,"withNativeMcpRequestTimeout");function o0(e,t=[]){let r=Jy(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:r0(a)};if(!e)return{...i,...Xy(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...Xy(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(o0,"buildNativeMcpTransportOptions");async function Mn(e,t,r){let{transport:n}=Je(e),a=new URL(n.baseUrl),i=new gs(a,o0(r,n.requestHeaders)),s=new ps(WU,{capabilities:{}});return n0((async()=>{let u=Yy();await s.connect(i);let d=i.sessionId,l=t0(a,d);try{return await t(s,l)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&lg(l,Yy()-u)}})())}o(Mn,"withNativeMcpClient");async function a0(e,t,r){let n=[],a,i=0;do{if(i>=JU)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(a0,"collectPaginatedSdkItems");async function ql(e){return e.enabled?a0(e.label,e.fetchPage,e.readItems):[]}o(ql,"listNativeMcpCapabilityItems");async function eS(e){return Mn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"tools/list",...r},()=>ql({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(Dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Ml(a.length),{tools:a}},e.credential)}o(eS,"listNativeMcpTools");async function tS(e){return Mn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"prompts/list",...r},()=>ql({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(Dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Ml(a.length),{prompts:a}},e.credential)}o(tS,"listNativeMcpPrompts");async function rS(e){return Mn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"resources/list",...r},()=>ql({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(Dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Ml(a.length),{resources:a}},e.credential)}o(rS,"listNativeMcpResources");async function nS(e){return Mn(e.upstreamServerId,(t,r)=>Ur({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(Dn(e.params))),e.credential)}o(nS,"callNativeMcpTool");async function oS(e){return Mn(e.upstreamServerId,(t,r)=>Ur({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(Dn(e.params))),e.credential)}o(oS,"getNativeMcpPrompt");async function aS(e){return Mn(e.upstreamServerId,(t,r)=>Ur({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(Dn(e.params))),e.credential)}o(aS,"readNativeMcpResource");var ua=class extends A{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(k.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function i0(e){return{content:[{type:"text",text:e}],isError:!0}}o(i0,"buildToolErrorResult");function s0(e){return e.authUrl?new Yt([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new ua(e)}o(s0,"toConnectRequiredError");function c0(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(c0,"buildCredentialResolvedAttributes");function u0(e){We(e.context,{eventType:H.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:c0(e.credential)})}o(u0,"emitCredentialResolvedAnalyticsEvent");function d0(e){We(e.context,{eventType:H.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(d0,"emitCredentialMissingAnalyticsEvent");function l0(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Dr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(l0,"readRouteBindingCredentialCacheKey");function p0(e){return typeof e.authorizeAndLoadConnections=="function"}o(p0,"isRuntimeHttpCompositeAuthorizationRepository");function sS(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(sS,"readOwnedRouteBindingLookup");async function m0(e){let t=q().downstreamOAuthRepository;if(!p0(t))return new Map;let r=ul(e.request);if(!r)return new Map;let n=new Map;for(let u of e.routeBindings){let d=sS(u);d!==void 0&&n.set(Dr(d),d)}if(n.size===0)return new Map;let a=[...n.values()],i=await t.authorizeAndLoadConnections({accessTokenHash:await F(r),resource:Nr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:a,now:O(new Date)});if(i.kind!=="authorized")return new Map;let s=new Map;return i.upstreamConnections.forEach((u,d)=>{let l=a[d];l!==void 0&&s.set(Dr(l),u.connection)}),s}o(m0,"preloadCompositeAuthorizedConnections");function h0(e){let t=new Map;return r=>{let n=l0(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,u=sS(r),d=u===void 0?void 0:Dr(u),l=await By({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(l.kind==="connect_required")throw d0({context:e.context,payload:l.payload,routeBinding:r}),s0(l.payload);return u0({context:e.context,credential:l.credential,routeBinding:r}),l.credential})();return t.set(n,i),i}}o(h0,"createCredentialResolver");var iS=500;function f0(e){return e.length<=iS?e:`${e.slice(0,iS)}...`}o(f0,"truncateAnalyticsDetail");function g0(e){We(e.context,{eventType:H.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(g0,"emitToolInvocationCompletedAnalyticsEvent");function _0(e){return e instanceof Yt||e instanceof ua?{eventType:H.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof A&&e.code===k.InvalidParams?{eventType:H.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:H.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(_0,"classifyToolInvocationFailure");function y0(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=_0(e.error);We(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:f0(t)}})}o(y0,"emitToolInvocationFailedAnalyticsEvent");var S0=256*1024;function w0(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new A(k.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>S0)throw new A(k.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(w0,"assertToolArgumentsWithinLimit");function $l(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(k.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o($l,"findBindingForPublishedCapability");function qn(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new A(k.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(qn,"requireSingleTransparentBinding");function v0(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:qn(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new A(k.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:$l({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(v0,"resolvePublishedToolRoute");function R0(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:qn(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new A(k.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:$l({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(R0,"resolvePublishedPromptRoute");function b0(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:qn(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new A(k.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:$l({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(b0,"resolvePublishedResourceRoute");function cS(e){let t=m0({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=h0({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(Ei)};let n=qn(e);return eS({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async callTool(n){let a=v0({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:n.name});try{w0(n);let i=await r(a.binding),s=await nS({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:i});return g0({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(y0({context:e.context,routeBinding:a.binding,toolName:n.name,error:i}),i instanceof Yt||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 Yt},"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"),i0(Fe("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(Pi)};let n=qn(e);return tS({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async getPrompt(n){let a=R0({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:n.name});return oS({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(xi)};let n=qn(e);return rS({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async readResource(n){let a=b0({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:n.uri});return aS({upstreamServerId:a.binding.upstreamServerId,params:{...n,uri:a.upstreamUri},credential:await r(a.binding)})}}}o(cS,"createCapabilityDispatcher");var I0="0.1.0",dS="POST",C0="POST, OPTIONS";function Ll(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:dS}})}o(Ll,"jsonRpcMethodNotAllowedResponse");function T0(e){let t={Allow:dS},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=C0;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(T0,"buildOptionsResponse");function $n(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o($n,"readJsonRpcRequestId");function jl(e){return e&&typeof e=="object"?e.params:void 0}o(jl,"readMcpRequestParams");function uS(e,t){return e.headers.get(t)??void 0}o(uS,"readMcpHeader");function A0(e){return{mcpProtocolVersion:uS(e,"mcp-protocol-version")??Or,mcpSessionId:uS(e,"mcp-session-id")}}o(A0,"buildServerTelemetryBase");function k0(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Or),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(k0,"ensureProtocolVersionHeader");async function Hl(e,t){if(e.method==="OPTIONS")return T0(e);if(e.method==="GET")return Ll("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return Ll("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return Ll("Only POST is supported by this virtual MCP server.");let r=Rn(t),n=Yf(r.virtualServerId),a=mg(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=A0(e),s=cS({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),u=ne(e.url),d=new wi({enableDnsRebindingProtection:!0,allowedOrigins:[u]}),l=new Si(n.catalog.serverInfo??{name:r.virtualServerId,version:I0},{capabilities:{prompts:{},resources:{},tools:{}}});l.setRequestHandler(uc,async m=>zr({methodName:"tools/list",params:jl(m),jsonRpcRequestId:$n(m),...i},()=>s.listTools())),l.setRequestHandler(eo,async m=>zr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:$n(m),...i},()=>s.callTool(m.params))),l.setRequestHandler(ec,async m=>zr({methodName:"prompts/list",params:jl(m),jsonRpcRequestId:$n(m),...i},()=>s.listPrompts())),l.setRequestHandler(rc,async m=>zr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:$n(m),...i},()=>s.getPrompt(m.params))),l.setRequestHandler(Zs,async m=>zr({methodName:"resources/list",params:jl(m),jsonRpcRequestId:$n(m),...i},()=>s.listResources())),l.setRequestHandler(Ys,async m=>zr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:$n(m),...i},()=>s.readResource(m.params))),await l.connect(d);let p=await d.handleRequest(e);return k0(p)}o(Hl,"virtualServerHandler");async function E0(e,t){return Wt("handler.mcp-virtual-server"),Hl(e,t)}o(E0,"McpVirtualServerHandler");var Ln={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},P0="oauth-protected-resource-metadata",x0="/.well-known/oauth-protected-resource/";function O0(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(O0,"readRouteOperationId");function U0(e){return e.hasGatewayRouteContext?Ln.VIRTUAL_MCP_SERVER:e.routeOperationId===P0||e.routeOperationId===void 0&&e.routePath.startsWith(x0)?Ln.OAUTH_PROTECTED_RESOURCE_METADATA:Ln.OTHER}o(U0,"classifyAnalyticsRouteSurface");function z0(e){let t=e.route.path;return{routePath:t,routeSurface:U0({routePath:t,routeOperationId:O0(e),hasGatewayRouteContext:Do(e)!==void 0})}}o(z0,"readAnalyticsRequestContext");function N0(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Ln.VIRTUAL_MCP_SERVER}o(N0,"isIntentionalMethodRejection");function D0(e){return N0(e)||e.response.status===401&&e.routeSurface===Ln.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(D0,"classifyRequestCompletedOutcome");async function Gl(e,t){let r=Date.now(),n=z0(t);return t.addResponseSendingFinalHook(a=>{let i=D0({response:a,routeSurface:n.routeSurface});We(t,{eventType:H.MCP_GATEWAY_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Gl,"analyticsContextInbound");function M0(e){return e instanceof Response}o(M0,"isResponse");var lS="/mcp/";function q0(e){let t=e.route.path;if(!t.startsWith(lS))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(lS.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(q0,"readVirtualServerIdFromRoute");async function da(e,t){let n={virtualServerId:me.parse(q0(t))};eg(t,n),zf(t,n);let a=await Gl(e,t);return M0(a)?a:dl(a,t)}o(da,"mcpOAuthInboundPolicy");var $0=o(async(e,t,r,n)=>(Wt("policy.inbound.mcp-auth0-oauth"),da(e,t)),"McpAuth0OAuthInboundPolicy");function L0(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 zi({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,devTenantId:e.devTenantId})}o(L0,"buildAuth0McpOAuthRuntimeConfig");var j0={policyType:"mcp-auth0-oauth-inbound",displayName:"MCP OAuth (Auth0)",getConfig(e){return L0(e)}};Ci(j0);var H0=o(async(e,t,r,n)=>(Wt("policy.inbound.mcp-oauth"),da(e,t)),"McpOAuthInboundPolicy"),G0={policyType:"mcp-oauth-inbound",displayName:"MCP OAuth",getConfig(e){return zi(e)}};Ci(G0);function B0(e){let t=kt(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(B0,"buildRouteAuthBaseFromConnection");function mS(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=kt(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:vn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(mS,"buildRouteAuthBaseFromPolicyOptions");function hS(e,t){let n=ct().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 B0({connection:a,virtualServerId:t})}o(hS,"resolveRouteAuthBase");function pS(e,t){switch(e){case"user":return mr(t.tenantId,t.subjectId);case"tenant_shared":return Bi(t.tenantId)}}o(pS,"buildOwnerForPrincipal");function _s(e,t){switch(e.ownerMode){case"tenant_shared":return{...e,owner:pS(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:pS(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(_s,"resolveRouteAuthForPrincipal");function V0(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(V0,"readSingleAuthMode");function fS(e){return At.parse(e)}o(fS,"buildToolNamePrefixFromConnectionId");async function Bl(e,t,r,n){let a=ki(r,n),i=V0({policyName:n,connection:a}),s=Rn(t),u=mS({connection:a,virtualServerId:s.virtualServerId,authMode:i});if(u.ownerMode==="none")return Pd(t,{...u,connectionPolicyName:n,toolNamePrefix:fS(a.id)}),e;let d=Tg(t);return d.tenantId?(Pd(t,{..._s(u,d),connectionPolicyName:n,toolNamePrefix:fS(a.id)}),e):Ze(e,t,{code:"forbidden",detail:"Upstream credentials for this virtual server require an authenticated tenant.",headers:{"WWW-Authenticate":An({virtualServerId:s.virtualServerId,requestUrl:e.url,error:"insufficient_scope",errorDescription:"The access token is missing tenant context required by this virtual server.",scope:ue})}})}o(Bl,"mcpUpstreamConnectionPolicy");var F0=o(async(e,t,r,n)=>(Wt("policy.inbound.mcp-upstream-connection"),Bl(e,t,r,n)),"McpUpstreamConnectionInboundPolicy");X();X();var gS="application/json",Z0="application/x-www-form-urlencoded";function K0(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(K0,"normalizeContentType");function W0(e,t){return e===t?!0:t===gS&&e.endsWith("+json")}o(W0,"contentTypeMatches");function J0(e,t){if(!t||t.length===0)return;let r=K0(e.headers.get("content-type"));if(!t.some(n=>W0(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(J0,"assertExpectedContentType");function Y0(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(Y0,"assertContentLengthWithinLimit");async function _S(e,t){let r=t.label??"Request body";J0(e,t.expectedContentTypes),Y0(e,t.maxBytes,r);let n=await cs(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(_S,"readBoundedTextBody");async function yS(e,t){let r=await _S(e,{...t,expectedContentTypes:[gS]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(yS,"readBoundedJsonBody");async function ys(e,t){let r=await _S(e,{...t,expectedContentTypes:[Z0]});return new URLSearchParams(r)}o(ys,"readBoundedFormUrlEncodedBody");var SS=Symbol("Html");function X0(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(X0,"escapeHtml");function Q0(e){return e===null||typeof e!="object"?!1:e[SS]===!0}o(Q0,"isHtml");function wS(e){return e==null||e===!1?"":Array.isArray(e)?e.map(wS).join(""):Q0(e)?e.value:X0(String(e))}o(wS,"renderValue");function St(e){return{[SS]:!0,value:e}}o(St,"trustedHtml");var ye=St("");function x(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=wS(t[n]),r+=e[n+1]??"";return St(r)}o(x,"html");function Zt(e){return e.value}o(Zt,"renderHtml");var ez="text/html; charset=utf-8";function vS(e,t=200){return new Response(Zt(e),{status:t,headers:{"content-type":ez,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(vS,"apiKeyLoginHtmlResponse");function Vl(e=401){return vS(x`<!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(Vl,"apiKeyLoginFailureResponse");function RS(e){return vS(x`<!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(RS,"renderApiKeyLoginForm");X();X();import{errors as US,jwtVerify as zS,SignJWT as NS}from"jose";X();import{errors as lz,jwtVerify as pz,SignJWT as mz}from"jose";function Sr(e){let t=Re().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(Sr,"requireBrowserLoginField");function Ss(e){if(!e.tenantId)throw g("identity_context_missing","Gateway OAuth browser login requires a tenant-scoped principal.");return{...e,tenantId:e.tenantId}}o(Ss,"requireTenantScopedBrowserPrincipal");X();import{createRemoteJWKSet as tz,errors as la,jwtVerify as rz}from"jose";var nz=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()}),oz=c.object({error:c.string().min(1).optional(),error_description:c.string().min(1).optional(),error_uri:c.string().min(1).optional()});function az(e){let t=oz.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(az,"readIdpErrorFields");function iz(e){return e instanceof la.JWTExpired?"expired":e instanceof la.JWTClaimValidationFailed?"claim":e instanceof la.JWSSignatureVerificationFailed?"signature":e instanceof la.JWKSNoMatchingKey?"jwks_no_match":e instanceof la.JWTInvalid?"invalid":e instanceof c.ZodError?"schema":"other"}o(iz,"readJwtFailureKind");var sz=c.object({sub:Q,nonce:c.string().min(1)}).catchall(c.unknown()),Fl;function cz(e){return e instanceof Error&&"cause"in e?e.cause:e}o(cz,"readErrorCause");function uz(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(uz,"readRuntimeGatewayCode");function dz(){if(!Fl){let e=Re();Fl=tz(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Fl}o(dz,"readFederatedJwks");async function bS(e){let t=Re(),r=Sr("tokenUrl"),n=Sr("clientId"),a=Sr("clientSecret"),i=new URL("/oauth/callback",_t(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 ky(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=az(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:st(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 l=nz.parse(d),p;try{({payload:p}=await rz(l.id_token,dz(),{issuer:t.oidc.issuer,audience:n}))}catch(f){let _={};throw ke(_,"error",f),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:iz(f),idpHost:st(r),expectedIssuer:t.oidc.issuer,..._},"Federated id_token failed jose verification"),f}if(p.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:st(r),nonceMissingFromIdToken:p.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=sz.parse(p);return Ss(Tn({sub:m.sub,data:m},e.requestUrl))}catch(u){let d=le(u)??uz(u);throw d!==void 0&&d!=="browser_login_verification_failed"?u:g("browser_login_verification_failed","Federated browser login callback could not be verified.",cz(u))}}o(bS,"exchangeFederatedAuthorizationCode");var Kl="zuplo_mcp_session",IS="HS256",CS="zuplo-mcp-gateway",TS="zuplo-mcp-gateway",hz=c.object({purpose:c.literal("gateway_browser_session"),sub:Q,tenantId:de,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 fz(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(fz,"parseCookieHeader");async function AS(){return Et({purpose:"browser-session",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>fr(e,"browser-session"),"derive")})}o(AS,"getBrowserSessionKey");function Zl(e){let t=new URL(ne(e)),r=[`${Kl}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(Zl,"buildBrowserSessionEvictionCookie");function gz(e){let t=new URL(ne(e.requestUrl)),r=[`${Kl}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(gz,"serializeSessionCookie");function kS(e={}){return new URL(Sr("url")).origin}o(kS,"readBrowserLoginOrigin");function Wl(){return Re().browserLogin.stateTtlSeconds}o(Wl,"readBrowserLoginStateTtlSeconds");function ES(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Ss(Tn(e.user,e.url))}o(ES,"resolveCurrentRequestPrincipal");async function ws(e,t={}){let r=fz(e.headers.get("cookie")).get(Kl);if(!r)return{};try{let{payload:n}=await pz(r,await AS(),{algorithms:[IS],issuer:CS,audience:TS}),a=hz.parse(n);if(a.browserLoginOrigin!==kS(t))return{evictCookie:Zl(e.url)};let i={subjectId:a.sub,tenantId:a.tenantId};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof lz.JWTExpired?{evictCookie:Zl(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:Zl(e.url)})}}o(ws,"readBrowserSession");async function pa(e){let t=Re().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,tenantId:e.principal.tenantId,browserLoginOrigin:kS({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new mz(r).setProtectedHeader({alg:IS,typ:"JWT"}).setIssuer(CS).setAudience(TS).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await AS());return gz({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(pa,"createBrowserSessionCookie");async function PS(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(PS,"resolveApiKeyBrowserLoginPrincipal");async function xS(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await ws(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 bS({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(xS,"resolveBrowserLoginCallbackPrincipal");function OS(e){let t=Re().browserLogin,r=new URL(Sr("url")),n=new URL("/oauth/callback",_t(e.requestUrl));return yg(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",Sr("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(OS,"buildBrowserLoginUrl");var DS=5*60,_z=["mcp_user"],vs="HS256",Rs="zuplo-mcp-gateway",bs="zuplo-mcp-gateway",yz=c.object({purpose:c.literal("gateway_browser_login"),transactionId:je,stateId:Mi,exp:c.number().int().positive(),iat:c.number().int().positive().optional()}),Sz=c.object({purpose:c.literal("gateway_authorization_setup"),transactionId:je,stateId:Mi,exp:c.number().int().positive(),iat:c.number().int().positive().optional()});async function MS(){return Et({purpose:"browser-login",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>fr(e,"browser-login"),"derive")})}o(MS,"getBrowserLoginKey");async function qS(){return Et({purpose:"authorization-csrf",envVar:"OAUTH_STATE_SIGNING_KEY",derive:o(e=>fr(e,"authorization-csrf"),"derive")})}o(qS,"getCsrfKey");function wz(e){return[...new Set([..._z,...e.roles??[]])]}o(wz,"buildRoles");function $S(e){return{repository:e.repository??q().downstreamOAuthRepository,now:e.now??new Date,ttlSeconds:Wl()}}o($S,"readPendingTransactionDependencies");function vz(e,t){return e.subjectId===t.subjectId&&e.tenantId===t.tenantId}o(vz,"principalsMatch");function LS(e){return{subjectId:e.subjectId,tenantId:e.tenantId,...e.roles===void 0?{}:{roles:e.roles}}}o(LS,"toPendingPrincipal");function jS(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:O(e.now),expiresAt:O(gt(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:LS(e.principal)}}o(jS,"createTransactionRecord");async function HS(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(HS,"savePendingTransaction");async function Rz(e){return new NS({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:vs,typ:"JWT"}).setIssuer(Rs).setAudience(bs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await MS())}o(Rz,"signBrowserLoginState");async function GS(e){return new NS({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Dd()}).setProtectedHeader({alg:vs,typ:"JWT"}).setIssuer(Rs).setAudience(bs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await qS())}o(GS,"signCsrfToken");async function Is(e){try{let{payload:t}=await zS(e,await MS(),{algorithms:[vs],issuer:Rs,audience:bs}),r=yz.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof US.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Is,"verifyBrowserLoginStateToken");async function bz(e){try{let{payload:t}=await zS(e,await qS(),{algorithms:[vs],issuer:Rs,audience:bs});return{transactionId:Sz.parse(t).transactionId}}catch(t){throw t instanceof US.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(bz,"verifyCsrfToken");function ma(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(ma,"pendingStateErrorCode");function BS(e){return e==="principal_mismatch"?"oauth_callback_mismatch":ma(e==="consumed_already"?"consumed_already":e)}o(BS,"setupDecisionErrorCode");function Iz(e){if(e.kind!=="available")throw g(ma(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(Iz,"requireAwaitingSetup");function Cz(e){if(e.kind!=="available")throw g(ma(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(Cz,"requireAwaitingLogin");function Tz(e){if(!vz(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(Tz,"requireCurrentPrincipalMatches");function VS(e){return typeof e.decideAuthorizationSetup=="function"}o(VS,"hasRuntimeHttpAuthorizationDecision");async function FS(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date,n=Wl(),a=Nd(),i=Dd(),s=await Rz({transactionId:a,stateId:i,ttlSeconds:n}),u=jS({id:a,transaction:e.transaction,currentStateHash:await F(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 HS({repository:t,record:u,client:e.transaction.client}),{transaction:u,browserLoginStateToken:s,browserLoginUrl:OS({state:s,nonce:i,virtualServerId:u.virtualServerId,requestUrl:e.requestUrl})}}o(FS,"startAwaitingLogin");async function ZS(e){let{repository:t,now:r,ttlSeconds:n}=$S(e),a=Nd(),i=await GS({transactionId:a,ttlSeconds:n}),s=jS({id:a,transaction:e.transaction,currentStateHash:await F(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 HS({repository:t,record:s,client:e.transaction.client}),{transaction:s,csrfToken:i}}o(ZS,"startAwaitingSetup");async function Jl(e){let{repository:t,now:r,ttlSeconds:n}=$S(e),a=await Is(e.browserLoginStateToken),i=await GS({transactionId:a.transactionId,ttlSeconds:n}),s=await t.advancePendingAuthorizationTransaction({id:a.transactionId,expectedPhase:"awaiting_login",currentStateHash:await F(e.browserLoginStateToken),nextStateHash:await F(i),nextPhase:"awaiting_setup",principal:LS(e.principal),now:r});if(s.kind!=="advanced")throw g(ma(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(Jl,"completeLogin");async function KS(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date,n=await Is(e.browserLoginStateToken);return Cz(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await F(e.browserLoginStateToken),now:r}))}o(KS,"getAwaitingLogin");async function ha(e){let t=await Yl(e);return Tz({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(ha,"getSetup");async function Yl(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date,n=await bz(e.csrfToken);return Iz(await t.getPendingAuthorizationTransaction({id:n.transactionId,currentStateHash:await F(e.csrfToken),now:r}))}o(Yl,"getSetupTransaction");async function Az(e){let t=Ke(),r=await F(t),n=Md(),a=O(gt(e.now,DS)),i={id:e.transaction.id,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,tenantId:e.transaction.principal.tenantId,subjectId:e.transaction.principal.subjectId,scope:e.transaction.scope,roles:wz(e.transaction.principal),codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:O(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(Az,"createAuthorizationCodeRedirect");async function kz(e){let t=await ha({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:e.now,repository:e.repository}),r=Ke(),n=O(gt(e.now,DS)),a=await e.repository.decideAuthorizationSetup({decision:"approve",transactionId:t.id,currentStateHash:await F(e.csrfToken),currentPrincipal:{tenantId:e.currentBrowserPrincipal.tenantId,subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await F(r),authorizationCodeExpiresAt:n,grantId:Md(),now:O(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":BS(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(kz,"createAuthorizationCodeRedirectWithDecision");async function Ez(e){let t=await ha({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:e.now,repository:e.repository}),r=await e.repository.decideAuthorizationSetup({decision:"cancel",transactionId:t.id,currentStateHash:await F(e.csrfToken),currentPrincipal:{tenantId:e.currentBrowserPrincipal.tenantId,subjectId:e.currentBrowserPrincipal.subjectId},now:O(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":BS(r.kind),"Authorization setup state is invalid, expired, or already used.");return WS({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(Ez,"createCancelRedirectWithDecision");function WS(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(WS,"buildClientCancelRedirect");async function Pz(e){let t=await ha(e),r=await e.repository.consumePendingAuthorizationTransaction({id:t.id,currentStateHash:await F(e.csrfToken),now:e.now});if(r.kind!=="consumed")throw g(ma(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(Pz,"consumeSetup");async function JS(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date;return{repository:t,now:r,transaction:await Pz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t})}}o(JS,"consumeSetupForDecision");async function YS(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date;if(VS(t))return kz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t});let n=await JS(e);return Az({repository:n.repository,transaction:n.transaction,now:n.now})}o(YS,"approve");async function XS(e){let t=e.repository??q().downstreamOAuthRepository,r=e.now??new Date;if(VS(t))return Ez({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:r,repository:t});let{transaction:n}=await JS(e);return WS({redirectUri:n.redirectUri,clientState:n.clientState})}o(XS,"cancel");X();var xz=1e4,Oz=5*1024,Uz=2,zz=90*24*60*60,Xl=["authorization_code","refresh_token"],Ql=["code"],Nz=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(Xl)).min(1).max(2).optional(),response_types:c.array(c.enum(Ql)).min(1).max(1).optional(),scope:c.literal(ue).optional(),token_endpoint_auth_method:$o.default("client_secret_basic")});function Dz(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Dz,"isCimdClientIdCandidate");function jn(e,t="invalid_request"){if(Mz(e))throw new U(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new U(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new U(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||Le(r)))throw new U(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(jn,"assertValidRedirectUri");function Mz(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(Mz,"hasForbiddenRawRedirectUriCharacter");async function qz(e){let{response:t,json:r}=await Ey(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Uz,maxResponseBytes:Oz,timeoutMs:xz});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=gg.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(qz,"fetchCimdMetadata");async function $z(e){let t=ss(e),r=await qz({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o($z,"resolveCimdClient");async function fa(e,t,r){let n=he.parse(t);if(Dz(n)){if(!Re().gateway.cimdEnabled)throw new U("invalid_client","OAuth client is not registered.");try{return await $z(n)}catch{throw new U("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 U("invalid_client",n.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(fa,"resolveClient");function Cs(e,t){if(!e.metadata.redirect_uris.some(r=>Li(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(Cs,"assertRedirectRegistered");function Lz(e){let t=QS(e.grant_types),r=e.response_types??[...Ql];if(!jz(t))throw new U("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!Hz(r))throw new U("invalid_client_metadata","response_types must be code.");if(!Gz(e.scope))throw new U("invalid_client_metadata",`Only the ${ue} scope is supported.`)}o(Lz,"assertSupportedDcrRequest");function QS(e){return e===void 0?[...Xl]:Array.from(new Set(e))}o(QS,"normalizeGrantTypes");function jz(e){return e.length===0?!1:e.every(t=>Xl.includes(t))}o(jz,"isSupportedGrantTypes");function Hz(e){return e.length===Ql.length&&e[0]==="code"}o(Hz,"isSupportedResponseTypes");function Gz(e){return e===void 0||e===ue}o(Gz,"isSupportedDcrScope");function Vr(e){if(e===void 0||e===ue)return ue;throw new U("invalid_request",`Only the ${ue} scope is supported.`)}o(Vr,"assertSupportedOAuthScope");function Pt(e,t){let r;try{r=new URL(t)}catch{throw new U("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new U("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Le(r))throw new U("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ne(e),a=Xf(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new U("invalid_target","resource must match a published virtual MCP server.");return i}o(Pt,"resolveResource");async function ew(e,t={}){let r=Bz(t)?{repository:t}:t,n;try{n=Nz.parse(e)}catch(f){if(f instanceof c.ZodError){let _=f.issues.some(S=>S.path[0]==="redirect_uris");throw new U(_?"invalid_redirect_uri":"invalid_client_metadata",f.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:f})}throw f}Lz(n);for(let f of n.redirect_uris)jn(f,"invalid_redirect_uri");let a=r.repository??q().downstreamOAuthRepository,i=new Date,s=he.parse(`dcr:${crypto.randomUUID()}`),u=gt(i,zz),d=Math.floor(i.getTime()/1e3),l=Math.floor(u.getTime()/1e3),p={client_id:s,client_name:n.client_name??"Dynamically registered MCP client",redirect_uris:n.redirect_uris,grant_types:QS(n.grant_types),response_types:["code"],scope:ue,token_endpoint_auth_method:n.token_endpoint_auth_method,client_id_issued_at:d},m={clientId:s,clientName:String(p.client_name),redirectUris:n.redirect_uris,tokenEndpointAuthMethod:n.token_endpoint_auth_method,createdAt:O(i),clientExpiresAt:O(u)};if(n.token_endpoint_auth_method!=="none"){let f=Ke();m.hashedClientSecret=await F(f),m.clientSecretExpiresAt=O(u),p.client_secret=f,p.client_secret_expires_at=l,p.client_secret_issued_at=d}return await a.saveDcrClient(m),p}o(ew,"registerDownstreamClient");function Bz(e){return typeof e.getDcrClient=="function"}o(Bz,"isOAuthRepository");var Vz=8;function tp(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(tp,"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 Zz(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(Zz,"parseIconSize");function Kz(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(Kz,"selectIconCandidates");function Wz(e){return tp(e.src)?e.sizes&&e.sizes.length>0?Math.max(...e.sizes.map(Zz)):0:-1}o(Wz,"readIconScore");function nw(e,t){if(!e||e.length===0)return;let r=Kz(e,t),n,a=-1;for(let i of r){let s=Wz(i);s>a&&(n=i,a=s)}return n}o(nw,"pickIcon");var Jz='<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>',tw=St(Jz),Yz=St('<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>'),Xz=St('<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>'),ow=St('<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>'),rw=St('<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 Qz(e,t){let r=nw(e,"light");if(!r)return x`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${tw}</span>`;let n=tp(r.src);return n?x`<span class="icon-frame"><img src="${n}" alt="${t}" loading="lazy" decoding="async"></span>`:x`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${tw}</span>`}o(Qz,"renderIconFrame");function As(e,t){let r=nw(e,"light");if(!r)return ye;let n=tp(r.src);return n?x`<img class="inline-icon" src="${n}" alt="${t}" loading="lazy" decoding="async">`:ye}o(As,"renderInlineIcon");function eN(e){switch(e){case"user":return"your account";case"tenant_shared":return"shared by your team";case"none":return"gateway-managed"}}o(eN,"ownerModeLabel");function tN(e){return e.endsWith("_oauth")||e==="oauth"?"OAuth":e.includes("static_secret")?"static credential":e.replaceAll("_"," ")}o(tN,"authModeLabel");function rN(e){switch(e){case"active":return x`<span class="status-badge status-badge--success">Connected</span>`;case"not_connected":return x`<span class="status-badge status-badge--neutral">Not connected</span>`;case"reconsent_required":return x`<span class="status-badge status-badge--warning">Reconnect required</span>`}}o(rN,"statusBadge");function nN(e){if(!e)return ye;let t=[];return e.destructiveHint&&t.push(x`<span class="badge badge--destructive" title="This tool may modify or delete data on your behalf.">destructive</span>`),e.readOnlyHint&&t.push(x`<span class="badge badge--muted" title="This tool only reads data and does not modify state.">read-only</span>`),e.openWorldHint&&t.push(x`<span class="badge badge--muted" title="This tool can access arbitrary URIs supplied at call time.">open-world</span>`),t.length>0?x`<span class="badge-row">${t}</span>`:ye}o(nN,"annotationBadges");function aw(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(aw,"summarizeCapabilities");function oN(e){let t=e.annotations?.title??e.title??e.name,r=e.description?x`<span class="capability-row__description">${e.description}</span>`:ye;return x`<li class="capability-row">${As(e.icons,t)}<span class="capability-row__name">${t}</span>${nN(e.annotations)}${r}</li>`}o(oN,"renderToolRow");function aN(e){let t=e.title??e.name,r=e.description?x`<span class="capability-row__description">${e.description}</span>`:ye;return x`<li class="capability-row">${As(e.icons,t)}<span class="capability-row__name">${t}</span>${r}</li>`}o(aN,"renderPromptRow");function iN(e){let t=e.title??e.name,r=e.mimeType===void 0?ye:x` · ${e.mimeType}`,n=e.description===void 0?ye:x` — ${e.description}`,a=x`<span class="capability-row__description"><code>${e.uri}</code>${r}${n}</span>`;return x`<li class="capability-row">${As(e.icons,t)}<span class="capability-row__name">${t}</span>${a}</li>`}o(iN,"renderResourceRow");function ep(e,t,r,n){if(t===0)return ye;let a=r.slice(0,Vz),i=t-a.length,s=i>0?x`<li class="capability-row capability-row--more">+ ${i} more</li>`:ye;return x`<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(ep,"renderCapabilitySection");function Ts(e,t,r=!1){return r?x`<span class="count-pill count-pill--destructive"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`:x`<span class="count-pill"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`}o(Ts,"countPill");function sN(e){let t=aw(e);if(t.tools+t.prompts+t.resources===0)return x`<div class="upstream-card__capabilities upstream-card__capabilities--empty">No tools, prompts, or resources advertised.</div>`;let n=[];t.tools>0&&n.push(Ts(t.tools===1?"tool":"tools",t.tools)),t.prompts>0&&n.push(Ts(t.prompts===1?"prompt":"prompts",t.prompts)),t.resources>0&&n.push(Ts(t.resources===1?"resource":"resources",t.resources)),t.destructiveTools>0&&n.push(Ts("destructive",t.destructiveTools,!0));let a=[ep("Tools",t.tools,e.tools,oN),ep("Prompts",t.prompts,e.prompts,aN),ep("Resources",t.resources,e.resources,iN)];return x`<details class="upstream-card__capabilities"><summary class="capabilities-summary"><span class="capabilities-summary__counts">${n}</span><span class="capabilities-summary__chevron" aria-hidden="true">${ow}</span></summary><div class="capabilities-detail">${a}</div></details>`}o(sN,"renderUpstreamCapabilities");function cN(e){if(!e||e.length===0)return ye;let t=e.map(n=>x`<code class="scope-chip">${n}</code>`),r=e.length===1?"scope":"scopes";return x`<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">${ow}</span></summary><div class="scopes-list">${t}</div></details>`}o(cN,"renderUpstreamScopes");function uN(e,t){if(e.ownerMode!=="user")return ye;let r=Fz(e.connectUrl,t);if(!r)return ye;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 x`<a class="button button--secondary button--small" href="${r}"${a===void 0?ye:x` title="${a}"`}>${n}</a>`}o(uN,"renderActionButton");function dN(e,t){let r=uN(e,t);return Zt(r)!==""?r:rN(e.status)}o(dN,"renderUpstreamControl");function lN(e,t){let n=e.ownerMode==="user"&&e.status!=="active"?St('<article class="upstream-card upstream-card--needs-action">'):St('<article class="upstream-card">'),a=e.description?x`<p class="upstream-card__description">${e.description}</p>`:ye,i=e.transportHost?x`<code class="upstream-card__host">${e.transportHost}</code><span class="upstream-card__sep" aria-hidden="true">·</span>`:ye,s=x`<div class="upstream-card__head">${Qz(e.serverIcons,e.upstreamDisplayName)}<div class="upstream-card__main"><div class="upstream-card__title-row"><h3 class="upstream-card__title">${e.upstreamDisplayName}</h3>${dN(e,t)}</div><div class="upstream-card__meta">${i}<span>${tN(e.authMode)}</span><span class="upstream-card__sep" aria-hidden="true">·</span><span>${eN(e.ownerMode)}</span></div>${a}</div></div>`,u=sN(e.capabilities),d=cN(e.scopesRequested);return x`${n}${s}${u}${d}</article>`}o(lN,"renderUpstreamCard");function pN(e){return e.reduce((t,r)=>{let n=aw(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(pN,"aggregateCapabilities");function mN(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(mN,"deriveMode");function hN(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?x`Re-authorize ${i} below to refresh access. Authorization will continue automatically once each is ready.`:x`Connect ${i} below before continuing. Authorization will continue automatically once each is ready.`;return x`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${Yz}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${s}</p></div></div>`}let t=pN(e.upstreams);if(t.destructiveTools===0)return ye;let r=t.destructiveTools===1?"tool can":"tools can";return x`<div class="banner banner--alert" role="alert"><span class="banner__icon" aria-hidden="true">${Xz}</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(hN,"renderBanner");function fN(e){return e.mode==="grant"?x`<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>`:x`<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(fN,"renderActions");var gN=`
814
840
  *,*::before,*::after{box-sizing:border-box}
815
841
  :root{
816
842
  --bg:#ffffff;
@@ -1242,8 +1268,8 @@ details[open] > .scopes-summary .capabilities-summary__chevron{transform:rotate(
1242
1268
  @media (prefers-reduced-motion: reduce){
1243
1269
  *{transition:none!important}
1244
1270
  }
1245
- `,pU=pt(lU);function Al(e){let t=cU(e.upstreams),r=[...e.upstreams].sort((m,h)=>{let _=o(y=>y.ownerMode!=="user"?2:y.status==="active"?1:0,"blockedRank"),w=_(m)-_(h);return w!==0?w:m.upstreamDisplayName.localeCompare(h.upstreamDisplayName)}),n=e.principalLabel?k`<span class="principal" title="Signed in as ${e.principalLabel}">${e.principalLabel}</span>`:me,a=e.virtualServerDescription?k`<p class="hero__description">${e.virtualServerDescription}</p>`:me,s=di(e.virtualServerIcons,e.virtualServerDisplayName),i=uU({mode:t,upstreams:r,clientDisplayName:e.clientDisplayName}),c=r.length===0?k`<div class="empty">This virtual server does not declare any upstream services.</div>`:k`<ul class="upstream-list">${r.map(m=>k`<li>${sU(m,e.gatewayOrigin)}</li>`)}</ul>`,d=dU({mode:t,state:e.state}),p=t==="grant"?k`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${qy}</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>`:k`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${qy}</span><span>Authorization continues automatically once every required service is connected.</span></p>`,l=r.length>0?k`<span class="section-label__count">(${r.length})</span>`:me;return Lt(k`<!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>${pU}</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">${s}${e.virtualServerDisplayName}</span></p>${a}</section>${i}</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">${c}</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(Al,"renderConsentPage");function mU(e){try{return new URL(e).host}catch{return}}o(mU,"safeUrlHost");function fU(e){if(e.mode==="user_oauth"||e.mode==="tenant_shared_oauth")return e.oauth.scopes}o(fU,"readOAuthScopes");function Pl(e){return e!==void 0&&e.length>0}o(Pl,"hasItems");async function hU(e){return H().upstreamConnectionRepository.get(e.userOwner,e.registeredConnection.upstreamServerId,e.registeredConnection.authProfileId)}o(hU,"readUserConnection");function gU(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Pl(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Pl(r)?r:void 0}o(gU,"readServerIcons");async function _U(e){if(!(e.returnTo===void 0||!e.isUserOwned))return $d({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(_U,"readConnectUrl");function Mr(e,t){return t===void 0?{}:{[e]:t}}o(Mr,"optionalRequirementField");function yU(e){return e.isUserOwned?_g(e.connection):{connected:!0,status:"active"}}o(yU,"readSetupConnectionStatus");function wU(e){let t=fU(e);return Pl(t)?t:void 0}o(wU,"readScopesRequested");function SU(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(SU,"readUpdatedAt");function vU(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(ms),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(fs),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(hs)}}o(vU,"readVirtualServerCapabilities");async function bU(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:s}=e.registeredConnection,i=Td(r),c=i==="user",d=yU({connection:e.connection,isUserOwned:c}),p=await _U({...e,connected:d.connected,isUserOwned:c});return{upstreamServerId:a,authProfileId:s,authMode:r,ownerMode:i,upstreamDisplayName:n.displayName,status:d.status,connected:d.connected,capabilities:vU({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...Mr("description",n.description),...Mr("transportHost",mU(n.transport.baseUrl)),...Mr("scopesRequested",wU(t)),...Mr("serverIcons",gU({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...Mr("connectUrl",p),...Mr("updatedAt",SU({connectionStatus:d,isUserOwned:c})),...Mr("expiresAt",e.connection?.expiresAt)}}o(bU,"buildSetupRequirement");function Gy(e){let t=tt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(Gy,"requireVirtualServer");async function xl(e){let t=Gy(e.transaction.virtualServerId),r=ur(e.transaction.principal.tenantId,e.transaction.principal.subjectId),n=[];for(let a of t.connections){let s=Td(a.authMode)==="user";n.push(await bU({connection:s?await hU({registeredConnection:a,userOwner:r}):void 0,registeredConnection:a,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return n}o(xl,"requirementsForSetup");function RU(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(RU,"readVirtualServerDisplayName");async function kl(e){let t=e.repository??H().downstreamOAuthRepository,r=Gy(e.transaction.virtualServerId),n=RU({virtualServer:r}),a=await t.getDcrClient(e.transaction.clientId),s={gatewayOrigin:Q(e.requestUrl),virtualServerDisplayName:n,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:`${e.transaction.principal.subjectId} \xB7 ${e.transaction.principal.tenantId}`},i=r.serverInfo?.title;return i!==void 0&&i!==n&&(s.virtualServerDescription=i),s}o(kl,"consentContext");function By(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(By,"hasUnresolvedUserUpstream");var IU=["mcp_user"],TU="dev-browser-user",CU=["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(" "),EU=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:hn,state:u.string().min(1).optional(),scope:u.literal(oe).default(oe)}),AU=u.enum(["continue","approve","cancel"]).default("continue"),PU=u.object({state:u.string().min(1),decision:AU}),xU=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),Dr=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 Vy(e){return typeof e=="string"&&e.length>0?e:void 0}o(Vy,"readQueryString");function kU(e,t){let r=Vy(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new z("invalid_target",CU)}let n=Eo(t,e.url);if(r===void 0||r===n)return n;throw new z("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(kU,"requireAuthorizeResource");async function OU(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await ri(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let s=gy(e);return{principal:s,setCookie:await Jo({principal:s,requestUrl:e.url,virtualServerId:t})}}o(OU,"resolveBrowserPrincipal");async function UU(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await ri(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(UU,"requireSetupPrincipal");async function Fy(e){let t=await xl({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await kl({transaction:e.transaction,requestUrl:e.requestUrl,...e.repository===void 0?{}:{repository:e.repository}}),n={kind:"setup_page",html:Al({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(Fy,"renderSetup");async function Ol(e,t={}){let r=EU.parse({...e.query,resource:kU(e,t.virtualServerId),state:Vy(e.query.state)}),n=Qo(r.scope);Yo(r.redirect_uri);let a=H().downstreamOAuthRepository,s=new Date,i=await Xo(a,r.client_id,s);ci(i,r.redirect_uri);try{let c=xn(e.url,r.resource);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i.clientId,virtualServerId:c.virtualServerId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved");let d={clientId:i.clientId,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:p,setCookie:l}=await OU(e,c.virtualServerId,t.context);if(!p){let h=await xy({transaction:d,requestUrl:e.url,now:s,repository:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i.clientId,virtualServerId:c.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let _={kind:"redirect",location:h.browserLoginUrl};return l!==void 0&&(_.setCookie=l),_}let m=await ky({transaction:d,principal:p,now:s,repository:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i.clientId,virtualServerId:c.virtualServerId,tenantId:p.tenantId,subjectId:p.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),Fy({transaction:m.transaction,csrfToken:m.csrfToken,requestUrl:e.url,repository:a,setCookie:l})}catch(c){throw NU({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Ol,"authorizeDownstreamClient");function NU(e){if(e.cause instanceof Dr)return e.cause;let t=$U(e.cause);return t?new Dr({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(NU,"toDownstreamAuthorizeRedirectError");function $U(e){if(e instanceof z)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($U,"mapToOAuthRedirectError");async function Zy(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 si(n),s={request:e,stateId:a.stateId};t.context!==void 0&&(s.context=t.context);let i=await yy(s),c=H().downstreamOAuthRepository,d=await vl({browserLoginStateToken:n,principal:i,repository:c}),p=await Fy({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,repository:c});return p.setCookie=await Jo({principal:i,requestUrl:e.url,virtualServerId:d.transaction.virtualServerId}),p}o(Zy,"completeBrowserLoginCallback");async function Ky(e){let t=_e();if(!t.devTenantId)throw g("authentication_required","Local browser login requires the `devTenantId` policy option on mcp-oauth-inbound.");let r=new URL(e.url);if(!Ue(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",Q(e.url)),s=new URL(Q(e.url)).origin;if(a.origin!==s||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 i={subjectId:le.parse(TU),tenantId:$e.parse(t.devTenantId),roles:IU};return{kind:"redirect",location:a,setCookie:await Jo({principal:i,requestUrl:e.url})}}o(Ky,"completeLocalDevBrowserLogin");async function Wy(e){let t=xU.parse(e.body),r=H().downstreamOAuthRepository,n=await Oy({browserLoginStateToken:t.state,repository:r}),a=await _y({apiKey:t.apiKey,virtualServerId:n.virtualServerId}),s=await vl({browserLoginStateToken:t.state,principal:a,repository:r});await x_({apiKey:t.apiKey,principal:a,virtualServerId:s.transaction.virtualServerId});let i=new URL("/oauth/setup",lt(e.request.url));return i.searchParams.set("state",s.csrfToken),{kind:"redirect",location:i,setCookie:await Jo({principal:a,requestUrl:e.request.url,virtualServerId:s.transaction.virtualServerId})}}o(Wy,"completeApiKeyBrowserLogin");function zU(e){let t=e.method==="POST"?e.body:e.query;return PU.parse(t)}o(zU,"readSetupContinueRequest");async function Jy(e){let{state:t,decision:r}=zU({method:e.request.method,query:e.request.query,body:e.body}),n=H().downstreamOAuthRepository,a=new Date,s=await Rl({csrfToken:t,now:a,repository:n}),i=await UU(e.request,s.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await $y({csrfToken:t,currentBrowserPrincipal:i,now:a,repository:n})};let c=await bl({csrfToken:t,currentBrowserPrincipal:i,now:a,repository:n}),d=await xl({transaction:c,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||By(d)){let p=await kl({repository:n,transaction:c,requestUrl:e.request.url});return{kind:"setup_page",html:Al({state:t,virtualServerId:c.virtualServerId,upstreams:d,...p})}}return{kind:"redirect",location:await Ny({csrfToken:t,currentBrowserPrincipal:i,now:a,repository:n})}}o(Jy,"continueDownstreamAuthorizeSetup");W();var MU=new Set(["authorization_code","refresh_token"]),DU=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:ws,resource:u.url().optional(),scope:u.literal(oe).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().optional(),scope:u.literal(oe).optional(),client_secret:u.string().min(1).optional()})]);function qU(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!MU.has(t)))throw new z("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(qU,"assertSupportedGrantType");var LU=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 jU(){return _e().gateway.accessTokenTtlSeconds}o(jU,"readAccessTokenTtlSeconds");function HU(){return _e().gateway.refreshTokenTtlSeconds}o(HU,"readRefreshTokenTtlSeconds");async function Yy(e){if(!e.client.hashedClientSecret||!e.clientSecret||e.clientSecretSource!==e.requiredSource)throw new z("invalid_client",e.missingMessage);if(!await J_({value:e.clientSecret,expectedHash:e.client.hashedClientSecret}))throw new z("invalid_client","Client authentication failed.")}o(Yy,"requireClientSecretAuthentication");async function Xy(e){switch(e.client.metadata.token_endpoint_auth_method){case"none":if(e.clientSecret)throw new z("invalid_request","Public clients must not authenticate with client_secret.");return;case"client_secret_basic":await Yy({...e,requiredSource:"basic",missingMessage:"Client authentication with HTTP Basic is required."});return;case"client_secret_post":await Yy({...e,requiredSource:"post",missingMessage:"Client authentication with client_secret_post is required."});return;case"private_key_jwt":throw new z("invalid_client","private_key_jwt client authentication is not supported.")}}o(Xy,"requireClientAuthentication");function Qy(e,t){let r=jU(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:K(ar(e,a)),expiresIn:a}}o(Qy,"calculateAccessTokenExpiresAt");async function GU(e){let t=qt(),r=await ce(t),n=Qy(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,tenantId:e.grant.tenantId,subjectId:e.grant.subjectId,scope:e.grant.scope,roles:e.grant.roles,createdAt:K(e.now),expiresAt:n.expiresAt}),{accessToken:t,expiresIn:n.expiresIn}}o(GU,"issueOpaqueAccessToken");function ew(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new z("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new z("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new z("invalid_client","Malformed HTTP Basic client authentication.")}}o(ew,"readBasicClientSecret");function tw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new z("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new z("invalid_client","Client authentication or client_id is required.");return t}o(tw,"resolveAuthenticatedClientId");function rw(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new z("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(rw,"resolveClientSecretInput");async function nw(e){qU(e.body);let t=DU.parse(e.body),r=ew(e.authorizationHeader),n=tw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=H().downstreamOAuthRepository,s=new Date,i=await Xo(a,n,s),c=rw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});if(await Xy({client:i,...c}),t.grant_type==="authorization_code"){Yo(t.redirect_uri),ci(i,t.redirect_uri),Qo(t.scope),t.resource!==void 0&&xn(e.requestUrl??t.resource,t.resource);let w=qt(),y=qt(),S=K(ar(s,HU())),v=Qy(s,S),b=await a.exchangeAuthorizationCode({codeHash:await ce(t.code),clientId:i.clientId,redirectUri:t.redirect_uri,...t.resource===void 0?{}:{resource:t.resource},codeChallenge:await Y_(t.code_verifier),currentRefreshTokenHash:await ce(w),accessTokenHash:await ce(y),now:s,grantExpiresAt:S,accessTokenExpiresAt:v.expiresAt});if(b.kind==="resource_mismatch")throw new z("invalid_target","Token request resource must match the authorization code resource.");if(b.kind!=="exchanged")throw new z("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:i.clientId,scope:b.grant.scope,resource:b.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:b.grant.scope,resource:b.grant.resource}}Qo(t.scope);let d=await ce(t.refresh_token);t.resource!==void 0&&xn(e.requestUrl??t.resource,t.resource);let p=qt(),l=await ce(p),m=await a.rotateRefreshToken({currentTokenHash:d,nextTokenHash:l,clientId:i.clientId,...t.resource===void 0?{}:{resource:t.resource},now:s});if(m.kind==="resource_mismatch")throw new z("invalid_target","Token request resource must match the refresh token grant resource.");if(m.kind!=="rotated")throw new z("invalid_grant","Refresh token is invalid, expired, or revoked.");let h=m.grant;if(h.revokedAt||h.clientId!==i.clientId)throw new z("invalid_grant","Refresh token grant is invalid or revoked.");xn(e.requestUrl??h.resource,h.resource);let _=await GU({repository:a,grant:h,now:s});return e.context?.log.info({event:"oauth_token_refresh_rotated",grantType:"refresh_token",clientId:i.clientId,scope:h.scope,resource:h.resource,expiresInSeconds:_.expiresIn},"OAuth refresh token rotated and access token issued"),{access_token:_.accessToken,token_type:"Bearer",expires_in:_.expiresIn,refresh_token:p,scope:h.scope,resource:h.resource}}o(nw,"exchangeDownstreamToken");async function ow(e){let t=LU.parse(e.body),r=ew(e.authorizationHeader),n=tw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=H().downstreamOAuthRepository,s=await Xo(a,n,new Date),i=rw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});await Xy({client:s,...i});let c=await ce(t.token);await a.revokeOAuthToken({tokenHash:c,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(ow,"revokeDownstreamToken");var BU=64*1024,VU=16*1024,FU="text/html; charset=utf-8";function ZU(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(ZU,"formDataToObject");async function KU(e){return ay(e,{maxBytes:BU,label:"Request body"})}o(KU,"readJsonBody");async function li(e){return ZU(await ei(e,{maxBytes:VU,label:"Request body"}))}o(li,"readFormBody");async function pi(e,t,r){let n=ae(r),a=r instanceof u.ZodError?aw(r):r instanceof Error?r.message:void 0,s={code:n??"invalid_request"};return a!==void 0&&(s.detail=a),je(e,t,s)}o(pi,"handleProblem");function ea(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(ea,"oauthErrorResponse");function WU(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(WU,"readOAuthProtocolHeaders");function JU(e,t){let r=Le("internal_server_error");return ea({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:WU(e,t)})}o(JU,"oauthProtocolErrorResponse");function YU(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(YU,"readZodOAuthErrorCode");function XU(e){let t={error:YU(e)},r=aw(e);return r!==void 0&&(t.errorDescription=r),ea(t)}o(XU,"oauthZodErrorResponse");function QU(e){let t=ae(e);if(t===void 0)return;let r=Le(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:tN(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,ea(n)}o(QU,"oauthGatewayProblemResponse");function eN(){let t={error:"server_error",status:500,errorDescription:Le("internal_server_error").publicDetail};return ea(t)}o(eN,"oauthFallbackErrorResponse");function tN(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(tN,"readOAuthStatus");function kn(e,t={}){return e instanceof Dr?rN(e):e instanceof z?JU(e,t):e instanceof u.ZodError?XU(e):QU(e)??eN()}o(kn,"oauthProblemResponse");function Rt(e,t,r){let n={event:t},a=!1;if(r instanceof z)n.oauthError=r.errorCode,n.status=r.status,Re(n,"error",r);else if(r instanceof Dr)n.oauthError=r.errorCode,Re(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Re(n,"error",r);let s=r.issues[0];s&&(n.zodPath=s.path.join("."))}else{let s=ae(r);if(s!==void 0){let i=Le(s);n.code=s,n.status=i.status,i.oauthError!==void 0&&(n.oauthError=i.oauthError),a=i.status>=500||i.oauthError==="server_error",Re(n,"error",r)}else a=!0,Re(n,"error",r)}if(a){let s=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,s.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Rt,"logUnexpectedOAuthHandlerError");function rN(e){let t;try{t=new URL(e.redirectUri)}catch{return ea({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(rN,"downstreamAuthorizeRedirectErrorResponse");function aw(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(aw,"formatZodErrorDetail");function nN(e,t){let r={event:"browser_login_callback_failed",code:ae(t)??"invalid_request"};Re(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(nN,"logBrowserLoginCallbackFailure");function Ul(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(Ul,"redirectResultResponse");function mi(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":FU,"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 Ul(e)}o(mi,"authorizeResultResponse");async function sw(e,t){try{return Response.json(bd(e.url))}catch(r){return Rt(t,"oauth_authorization_server_metadata_failed",r),pi(e,t,r)}}o(sw,"authorizationServerMetadataHandler");async function iw(e,t){try{let r=ge.parse(e.params.virtualServerId),n=bo(r);return Response.json(Fh({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Rt(t,"oauth_authorization_server_metadata_failed",r),pi(e,t,r)}}o(iw,"scopedAuthorizationServerMetadataHandler");async function cw(e,t){try{let r=await My(await KU(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 Rt(t,"oauth_register_failed",r),kn(r)}}o(cw,"registerHandler");async function uw(e,t){try{return mi(await Ol(e,{context:t}))}catch(r){return Rt(t,"oauth_authorize_failed",r),kn(r,{includeInvalidClientChallenge:!1})}}o(uw,"authorizeHandler");async function dw(e,t){try{let r=ge.parse(e.params.virtualServerId),n=bo(r);return mi(await Ol(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Rt(t,"oauth_authorize_scoped_failed",r),kn(r,{includeInvalidClientChallenge:!1})}}o(dw,"scopedAuthorizeHandler");async function lw(e,t){try{let r=await Zy(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),mi(r)}catch(r){return nN(t,r),pi(e,t,r)}}o(lw,"callbackHandler");async function pw(e,t){try{return Ul(await Ky(e))}catch(r){return Rt(t,"oauth_dev_login_failed",r),kn(r)}}o(pw,"devLoginHandler");async function mw(e,t){try{if(e.method==="GET"){let r=typeof e.query.state=="string"?e.query.state:void 0;return r?uy(r):gl(400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Ul(await Wy({request:e,body:await li(e)}))}catch(r){return Rt(t,"oauth_api_key_login_failed",r),gl()}}o(mw,"apiKeyLoginHandler");async function fw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Jy({request:e,body:e.method==="POST"?await li(e):void 0,context:t});return mi(r)}catch(r){return Rt(t,"oauth_setup_failed",r),pi(e,t,r)}}o(fw,"setupHandler");async function hw(e,t){try{return Response.json(await nw({body:await li(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Rt(t,"oauth_token_failed",r),kn(r)}}o(hw,"tokenHandler");async function gw(e,t){try{return await ow({body:await li(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Rt(t,"oauth_revoke_failed",r),kn(r)}}o(gw,"revokeHandler");var oN={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},_w=new Ct("upstream-request");function aN(e){let t=_w.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(aN,"readUpstreamRequestContext");function sN(e,t){return t.some(r=>r===e)}o(sN,"requestContextMatchesKind");function iN(e){return typeof e=="string"?[e]:e}o(iN,"toExpectedKinds");function qr(e,t){_w.set(e,t)}o(qr,"setUpstreamRequestContext");function Lr(e,t){let r=aN(e),n=iN(t);if(!sN(r.kind,n)){let a=oN[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(Lr,"requireUpstreamRequestContext");var cN="text/html; charset=utf-8",uN="none";function yw(e){return k`<!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??uN}"><main><h1>${e.title}</h1><p>${e.body}</p></main></body></html>`}o(yw,"browserResultHtml");function ww(e,t=200){return new Response(Lt(e),{status:t,headers:{"content-type":cN,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(ww,"browserResultResponse");function fi(e){return ww(yw(e))}o(fi,"browserConnectionSuccessResponse");function On(e){let t=sh(e);return ww(yw({title:t.title,body:t.body,code:e}),400)}o(On,"browserConnectionFailureResponse");var dN="text/html; charset=utf-8",lN=16*1024;function pN(e,t=200){return new Response(Lt(e),{status:t,headers:{"content-type":dN,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(pN,"htmlResponse");function mN(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(mN,"safeRedirect");function fN(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(fN,"requireBrowserTicket");function hN(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(hN,"appPasswordTicketMatchesTarget");async function Sw(e){let t=fN(e.browserTicket),r=await Ds(t);if(!hN(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(Sw,"readAppPasswordTarget");function gN(e){let t=jd(e.upstreamServerId,e.authProfileId),r=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,n=t.kind==="basic_auth_app_password"?k`<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">`:k`<label for="token">${t.label}</label><input id="token" name="token" type="password" required autocomplete="off">`;return pN(k`<!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(gN,"renderCaptureForm");function hi(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(hi,"readRequiredFormValue");function _N(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(_N,"readCaptureFormTargetInput");async function yN(e){return gN(await Sw(_N(e)))}o(yN,"handleCaptureFormRequest");async function wN(e){let t=await ei(e.request,{maxBytes:lN,label:"App password request body"});return{form:t,target:await Sw({upstreamServerId:e.upstreamServerId,browserTicket:hi(t,"browserTicket")})}}o(wN,"readSubmittedAppPasswordTarget");async function SN(e){let t=Sn(e.target.ticket);if(await qs(e.target.ticket),jd(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Ls({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:hi(e.form,"token")});return}await Kg({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:hi(e.form,"username"),appPassword:hi(e.form,"appPassword")})}o(SN,"saveSubmittedAppPasswordCredential");function vN(e,t){return t.ticket.returnTo?mN(e,t.ticket.returnTo):fi({title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(vN,"appPasswordSuccessResponse");async function bN(e){let t=await wN({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await SN(t),vN(e.request.url,t.target)}o(bN,"handleAppPasswordSubmission");function RN(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(RN,"methodNotAllowedResponse");function IN(e){let t=ae(e);return On(as(t)?t:"oauth_state_invalid")}o(IN,"appPasswordFailureResponse");async function TN(e){switch(e.request.method){case"GET":return yN(e.appPasswordRequest);case"POST":return bN(e);default:return RN()}}o(TN,"handleAppPasswordMethod");async function Nl(e,t){let r=Lr(t,"app_password");try{return await TN({request:e,appPasswordRequest:r})}catch(n){return IN(n)}}o(Nl,"appPasswordHandler");var CN=["callback_authorization_code","callback_provider_error","callback_invalid"];function EN(e){return"cause"in e?e.cause:void 0}o(EN,"readErrorCause");function AN(e){return e.stack?.split(`
1246
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(AN,"readFirstStackFrame");function vw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=AN(r))}o(vw,"addErrorAttributes");function PN(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"),He(e,{eventType:L.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}}),On("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"),On("oauth_state_invalid");case"callback_authorization_code":return t}}o(PN,"requireAuthorizationCallbackRequest");function xN(e,t){He(e,{eventType:L.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(xN,"emitCallbackReceivedAnalyticsEvent");function kN(e,t){He(e,{eventType:L.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(kN,"emitTokenExchangeSucceededAnalyticsEvent");function ON(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return fi({title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(ON,"buildSuccessfulCallbackResponse");function UN(e){let t={detail:e instanceof Error?e.message:void 0};return vw(t,"error",e),e instanceof Error&&vw(t,"cause",EN(e)),t}o(UN,"buildTokenExchangeFailureAttributes");function NN(e){He(e.context,{eventType:L.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:ae(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:UN(e.error)})}o(NN,"emitTokenExchangeFailedAnalyticsEvent");function $N(e){let t=ae(e);return On(as(t)?t:"upstream_token_exchange_failed")}o($N,"tokenExchangeFailureResponse");async function $l(e,t){let r=Lr(t,CN),n=PN(t,r);if(n instanceof Response)return n;xN(t,n);try{let a=await O_({request:e,callbackRequest:n});return kN(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"),ON(e,a)}catch(a){let s={event:"upstream_oauth_token_exchange_failed",code:ae(a)??"upstream_token_exchange_failed",upstreamServerId:n.upstreamServerId};return Re(s,"error",a),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),NN({context:t,callbackRequest:n,error:a}),$N(a)}}o($l,"callbackHandler");function zN(e){let t=ae(e);return t==="unknown_upstream_server"?t:"not_found"}o(zN,"clientMetadataProblemCode");function MN(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(MN,"clientMetadataProblemDetail");async function bw(e,t){let r=Lr(t,"connect"),n=await k_({request:e,connectRequest:r});if(He(t,{eventType:L.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(bw,"connectHandler");async function Rw(e,t){let r=Lr(t,"client_metadata");try{let n=g_(e.url),a=__(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=zN(n),s=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:s},"Failed to serve OAuth client metadata document for upstream connection"),je(e,t,{code:a,detail:MN(n)})}}o(Rw,"oauthClientMetadataHandler");function jt(e){if(typeof e=="string"&&e.length!==0)return e}o(jt,"readOptionalQueryString");function DN(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(DN,"requirePathString");function Iw(e){let t=jt(e);return t?ge.parse(t):void 0}o(Iw,"readOptionalVirtualServerId");function qN(e,t){let r=jt(e);return r?dt.parse(r):pn(t,"user_oauth")}o(qN,"readOptionalAuthProfileId");function LN(e){let t=Iw(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(LN,"readRequiredVirtualServerId");function jN(e){let t=jt(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(jN,"readOptionalBrowserTicket");function HN(e){let t=As(jt(e));return t===void 0?{}:{returnTo:t}}o(HN,"readOptionalReturnTo");function GN(e){let t=Iw(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(GN,"readOptionalVirtualServerIdContext");function BN(e){let t=jt(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(BN,"readOptionalProviderErrorDescription");function VN(e){let t=vt(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(VN,"requireConnectableRouteAuth");function FN(e,t,r,n){let a=Qs(e,t);if(a.ownerMode==="none"||a.authMode==="tenant_static_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(FN,"buildConnectContextForPrincipal");function ZN(e,t,r){let n=Sn(t),a=vt(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(ZN,"buildConnectContextForTicket");async function KN(e,t){let r=VN(ty(t,LN(e.query.virtualServerId))),n=e.query.redirect==="true",a=jt(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 i=gn(e.user,e.url);return FN(r,i,n,HN(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let s=await Ds(a);if(s.ownerMode!==r.ownerMode||s.upstreamServerId!==r.upstreamServerId||s.authProfileId!==r.authProfileId||s.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await qs(s),ZN(r,s,n)}o(KN,"resolveConnectContext");async function WN(e,t,r){let n=ut.parse(DN(e,"connection"));switch(r){case"connect":qr(t,await KN(e,n));return;case"app_password":qr(t,{kind:"app_password",upstreamServerId:n,...GN(e),...jN(e)});return;case"callback":{let a=jt(e.query.error);if(a){qr(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...BN(e)});return}let s=jt(e.query.code),i=jt(e.query.state);if(s&&i){qr(t,{kind:"callback_authorization_code",upstreamServerId:n,code:s,state:i});return}qr(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":qr(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:qN(e.query.authProfileId,n)});return}}o(WN,"resolveUpstreamRequestInbound");async function JN(e,t,r){try{await WN(e,t,r);return}catch(n){let a=ae(n);if(!a)throw n;let s=n instanceof Error?n.message:void 0;return je(e,t,{code:a,...s===void 0?{}:{detail:s}})}}o(JN,"applyUpstreamRequestContext");function ta(e,t){return o(async(n,a)=>{let s=await JN(n,a,e);return s||t(n,a)},"wrapped")}o(ta,"withUpstreamRequestContext");var YN={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function XN(){return new Response(null,{status:204,headers:YN})}o(XN,"buildWellKnownPreflightResponse");function QN(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(QN,"withWellKnownCorsHeaders");function zl(e){return async(t,r)=>t.method==="OPTIONS"?XN():QN(await e(t,r))}o(zl,"wrapWellKnownHandler");var e$=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:zl(sw)},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:zl(iw)},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:zl(Zh)},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:cw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:uw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:dw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:lw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:pw},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:mw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:fw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:hw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:gw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ta("client_metadata",Rw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ta("connect",bw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ta("callback",$l)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:ta("app_password",Nl)}];function Tw(e){if(e)return e.find(t=>ds(t.policyType))}o(Tw,"findMcpOAuthPolicy");function Cw(e){return Tw(e)!==void 0}o(Cw,"shouldRegisterMcpGatewayInternalRoutes");function t$(e){let t=td(e.policyType);if(!t){let r=rd();throw new Tt(`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 Tt(r$(e.name??e.policyType,r),{cause:r}):r}}o(t$,"resolveOAuthConfigFromPolicy");function r$(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
1271
+ `,_N=St(gN);function rp(e){let t=mN(e.upstreams),r=[...e.upstreams].sort((m,f)=>{let _=o(y=>y.ownerMode!=="user"?2:y.status==="active"?1:0,"blockedRank"),S=_(m)-_(f);return S!==0?S:m.upstreamDisplayName.localeCompare(f.upstreamDisplayName)}),n=e.principalLabel?x`<span class="principal" title="Signed in as ${e.principalLabel}">${e.principalLabel}</span>`:ye,a=e.virtualServerDescription?x`<p class="hero__description">${e.virtualServerDescription}</p>`:ye,i=As(e.virtualServerIcons,e.virtualServerDisplayName),s=hN({mode:t,upstreams:r,clientDisplayName:e.clientDisplayName}),u=r.length===0?x`<div class="empty">This virtual server does not declare any upstream services.</div>`:x`<ul class="upstream-list">${r.map(m=>x`<li>${lN(m,e.gatewayOrigin)}</li>`)}</ul>`,d=fN({mode:t,state:e.state}),l=t==="grant"?x`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${rw}</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>`:x`<p class="fineprint"><span class="fineprint__icon" aria-hidden="true">${rw}</span><span>Authorization continues automatically once every required service is connected.</span></p>`,p=r.length>0?x`<span class="section-label__count">(${r.length})</span>`:ye;return Zt(x`<!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>${_N}</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${p}</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">${l}${d}</div></div></body></html>`)}o(rp,"renderConsentPage");function yN(e){try{return new URL(e).host}catch{return}}o(yN,"safeUrlHost");function SN(e){if(e.mode==="user_oauth"||e.mode==="tenant_shared_oauth")return e.oauth.scopes}o(SN,"readOAuthScopes");function np(e){return e!==void 0&&e.length>0}o(np,"hasItems");function wN(e){let t=e.registeredConnection.config.serverInfo?.icons;if(np(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&np(r)?r:void 0}o(wN,"readServerIcons");async function vN(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(vN,"readConnectUrl");function Fr(e,t){return t===void 0?{}:{[e]:t}}o(Fr,"optionalRequirementField");function RN(e){return e.isUserOwned?$g(e.connection):{connected:!0,status:"active"}}o(RN,"readSetupConnectionStatus");function bN(e){let t=SN(e);return np(t)?t:void 0}o(bN,"readScopesRequested");function IN(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(IN,"readUpdatedAt");function CN(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(Ei),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(Pi),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(xi)}}o(CN,"readVirtualServerCapabilities");async function TN(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=Yi(r),u=s==="user",d=RN({connection:e.connection,isUserOwned:u}),l=await vN({...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:CN({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...Fr("description",n.description),...Fr("transportHost",yN(n.transport.baseUrl)),...Fr("scopesRequested",bN(t)),...Fr("serverIcons",wN({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...Fr("connectUrl",l),...Fr("updatedAt",IN({connectionStatus:d,isUserOwned:u})),...Fr("expiresAt",e.connection?.expiresAt)}}o(TN,"buildSetupRequirement");function iw(e){let t=ct().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(iw,"requireVirtualServer");async function op(e){let t=iw(e.transaction.virtualServerId),r=mr(e.transaction.principal.tenantId,e.transaction.principal.subjectId),n=[],a=new Map;for(let u of t.connections)Yi(u.authMode)==="user"&&(a.set(u,n.length),n.push({owner:r,upstreamServerId:u.upstreamServerId,authProfileId:u.authProfileId}));let i=await q().upstreamConnectionRepository.batchGet(n),s=[];for(let u of t.connections){let d=Yi(u.authMode)==="user",l=a.get(u);s.push(await TN({connection:d&&l!==void 0?i[l]:void 0,registeredConnection:u,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(op,"requirementsForSetup");function AN(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(AN,"readVirtualServerDisplayName");async function ap(e){let t=e.repository??q().downstreamOAuthRepository,r=iw(e.transaction.virtualServerId),n=AN({virtualServer:r}),a=await t.getDcrClient(e.transaction.clientId),i={gatewayOrigin:ne(e.requestUrl),virtualServerDisplayName:n,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:`${e.transaction.principal.subjectId} \xB7 ${e.transaction.principal.tenantId}`},s=r.serverInfo?.title;return s!==void 0&&s!==n&&(i.virtualServerDescription=s),i}o(ap,"consentContext");function sw(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(sw,"hasUnresolvedUserUpstream");var kN=["mcp_user"],EN="dev-browser-user",PN=["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(" "),xN=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:In,state:c.string().min(1).optional(),scope:c.literal(ue).default(ue)}),ON=c.enum(["continue","approve","cancel"]).default("continue"),UN=c.object({state:c.string().min(1),decision:ON}),zN=c.object({state:c.string().min(1),apiKey:c.string().min(1)}),Zr=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 cw(e){return typeof e=="string"&&e.length>0?e:void 0}o(cw,"readQueryString");function NN(e,t){let r=cw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new U("invalid_target",PN)}let n=Nr(t,e.url);if(r===void 0||r===n)return n;throw new U("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(NN,"requireAuthorizeResource");async function DN(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await ws(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=ES(e);return{principal:i,setCookie:await pa({principal:i,requestUrl:e.url,virtualServerId:t})}}o(DN,"resolveBrowserPrincipal");async function MN(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await ws(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(MN,"requireSetupPrincipal");async function uw(e){let t=await op({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await ap({transaction:e.transaction,requestUrl:e.requestUrl,...e.repository===void 0?{}:{repository:e.repository}}),n={kind:"setup_page",html:rp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(uw,"renderSetup");function qN(e){return typeof e.decideAuthorizationSetup=="function"}o(qN,"usesRuntimeHttpAuthorizationOperations");function $N(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new U("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o($N,"toAuthorizationTransactionClient");async function ip(e,t={}){let r=xN.parse({...e.query,resource:NN(e,t.virtualServerId),state:cw(e.query.state)}),n=Vr(r.scope);jn(r.redirect_uri);let a=q().downstreamOAuthRepository,i=new Date,s=he.parse(r.client_id),u=qN(a)&&s.startsWith("dcr:")?void 0:await fa(a,r.client_id,i);u!==void 0&&Cs(u,r.redirect_uri);let d=u===void 0,l=d?Pt(e.url,r.resource):void 0;try{let p=l??Pt(e.url,r.resource),m=$N(u);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:s,virtualServerId:p.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:p.virtualServerId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:_,setCookie:S}=await DN(e,p.virtualServerId,t.context);if(!_){let w=await FS({transaction:f,requestUrl:e.url,now:i,repository:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:s,virtualServerId:p.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let v={kind:"redirect",location:w.browserLoginUrl};return S!==void 0&&(v.setCookie=S),v}let y=await ZS({transaction:f,principal:_,now:i,repository:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:s,virtualServerId:p.virtualServerId,tenantId:_.tenantId,subjectId:_.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),uw({transaction:y.transaction,csrfToken:y.csrfToken,requestUrl:e.url,repository:a,setCookie:S})}catch(p){throw d?p:LN({redirectUri:r.redirect_uri,clientState:r.state,cause:p})}}o(ip,"authorizeDownstreamClient");function LN(e){if(e.cause instanceof Zr)return e.cause;let t=jN(e.cause);return t?new Zr({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(LN,"toDownstreamAuthorizeRedirectError");function jN(e){if(e instanceof U)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(jN,"mapToOAuthRedirectError");async function dw(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,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,...p===void 0?{}:{idpErrorDescription:p},...m===void 0?{}:{idpErrorUri:m}},"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 Is(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await xS(i),u=q().downstreamOAuthRepository,d=await Jl({browserLoginStateToken:n,principal:s,repository:u}),l=await uw({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url,repository:u});return l.setCookie=await pa({principal:s,requestUrl:e.url,virtualServerId:d.transaction.virtualServerId}),l}o(dw,"completeBrowserLoginCallback");async function lw(e){let t=Re();if(!t.devTenantId)throw g("authentication_required","Local browser login requires the `devTenantId` policy option on mcp-oauth-inbound.");let 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",ne(e.url)),i=new URL(ne(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:Q.parse(EN),tenantId:de.parse(t.devTenantId),roles:kN};return{kind:"redirect",location:a,setCookie:await pa({principal:s,requestUrl:e.url})}}o(lw,"completeLocalDevBrowserLogin");async function pw(e){let t=zN.parse(e.body),r=q().downstreamOAuthRepository,n=await KS({browserLoginStateToken:t.state,repository:r}),a=await PS({apiKey:t.apiKey,virtualServerId:n.virtualServerId}),i=await Jl({browserLoginStateToken:t.state,principal:a,repository:r});await Vy({apiKey:t.apiKey,principal:a,virtualServerId:i.transaction.virtualServerId});let s=new URL("/oauth/setup",_t(e.request.url));return s.searchParams.set("state",i.csrfToken),{kind:"redirect",location:s,setCookie:await pa({principal:a,requestUrl:e.request.url,virtualServerId:i.transaction.virtualServerId})}}o(pw,"completeApiKeyBrowserLogin");function HN(e){let t=e.method==="POST"?e.body:e.query;return UN.parse(t)}o(HN,"readSetupContinueRequest");async function mw(e){let{state:t,decision:r}=HN({method:e.request.method,query:e.request.query,body:e.body}),n=q().downstreamOAuthRepository,a=new Date,i=await Yl({csrfToken:t,now:a,repository:n}),s=await MN(e.request,i.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await XS({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n})};let u=await ha({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n}),d=await op({transaction:u,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||sw(d)){let l=await ap({repository:n,transaction:u,requestUrl:e.request.url});return{kind:"setup_page",html:rp({state:t,virtualServerId:u.virtualServerId,upstreams:d,...l})}}return{kind:"redirect",location:await YS({csrfToken:t,currentBrowserPrincipal:s,now:a,repository:n})}}o(mw,"continueDownstreamAuthorizeSetup");X();var GN=new Set(["authorization_code","refresh_token"]),BN=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:Ni,resource:c.url().optional(),scope:c.literal(ue).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(ue).optional(),client_secret:c.string().min(1).optional()})]);function VN(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!GN.has(t)))throw new U("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(VN,"assertSupportedGrantType");var FN=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 fw(){return Re().gateway.accessTokenTtlSeconds}o(fw,"readAccessTokenTtlSeconds");function gw(){return Re().gateway.refreshTokenTtlSeconds}o(gw,"readRefreshTokenTtlSeconds");async function hw(e){if(!e.client.hashedClientSecret||!e.clientSecret||e.clientSecretSource!==e.requiredSource)throw new U("invalid_client",e.missingMessage);if(!await bg({value:e.clientSecret,expectedHash:e.client.hashedClientSecret}))throw new U("invalid_client","Client authentication failed.")}o(hw,"requireClientSecretAuthentication");async function _w(e){switch(e.client.metadata.token_endpoint_auth_method){case"none":if(e.clientSecret)throw new U("invalid_request","Public clients must not authenticate with client_secret.");return;case"client_secret_basic":await hw({...e,requiredSource:"basic",missingMessage:"Client authentication with HTTP Basic is required."});return;case"client_secret_post":await hw({...e,requiredSource:"post",missingMessage:"Client authentication with client_secret_post is required."});return;case"private_key_jwt":throw new U("invalid_client","private_key_jwt client authentication is not supported.")}}o(_w,"requireClientAuthentication");function sp(e,t){let r=fw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:O(gt(e,a)),expiresIn:a}}o(sp,"calculateAccessTokenExpiresAt");async function ZN(e){let t=Ke(),r=await F(t),n=sp(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,tenantId:e.grant.tenantId,subjectId:e.grant.subjectId,scope:e.grant.scope,roles:e.grant.roles,createdAt:O(e.now),expiresAt:n.expiresAt}),{accessToken:t,expiresIn:n.expiresIn}}o(ZN,"issueOpaqueAccessToken");function yw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new U("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new U("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new U("invalid_client","Malformed HTTP Basic client authentication.")}}o(yw,"readBasicClientSecret");function Sw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new U("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new U("invalid_client","Client authentication or client_id is required.");return t}o(Sw,"resolveAuthenticatedClientId");function ww(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new U("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(ww,"resolveClientSecretInput");function vw(e){return typeof e.exchangeAuthorizationCodeWithClientAuth=="function"&&typeof e.refreshTokenWithClientAuth=="function"&&typeof e.revokeOAuthTokenWithClientAuth=="function"}o(vw,"usesRuntimeHttpTokenOperations");async function Rw(e){let t=he.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 F(e.clientSecret)}}o(Rw,"buildRuntimeHttpClientAuth");async function bw(e){VN(e.body);let t=BN.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=q().downstreamOAuthRepository,i=new Date,s=ww({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});if(vw(a))return KN({parsed:t,clientId:n,clientSecretInput:s,now:i,repository:a,requestUrl:e.requestUrl});let u=await fa(a,n,i);if(await _w({client:u,...s}),t.grant_type==="authorization_code"){jn(t.redirect_uri),Cs(u,t.redirect_uri),Vr(t.scope),t.resource!==void 0&&Pt(e.requestUrl??t.resource,t.resource);let S=Ke(),y=Ke(),w=O(gt(i,gw())),v=sp(i,w),R=await a.exchangeAuthorizationCode({codeHash:await F(t.code),clientId:u.clientId,redirectUri:t.redirect_uri,...t.resource===void 0?{}:{resource:t.resource},codeChallenge:await jd(t.code_verifier),currentRefreshTokenHash:await F(S),accessTokenHash:await F(y),now:i,grantExpiresAt:w,accessTokenExpiresAt:v.expiresAt});if(R.kind==="resource_mismatch")throw new U("invalid_target","Token request resource must match the authorization code resource.");if(R.kind!=="exchanged")throw new U("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:S,scope:R.grant.scope,resource:R.grant.resource}}Vr(t.scope);let d=await F(t.refresh_token);t.resource!==void 0&&Pt(e.requestUrl??t.resource,t.resource);let l=Ke(),p=await F(l),m=await a.rotateRefreshToken({currentTokenHash:d,nextTokenHash:p,clientId:u.clientId,...t.resource===void 0?{}:{resource:t.resource},now:i});if(m.kind==="resource_mismatch")throw new U("invalid_target","Token request resource must match the refresh token grant resource.");if(m.kind!=="rotated")throw new U("invalid_grant","Refresh token is invalid, expired, or revoked.");let f=m.grant;if(f.revokedAt||f.clientId!==u.clientId)throw new U("invalid_grant","Refresh token grant is invalid or revoked.");Pt(e.requestUrl??f.resource,f.resource);let _=await ZN({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:l,scope:f.scope,resource:f.resource}}o(bw,"exchangeDownstreamToken");async function KN(e){let t=await Rw({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){jn(e.parsed.redirect_uri),Vr(e.parsed.scope),e.parsed.resource!==void 0&&Pt(e.requestUrl??e.parsed.resource,e.parsed.resource);let u=Ke(),d=Ke(),l=O(gt(e.now,gw())),p=sp(e.now,l),m=await e.repository.exchangeAuthorizationCodeWithClientAuth({clientAuth:t,codeHash:await F(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await jd(e.parsed.code_verifier),currentRefreshTokenHash:await F(u),accessTokenHash:await F(d),grantExpiresAt:l,accessTokenExpiresAt:p.expiresAt,now:O(e.now)});if(m.kind==="invalid_client")throw new U("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new U("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new U("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return{access_token:d,token_type:"Bearer",expires_in:p.expiresIn,refresh_token:u,scope:m.grant.scope,resource:m.grant.resource}}Vr(e.parsed.scope),e.parsed.resource!==void 0&&Pt(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=Ke(),n=Ke(),a=O(gt(e.now,fw())),i=await e.repository.refreshTokenWithClientAuth({clientAuth:t,currentRefreshTokenHash:await F(e.parsed.refresh_token),nextRefreshTokenHash:await F(r),accessTokenHash:await F(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:O(e.now)});if(i.kind==="invalid_client")throw new U("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new U("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new U("invalid_grant","Refresh token is invalid, expired, or revoked.");Pt(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(KN,"exchangeDownstreamTokenWithRuntimeHttp");async function Iw(e){let t=FN.parse(e.body),r=yw(e.authorizationHeader),n=Sw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=q().downstreamOAuthRepository,i=ww({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});if(vw(a)){let d=new Date;if((await a.revokeOAuthTokenWithClientAuth({clientAuth:await Rw({clientId:n,...i}),tokenHash:await F(t.token),now:O(d)})).kind==="invalid_client")throw new U("invalid_client","Client authentication failed.");return}let s=await fa(a,n,new Date);await _w({client:s,...i});let u=await F(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(Iw,"revokeDownstreamToken");var WN=64*1024,JN=16*1024,YN="text/html; charset=utf-8";function XN(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(XN,"formDataToObject");async function QN(e){return yS(e,{maxBytes:WN,label:"Request body"})}o(QN,"readJsonBody");async function ks(e){return XN(await ys(e,{maxBytes:JN,label:"Request body"}))}o(ks,"readFormBody");async function Es(e,t,r){let n=le(r),a=r instanceof c.ZodError?Cw(r):r instanceof Error?r.message:void 0,i={code:n??"invalid_request"};return a!==void 0&&(i.detail=a),Ze(e,t,i)}o(Es,"handleProblem");function ga(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(ga,"oauthErrorResponse");function eD(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(eD,"readOAuthProtocolHeaders");function tD(e,t){let r=Fe("internal_server_error");return ga({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:eD(e,t)})}o(tD,"oauthProtocolErrorResponse");function rD(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(rD,"readZodOAuthErrorCode");function nD(e){let t={error:rD(e)},r=Cw(e);return r!==void 0&&(t.errorDescription=r),ga(t)}o(nD,"oauthZodErrorResponse");function oD(e){let t=le(e);if(t===void 0)return;let r=Fe(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:iD(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,ga(n)}o(oD,"oauthGatewayProblemResponse");function aD(){let t={error:"server_error",status:500,errorDescription:Fe("internal_server_error").publicDetail};return ga(t)}o(aD,"oauthFallbackErrorResponse");function iD(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(iD,"readOAuthStatus");function Hn(e,t={}){return e instanceof Zr?sD(e):e instanceof U?tD(e,t):e instanceof c.ZodError?nD(e):oD(e)??aD()}o(Hn,"oauthProblemResponse");function xt(e,t,r){let n={event:t},a=!1;if(r instanceof U)n.oauthError=r.errorCode,n.status=r.status,ke(n,"error",r);else if(r instanceof Zr)n.oauthError=r.errorCode,ke(n,"error",r);else if(r instanceof c.ZodError){n.code="invalid_request",ke(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=le(r);if(i!==void 0){let s=Fe(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",ke(n,"error",r)}else a=!0,ke(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(xt,"logUnexpectedOAuthHandlerError");function sD(e){let t;try{t=new URL(e.redirectUri)}catch{return ga({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(sD,"downstreamAuthorizeRedirectErrorResponse");function Cw(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Cw,"formatZodErrorDetail");function cD(e,t){let r={event:"browser_login_callback_failed",code:le(t)??"invalid_request"};ke(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(cD,"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 Ps(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":YN,"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(Ps,"authorizeResultResponse");async function Tw(e,t){try{return Response.json($d(e.url))}catch(r){return xt(t,"oauth_authorization_server_metadata_failed",r),Es(e,t,r)}}o(Tw,"authorizationServerMetadataHandler");async function Aw(e,t){try{let r=me.parse(e.params.virtualServerId),n=No(r);return Response.json(Sg({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return xt(t,"oauth_authorization_server_metadata_failed",r),Es(e,t,r)}}o(Aw,"scopedAuthorizationServerMetadataHandler");async function kw(e,t){try{let r=await ew(await QN(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 xt(t,"oauth_register_failed",r),Hn(r)}}o(kw,"registerHandler");async function Ew(e,t){try{return Ps(await ip(e,{context:t}))}catch(r){return xt(t,"oauth_authorize_failed",r),Hn(r,{includeInvalidClientChallenge:!1})}}o(Ew,"authorizeHandler");async function Pw(e,t){try{let r=me.parse(e.params.virtualServerId),n=No(r);return Ps(await ip(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return xt(t,"oauth_authorize_scoped_failed",r),Hn(r,{includeInvalidClientChallenge:!1})}}o(Pw,"scopedAuthorizeHandler");async function xw(e,t){try{let r=await dw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ps(r)}catch(r){return cD(t,r),Es(e,t,r)}}o(xw,"callbackHandler");async function Ow(e,t){try{return cp(await lw(e))}catch(r){return xt(t,"oauth_dev_login_failed",r),Hn(r)}}o(Ow,"devLoginHandler");async function Uw(e,t){try{if(e.method==="GET"){let r=typeof e.query.state=="string"?e.query.state:void 0;return r?RS(r):Vl(400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):cp(await pw({request:e,body:await ks(e)}))}catch(r){return xt(t,"oauth_api_key_login_failed",r),Vl()}}o(Uw,"apiKeyLoginHandler");async function zw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await mw({request:e,body:e.method==="POST"?await ks(e):void 0,context:t});return Ps(r)}catch(r){return xt(t,"oauth_setup_failed",r),Es(e,t,r)}}o(zw,"setupHandler");async function Nw(e,t){try{return Response.json(await bw({body:await ks(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return xt(t,"oauth_token_failed",r),Hn(r)}}o(Nw,"tokenHandler");async function Dw(e,t){try{return await Iw({body:await ks(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return xt(t,"oauth_revoke_failed",r),Hn(r)}}o(Dw,"revokeHandler");var uD={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Mw=new Ut("upstream-request");function dD(e){let t=Mw.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(dD,"readUpstreamRequestContext");function lD(e,t){return t.some(r=>r===e)}o(lD,"requestContextMatchesKind");function pD(e){return typeof e=="string"?[e]:e}o(pD,"toExpectedKinds");function Kr(e,t){Mw.set(e,t)}o(Kr,"setUpstreamRequestContext");function Wr(e,t){let r=dD(e),n=pD(t);if(!lD(r.kind,n)){let a=uD[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(Wr,"requireUpstreamRequestContext");var mD="text/html; charset=utf-8",hD="none";function qw(e){return x`<!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??hD}"><main><h1>${e.title}</h1><p>${e.body}</p></main></body></html>`}o(qw,"browserResultHtml");function $w(e,t=200){return new Response(Zt(e),{status:t,headers:{"content-type":mD,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o($w,"browserResultResponse");function xs(e){return $w(qw(e))}o(xs,"browserConnectionSuccessResponse");function Gn(e){let t=Mf(e);return $w(qw({title:t.title,body:t.body,code:e}),400)}o(Gn,"browserConnectionFailureResponse");var fD="text/html; charset=utf-8",gD=16*1024;function _D(e,t=200){return new Response(Zt(e),{status:t,headers:{"content-type":fD,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(_D,"htmlResponse");function yD(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(yD,"safeRedirect");function SD(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(SD,"requireBrowserTicket");function wD(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(wD,"appPasswordTicketMatchesTarget");async function Lw(e){let t=SD(e.browserTicket),r=await rs(t);if(!wD(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(Lw,"readAppPasswordTarget");function vD(e){let t=yl(e.upstreamServerId,e.authProfileId),r=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,n=t.kind==="basic_auth_app_password"?x`<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">`:x`<label for="token">${t.label}</label><input id="token" name="token" type="password" required autocomplete="off">`;return _D(x`<!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(vD,"renderCaptureForm");function Os(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(Os,"readRequiredFormValue");function RD(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(RD,"readCaptureFormTargetInput");async function bD(e){return vD(await Lw(RD(e)))}o(bD,"handleCaptureFormRequest");async function ID(e){let t=await ys(e.request,{maxBytes:gD,label:"App password request body"});return{form:t,target:await Lw({upstreamServerId:e.upstreamServerId,browserTicket:Os(t,"browserTicket")})}}o(ID,"readSubmittedAppPasswordTarget");async function CD(e){let t=En(e.target.ticket);if(await ns(e.target.ticket),yl(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await os({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:Os(e.form,"token")});return}await uy({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:Os(e.form,"username"),appPassword:Os(e.form,"appPassword")})}o(CD,"saveSubmittedAppPasswordCredential");function TD(e,t){return t.ticket.returnTo?yD(e,t.ticket.returnTo):xs({title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(TD,"appPasswordSuccessResponse");async function AD(e){let t=await ID({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await CD(t),TD(e.request.url,t.target)}o(AD,"handleAppPasswordSubmission");function kD(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(kD,"methodNotAllowedResponse");function ED(e){let t=le(e);return Gn(vi(t)?t:"oauth_state_invalid")}o(ED,"appPasswordFailureResponse");async function PD(e){switch(e.request.method){case"GET":return bD(e.appPasswordRequest);case"POST":return AD(e);default:return kD()}}o(PD,"handleAppPasswordMethod");async function up(e,t){let r=Wr(t,"app_password");try{return await PD({request:e,appPasswordRequest:r})}catch(n){return ED(n)}}o(up,"appPasswordHandler");var xD=["callback_authorization_code","callback_provider_error","callback_invalid"];function OD(e){return"cause"in e?e.cause:void 0}o(OD,"readErrorCause");function UD(e){return e.stack?.split(`
1272
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(UD,"readFirstStackFrame");function jw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=UD(r))}o(jw,"addErrorAttributes");function zD(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"),We(e,{eventType:H.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}}),Gn("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"),Gn("oauth_state_invalid");case"callback_authorization_code":return t}}o(zD,"requireAuthorizationCallbackRequest");function ND(e,t){We(e,{eventType:H.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(ND,"emitCallbackReceivedAnalyticsEvent");function DD(e,t){We(e,{eventType:H.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(DD,"emitTokenExchangeSucceededAnalyticsEvent");function MD(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return xs({title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(MD,"buildSuccessfulCallbackResponse");function qD(e){let t={detail:e instanceof Error?e.message:void 0};return jw(t,"error",e),e instanceof Error&&jw(t,"cause",OD(e)),t}o(qD,"buildTokenExchangeFailureAttributes");function $D(e){We(e.context,{eventType:H.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:le(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:qD(e.error)})}o($D,"emitTokenExchangeFailedAnalyticsEvent");function LD(e){let t=le(e);return Gn(vi(t)?t:"upstream_token_exchange_failed")}o(LD,"tokenExchangeFailureResponse");async function dp(e,t){let r=Wr(t,xD),n=zD(t,r);if(n instanceof Response)return n;ND(t,n);try{let a=await Zy({request:e,callbackRequest:n});return DD(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"),MD(e,a)}catch(a){let i={event:"upstream_oauth_token_exchange_failed",code:le(a)??"upstream_token_exchange_failed",upstreamServerId:n.upstreamServerId};return ke(i,"error",a),t.log.warn(i,"Upstream OAuth token exchange failed; user shown connection-failure page"),$D({context:t,callbackRequest:n,error:a}),LD(a)}}o(dp,"callbackHandler");function jD(e){let t=le(e);return t==="unknown_upstream_server"?t:"not_found"}o(jD,"clientMetadataProblemCode");function HD(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(HD,"clientMetadataProblemDetail");async function Hw(e,t){let r=Wr(t,"connect"),n=await Fy({request:e,connectRequest:r});if(We(t,{eventType:H.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 On({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(Hw,"connectHandler");async function Gw(e,t){let r=Wr(t,"client_metadata");try{let n=xy(e.url),a=Oy(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=jD(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"),Ze(e,t,{code:a,detail:HD(n)})}}o(Gw,"oauthClientMetadataHandler");function Kt(e){if(typeof e=="string"&&e.length!==0)return e}o(Kt,"readOptionalQueryString");function GD(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(GD,"requirePathString");function Bw(e){let t=Kt(e);return t?me.parse(t):void 0}o(Bw,"readOptionalVirtualServerId");function BD(e,t){let r=Kt(e);return r?Pe.parse(r):vn(t,"user_oauth")}o(BD,"readOptionalAuthProfileId");function VD(e){let t=Bw(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(VD,"readRequiredVirtualServerId");function FD(e){let t=Kt(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(FD,"readOptionalBrowserTicket");function ZD(e){let t=Vi(Kt(e));return t===void 0?{}:{returnTo:t}}o(ZD,"readOptionalReturnTo");function KD(e){let t=Bw(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(KD,"readOptionalVirtualServerIdContext");function WD(e){let t=Kt(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(WD,"readOptionalProviderErrorDescription");function JD(e){let t=kt(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(JD,"requireConnectableRouteAuth");function YD(e,t,r,n){let a=_s(e,t);if(a.ownerMode==="none"||a.authMode==="tenant_static_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(YD,"buildConnectContextForPrincipal");function XD(e,t,r){let n=En(t),a=kt(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(XD,"buildConnectContextForTicket");async function QD(e,t){let r=JD(hS(t,VD(e.query.virtualServerId))),n=e.query.redirect==="true",a=Kt(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=Tn(e.user,e.url);return YD(r,s,n,ZD(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await rs(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 ns(i),XD(r,i,n)}o(QD,"resolveConnectContext");async function eM(e,t,r){let n=Ee.parse(GD(e,"connection"));switch(r){case"connect":Kr(t,await QD(e,n));return;case"app_password":Kr(t,{kind:"app_password",upstreamServerId:n,...KD(e),...FD(e)});return;case"callback":{let a=Kt(e.query.error);if(a){Kr(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...WD(e)});return}let i=Kt(e.query.code),s=Kt(e.query.state);if(i&&s){Kr(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}Kr(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":Kr(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:BD(e.query.authProfileId,n)});return}}o(eM,"resolveUpstreamRequestInbound");async function tM(e,t,r){try{await eM(e,t,r);return}catch(n){let a=le(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return Ze(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(tM,"applyUpstreamRequestContext");function _a(e,t){return o(async(n,a)=>{let i=await tM(n,a,e);return i||t(n,a)},"wrapped")}o(_a,"withUpstreamRequestContext");var rM={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function nM(){return new Response(null,{status:204,headers:rM})}o(nM,"buildWellKnownPreflightResponse");function oM(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(oM,"withWellKnownCorsHeaders");function lp(e){return async(t,r)=>t.method==="OPTIONS"?nM():oM(await e(t,r))}o(lp,"wrapWellKnownHandler");var aM=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:lp(Tw)},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:lp(Aw)},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:lp(wg)},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:kw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:Ew},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:Pw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:xw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:Ow},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:Uw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:zw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:Nw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:Dw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:_a("client_metadata",Gw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:_a("connect",Hw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:_a("callback",dp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:_a("app_password",up)}];function Vw(e){if(e)return e.find(t=>Ti(t.policyType))}o(Vw,"findMcpOAuthPolicy");function Fw(e){return Vw(e)!==void 0}o(Fw,"shouldRegisterMcpGatewayInternalRoutes");function iM(e){let t=_d(e.policyType);if(!t){let r=yd();throw new et(`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 et(sM(e.name??e.policyType,r),{cause:r}):r}}o(iM,"resolveOAuthConfigFromPolicy");function sM(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
1247
1273
  `);return`MCP OAuth policy "${e}" is misconfigured. Missing/invalid options:
1248
- ${r}`}o(r$,"formatPolicyConfigError");function Ew(e){let t=Tw(e.policies);if(!t){let r=rd(),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 Tt(`MCP gateway: could not find an MCP authorization policy in policies.json. ${n}`)}Dh(t$(t)),wh(yh({routes:e.routes,policies:e.policies}))}o(Ew,"initializeMcpGatewayState");function n$(e,t){return async(r,n)=>{let a=n,s=r.method==="OPTIONS",i=Date.now();s||a.log.info({event:`${e}_received`,method:r.method},`MCP gateway: ${e} received`);try{let c=await t(r,n);return s||a.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-i},`MCP gateway: ${e} responded`),c}catch(c){let d={event:`${e}_threw`,durationMs:Date.now()-i};throw Re(d,"err",c),a.log.error(d,`MCP gateway: ${e} threw`),c}}}o(n$,"wrapInternalHandler");function Aw(e){for(let t of e$){let r=n$(t.routeName,t.handler),n=o((a,s)=>r(a,s),"handler");e.addPluginRoute({path:t.path,methods:t.methods,handler:n,processors:[wi],corsPolicy:"none"})}}o(Aw,"registerMcpGatewayInternalRoutes");var Ml=class extends jl{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;r&&Cw(r.policies)&&(Ew({routes:r.routes,policies:r.policies}),Aw(t.router))}};export{UO as McpAuth0OAuthInboundPolicy,Ml as McpGatewayPlugin,zO as McpOAuthInboundPolicy,LO as McpUpstreamConnectionInboundPolicy,mO as McpVirtualServerHandler};
1274
+ ${r}`}o(sM,"formatPolicyConfigError");function Zw(e){let t=Vw(e.policies);if(!t){let r=yd(),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 et(`MCP gateway: could not find an MCP authorization policy in policies.json. ${n}`)}fg(iM(t)),Jf(Wf({routes:e.routes,policies:e.policies}))}o(Zw,"initializeMcpGatewayState");function cM(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 ke(d,"err",u),a.log.error(d,`MCP gateway: ${e} threw`),u}}}o(cM,"wrapInternalHandler");function Kw(e){for(let t of aM){let r=cM(t.routeName,t.handler),n=o((a,i)=>r(a,i),"handler");e.addPluginRoute({path:t.path,methods:t.methods,handler:n,processors:[Ds],corsPolicy:"none"})}}o(Kw,"registerMcpGatewayInternalRoutes");var pp=class extends yp{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;r&&Fw(r.policies)&&(Zw({routes:r.routes,policies:r.policies}),Kw(t.router))}};export{$0 as McpAuth0OAuthInboundPolicy,pp as McpGatewayPlugin,H0 as McpOAuthInboundPolicy,F0 as McpUpstreamConnectionInboundPolicy,E0 as McpVirtualServerHandler};
1249
1275
  //# sourceMappingURL=index.js.map