@ours.network/mcp 0.17.1 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,67 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
- var iy=Object.create;var ii=Object.defineProperty;var ay=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,ly=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ai=(e,t)=>{for(var r in t)ii(e,r,{get:t[r],enumerable:!0})},dy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of cy(t))!ly.call(e,o)&&o!==r&&ii(e,o,{get:()=>t[o],enumerable:!(n=ay(t,o))||n.enumerable});return e};var nl=(e,t,r)=>(r=e!=null?iy(uy(e)):{},dy(t||!e||!e.__esModule?ii(r,"default",{value:e,enumerable:!0}):r,e));var On=R(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.regexpCode=Q.getEsmExportName=Q.getProperty=Q.safeStringify=Q.stringify=Q.strConcat=Q.addCodeArg=Q.str=Q._=Q.nil=Q._Code=Q.Name=Q.IDENTIFIER=Q._CodeOrName=void 0;var En=class{};Q._CodeOrName=En;Q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rr=class extends En{constructor(t){if(super(),!Q.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}}};Q.Name=rr;var tt=class extends En{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),{})}};Q._Code=tt;Q.nil=new tt("");function Vf(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ea(r,t[n]),r.push(e[++n]);return new tt(r)}Q._=Vf;var Ra=new tt("+");function Hf(e,...t){let r=[In(e[0])],n=0;for(;n<t.length;)r.push(Ra),Ea(r,t[n]),r.push(Ra,In(e[++n]));return _w(r),new tt(r)}Q.str=Hf;function Ea(e,t){t instanceof tt?e.push(...t._items):t instanceof rr?e.push(t):e.push(bw(t))}Q.addCodeArg=Ea;function _w(e){let t=1;for(;t<e.length-1;){if(e[t]===Ra){let r=yw(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function yw(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)}`}function vw(e,t){return t.emptyStr()?e:e.emptyStr()?t:Hf`${e}${t}`}Q.strConcat=vw;function bw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:In(Array.isArray(e)?e.join(","):e)}function ww(e){return new tt(In(e))}Q.stringify=ww;function In(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Q.safeStringify=In;function $w(e){return typeof e=="string"&&Q.IDENTIFIER.test(e)?new tt(`.${e}`):Vf`[${e}]`}Q.getProperty=$w;function Sw(e){if(typeof e=="string"&&Q.IDENTIFIER.test(e))return new tt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Q.getEsmExportName=Sw;function xw(e){return new tt(e.toString())}Q.regexpCode=xw});var Aa=R(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.ValueScope=He.ValueScopeName=He.Scope=He.varKinds=He.UsedValueState=void 0;var Ve=On(),Ia=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},ns;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(ns||(He.UsedValueState=ns={}));He.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var os=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ve.Name?t:this.name(t)}name(t){return new Ve.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}}};He.Scope=os;var ss=class extends Ve.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ve._)`.${new Ve.Name(r)}[${n}]`}};He.ValueScopeName=ss;var kw=(0,Ve._)`\n`,Oa=class extends os{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?kw:Ve.nil}}get(){return this._scope}name(t){return new ss(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 o=this.toName(t),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}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,Ve._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ve.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ns.Started);let l=r(u);if(l){let d=this.opts.es5?He.varKinds.var:He.varKinds.const;s=(0,Ve._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ve._)`${s}${l}${this.opts._n}`;else throw new Ia(u);c.set(u,ns.Completed)})}return s}};He.ValueScope=Oa});var L=R(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var K=On(),ut=Aa(),Ut=On();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return Ut._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return Ut.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return Ut.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return Ut.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return Ut.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return Ut.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return Ut.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return Ut.Name}});var us=Aa();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return us.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return us.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return us.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return us.varKinds}});F.operators={GT:new K._Code(">"),GTE:new K._Code(">="),LT:new K._Code("<"),LTE:new K._Code("<="),EQ:new K._Code("==="),NEQ:new K._Code("!=="),NOT:new K._Code("!"),OR:new K._Code("||"),AND:new K._Code("&&"),ADD:new K._Code("+")};var Pt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Ca=class extends Pt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ut.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Ur(this.rhs,t,r)),this}get names(){return this.rhs instanceof K._CodeOrName?this.rhs.names:{}}},is=class extends Pt{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 K.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Ur(this.rhs,t,r),this}get names(){let t=this.lhs instanceof K.Name?{}:{...this.lhs.names};return cs(t,this.rhs)}},Na=class extends is{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ja=class extends Pt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ma=class extends Pt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ua=class extends Pt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Da=class extends Pt{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=Ur(this.code,t,r),this}get names(){return this.code instanceof K._CodeOrName?this.code.names:{}}},An=class extends Pt{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,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(zw(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>sr(t,r.names),{})}},Rt=class extends An{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Za=class extends An{},Mr=class extends Rt{};Mr.kind="else";var nr=class e extends Rt{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 Mr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Bf(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=Ur(this.condition,t,r),this}get names(){let t=super.names;return cs(t,this.condition),this.else&&sr(t,this.else.names),t}};nr.kind="if";var or=class extends Rt{};or.kind="for";var qa=class extends or{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=Ur(this.iteration,t,r),this}get names(){return sr(super.names,this.iteration.names)}},La=class extends or{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?ut.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=cs(super.names,this.from);return cs(t,this.to)}},as=class extends or{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}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=Ur(this.iterable,t,r),this}get names(){return sr(super.names,this.iterable.names)}},Cn=class extends Rt{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)}};Cn.kind="func";var Nn=class extends An{render(t){return"return "+super.render(t)}};Nn.kind="return";var Fa=class extends Rt{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,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.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}},jn=class extends Rt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};jn.kind="catch";var Mn=class extends Rt{render(t){return"finally"+super.render(t)}};Mn.kind="finally";var Va=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new ut.Scope({parent:t}),this._nodes=[new Za]}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,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ca(t,s,n)),s}const(t,r,n){return this._def(ut.varKinds.const,t,r,n)}let(t,r,n){return this._def(ut.varKinds.let,t,r,n)}var(t,r,n){return this._def(ut.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new is(t,r,n))}add(t,r){return this._leafNode(new Na(t,F.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==K.nil&&this._leafNode(new Da(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,K.addCodeArg)(r,o));return r.push("}"),new K._Code(r)}if(t,r,n){if(this._blockNode(new nr(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 nr(t))}else(){return this._elseNode(new Mr)}endIf(){return this._endBlockNode(nr,Mr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new qa(t),r)}forRange(t,r,n,o,s=this.opts.es5?ut.varKinds.var:ut.varKinds.let){let i=this._scope.toName(t);return this._for(new La(s,i,r,n),()=>o(i))}forOf(t,r,n,o=ut.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof K.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,K._)`${i}.length`,a=>{this.var(s,(0,K._)`${i}[${a}]`),n(s)})}return this._for(new as("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?ut.varKinds.var:ut.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,K._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new as("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(or)}label(t){return this._leafNode(new ja(t))}break(t){return this._leafNode(new Ma(t))}return(t){let r=new Nn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Nn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Fa;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new jn(s),r(s)}return n&&(this._currNode=o.finally=new Mn,this.code(n)),this._endBlockNode(jn,Mn)}throw(t){return this._leafNode(new Ua(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=K.nil,n,o){return this._blockNode(new Cn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Cn)}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 nr))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}};F.CodeGen=Va;function sr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function cs(e,t){return t instanceof K._CodeOrName?sr(e,t.names):e}function Ur(e,t,r){if(e instanceof K.Name)return n(e);if(!o(e))return e;return new K._Code(e._items.reduce((s,i)=>(i instanceof K.Name&&(i=n(i)),i instanceof K._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 o(s){return s instanceof K._Code&&s._items.some(i=>i instanceof K.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function zw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Bf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,K._)`!${Ha(e)}`}F.not=Bf;var Tw=Kf(F.operators.AND);function Pw(...e){return e.reduce(Tw)}F.and=Pw;var Rw=Kf(F.operators.OR);function Ew(...e){return e.reduce(Rw)}F.or=Ew;function Kf(e){return(t,r)=>t===K.nil?r:r===K.nil?t:(0,K._)`${Ha(t)} ${e} ${Ha(r)}`}function Ha(e){return e instanceof K.Name?e:(0,K._)`(${e})`}});var J=R(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;var oe=L(),Iw=On();function Ow(e){let t={};for(let r of e)t[r]=!0;return t}V.toHash=Ow;function Aw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Wf(e,t),!Yf(t,e.self.RULES.all))}V.alwaysValidSchema=Aw;function Wf(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||em(e,`unknown keyword: "${s}"`)}V.checkUnknownRules=Wf;function Yf(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}V.schemaHasRules=Yf;function Cw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}V.schemaHasRulesButRef=Cw;function Nw({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,oe._)`${r}`}return(0,oe._)`${e}${t}${(0,oe.getProperty)(n)}`}V.schemaRefOrVal=Nw;function jw(e){return Qf(decodeURIComponent(e))}V.unescapeFragment=jw;function Mw(e){return encodeURIComponent(Ka(e))}V.escapeFragment=Mw;function Ka(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=Ka;function Qf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=Qf;function Uw(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}V.eachItem=Uw;function Jf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof oe.Name?(s instanceof oe.Name?e(o,s,i):t(o,s,i),i):s instanceof oe.Name?(t(o,i,s),s):r(s,i);return a===oe.Name&&!(c instanceof oe.Name)?n(o,c):c}}V.mergeEvaluated={props:Jf({mergeNames:(e,t,r)=>e.if((0,oe._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,oe._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,oe._)`${r} || {}`).code((0,oe._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,oe._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,oe._)`${r} || {}`),Ja(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Xf}),items:Jf({mergeNames:(e,t,r)=>e.if((0,oe._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,oe._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,oe._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,oe._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Xf(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,oe._)`{}`);return t!==void 0&&Ja(e,r,t),r}V.evaluatedPropsToName=Xf;function Ja(e,t,r){Object.keys(r).forEach(n=>e.assign((0,oe._)`${t}${(0,oe.getProperty)(n)}`,!0))}V.setEvaluated=Ja;var Gf={};function Dw(e,t){return e.scopeValue("func",{ref:t,code:Gf[t.code]||(Gf[t.code]=new Iw._Code(t.code))})}V.useFunc=Dw;var Ba;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ba||(V.Type=Ba={}));function Zw(e,t,r){if(e instanceof oe.Name){let n=t===Ba.Num;return r?n?(0,oe._)`"[" + ${e} + "]"`:(0,oe._)`"['" + ${e} + "']"`:n?(0,oe._)`"/" + ${e}`:(0,oe._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,oe.getProperty)(e).toString():"/"+Ka(e)}V.getErrorPath=Zw;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)}}V.checkStrictMode=em});var Et=R(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Oe=L(),qw={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Ga.default=qw});var Un=R(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.extendErrors=Ae.resetErrorsCount=Ae.reportExtraError=Ae.reportError=Ae.keyword$DataError=Ae.keywordError=void 0;var G=L(),ls=J(),Ue=Et();Ae.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};Ae.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,G.str)`"${e}" keyword must be ${t} ($data)`:(0,G.str)`"${e}" keyword is invalid ($data)`};function Lw(e,t=Ae.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=nm(e,t,r);n??(i||a)?tm(s,c):rm(o,(0,G._)`[${c}]`)}Ae.reportError=Lw;function Fw(e,t=Ae.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=nm(e,t,r);tm(o,a),s||i||rm(n,Ue.default.vErrors)}Ae.reportExtraError=Fw;function Vw(e,t){e.assign(Ue.default.errors,t),e.if((0,G._)`${Ue.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,G._)`${Ue.default.vErrors}.length`,t),()=>e.assign(Ue.default.vErrors,null)))}Ae.resetErrorsCount=Vw;function Hw({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,Ue.default.errors,a=>{e.const(i,(0,G._)`${Ue.default.vErrors}[${a}]`),e.if((0,G._)`${i}.instancePath === undefined`,()=>e.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Ue.default.instancePath,s.errorPath))),e.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,G._)`${i}.schema`,r),e.assign((0,G._)`${i}.data`,n))})}Ae.extendErrors=Hw;function tm(e,t){let r=e.const("err",t);e.if((0,G._)`${Ue.default.vErrors} === null`,()=>e.assign(Ue.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Ue.default.vErrors}.push(${r})`),e.code((0,G._)`${Ue.default.errors}++`)}function rm(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,G._)`new ${e.ValidationError}(${t})`):(r.assign((0,G._)`${n}.errors`,t),r.return(!1))}var ir={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function nm(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,G._)`{}`:Bw(e,t,r)}function Bw(e,t,r={}){let{gen:n,it:o}=e,s=[Kw(o,r),Jw(e,r)];return Gw(e,t,s),n.object(...s)}function Kw({errorPath:e},{instancePath:t}){let r=t?(0,G.str)`${e}${(0,ls.getErrorPath)(t,ls.Type.Str)}`:e;return[Ue.default.instancePath,(0,G.strConcat)(Ue.default.instancePath,r)]}function Jw({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,G.str)`${t}/${e}`;return r&&(o=(0,G.str)`${o}${(0,ls.getErrorPath)(r,ls.Type.Str)}`),[ir.schemaPath,o]}function Gw(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([ir.keyword,o],[ir.params,typeof t=="function"?t(e):t||(0,G._)`{}`]),c.messages&&n.push([ir.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([ir.schema,i],[ir.parentSchema,(0,G._)`${l}${d}`],[Ue.default.data,s]),u&&n.push([ir.propertyName,u])}});var sm=R(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.boolOrEmptySchema=Dr.topBoolOrEmptySchema=void 0;var Ww=Un(),Yw=L(),Qw=Et(),Xw={message:"boolean schema is false"};function e0(e){let{gen:t,schema:r,validateName:n}=e;r===!1?om(e,!1):typeof r=="object"&&r.$async===!0?t.return(Qw.default.data):(t.assign((0,Yw._)`${n}.errors`,null),t.return(!0))}Dr.topBoolOrEmptySchema=e0;function t0(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),om(e)):r.var(t,!0)}Dr.boolOrEmptySchema=t0;function om(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Ww.reportError)(o,Xw,void 0,t)}});var Wa=R(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.getRules=Zr.isJSONType=void 0;var r0=["string","number","integer","boolean","null","object","array"],n0=new Set(r0);function o0(e){return typeof e=="string"&&n0.has(e)}Zr.isJSONType=o0;function s0(){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:{}}}Zr.getRules=s0});var Ya=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.shouldUseRule=Dt.shouldUseGroup=Dt.schemaHasRulesForType=void 0;function i0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&im(e,n)}Dt.schemaHasRulesForType=i0;function im(e,t){return t.rules.some(r=>am(e,r))}Dt.shouldUseGroup=im;function am(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))}Dt.shouldUseRule=am});var Dn=R(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.reportTypeError=Ce.checkDataTypes=Ce.checkDataType=Ce.coerceAndCheckDataType=Ce.getJSONTypes=Ce.getSchemaTypes=Ce.DataType=void 0;var a0=Wa(),c0=Ya(),u0=Un(),q=L(),cm=J(),qr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(qr||(Ce.DataType=qr={}));function l0(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}Ce.getSchemaTypes=l0;function um(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(a0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ce.getJSONTypes=um;function d0(e,t){let{gen:r,data:n,opts:o}=e,s=p0(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,c0.schemaHasRulesForType)(e,t[0]));if(i){let a=Xa(t,n,o.strictNumbers,qr.Wrong);r.if(a,()=>{s.length?f0(e,t,s):ec(e)})}return i}Ce.coerceAndCheckDataType=d0;var lm=new Set(["string","number","integer","boolean","null"]);function p0(e,t){return t?e.filter(r=>lm.has(r)||t==="array"&&r==="array"):[]}function f0(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Xa(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(lm.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ec(e),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),m0(e,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
3
+ var iy=Object.create;var ii=Object.defineProperty;var ay=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,ly=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ai=(e,t)=>{for(var r in t)ii(e,r,{get:t[r],enumerable:!0})},dy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of cy(t))!ly.call(e,o)&&o!==r&&ii(e,o,{get:()=>t[o],enumerable:!(n=ay(t,o))||n.enumerable});return e};var nl=(e,t,r)=>(r=e!=null?iy(uy(e)):{},dy(t||!e||!e.__esModule?ii(r,"default",{value:e,enumerable:!0}):r,e));var An=R(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.regexpCode=Q.getEsmExportName=Q.getProperty=Q.safeStringify=Q.stringify=Q.strConcat=Q.addCodeArg=Q.str=Q._=Q.nil=Q._Code=Q.Name=Q.IDENTIFIER=Q._CodeOrName=void 0;var In=class{};Q._CodeOrName=In;Q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var nr=class extends In{constructor(t){if(super(),!Q.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}}};Q.Name=nr;var tt=class extends In{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 nr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Q._Code=tt;Q.nil=new tt("");function Vf(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Ea(r,t[n]),r.push(e[++n]);return new tt(r)}Q._=Vf;var Ra=new tt("+");function Hf(e,...t){let r=[On(e[0])],n=0;for(;n<t.length;)r.push(Ra),Ea(r,t[n]),r.push(Ra,On(e[++n]));return _w(r),new tt(r)}Q.str=Hf;function Ea(e,t){t instanceof tt?e.push(...t._items):t instanceof nr?e.push(t):e.push(bw(t))}Q.addCodeArg=Ea;function _w(e){let t=1;for(;t<e.length-1;){if(e[t]===Ra){let r=yw(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function yw(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof nr||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 nr))return`"${e}${t.slice(1)}`}function vw(e,t){return t.emptyStr()?e:e.emptyStr()?t:Hf`${e}${t}`}Q.strConcat=vw;function bw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:On(Array.isArray(e)?e.join(","):e)}function ww(e){return new tt(On(e))}Q.stringify=ww;function On(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Q.safeStringify=On;function $w(e){return typeof e=="string"&&Q.IDENTIFIER.test(e)?new tt(`.${e}`):Vf`[${e}]`}Q.getProperty=$w;function Sw(e){if(typeof e=="string"&&Q.IDENTIFIER.test(e))return new tt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Q.getEsmExportName=Sw;function xw(e){return new tt(e.toString())}Q.regexpCode=xw});var Aa=R(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.ValueScope=He.ValueScopeName=He.Scope=He.varKinds=He.UsedValueState=void 0;var Ve=An(),Ia=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},os;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(os||(He.UsedValueState=os={}));He.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var ss=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ve.Name?t:this.name(t)}name(t){return new Ve.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}}};He.Scope=ss;var is=class extends Ve.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ve._)`.${new Ve.Name(r)}[${n}]`}};He.ValueScopeName=is;var kw=(0,Ve._)`\n`,Oa=class extends ss{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?kw:Ve.nil}}get(){return this._scope}name(t){return new is(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 o=this.toName(t),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}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,Ve._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ve.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,os.Started);let l=r(u);if(l){let d=this.opts.es5?He.varKinds.var:He.varKinds.const;s=(0,Ve._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ve._)`${s}${l}${this.opts._n}`;else throw new Ia(u);c.set(u,os.Completed)})}return s}};He.ValueScope=Oa});var L=R(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var K=An(),ut=Aa(),Dt=An();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return Dt._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return Dt.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return Dt.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return Dt.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return Dt.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return Dt.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return Dt.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return Dt.Name}});var ls=Aa();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return ls.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return ls.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return ls.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return ls.varKinds}});F.operators={GT:new K._Code(">"),GTE:new K._Code(">="),LT:new K._Code("<"),LTE:new K._Code("<="),EQ:new K._Code("==="),NEQ:new K._Code("!=="),NOT:new K._Code("!"),OR:new K._Code("||"),AND:new K._Code("&&"),ADD:new K._Code("+")};var Rt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Ca=class extends Rt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ut.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Dr(this.rhs,t,r)),this}get names(){return this.rhs instanceof K._CodeOrName?this.rhs.names:{}}},as=class extends Rt{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 K.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Dr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof K.Name?{}:{...this.lhs.names};return us(t,this.rhs)}},Na=class extends as{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ja=class extends Rt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ma=class extends Rt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ua=class extends Rt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Da=class extends Rt{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=Dr(this.code,t,r),this}get names(){return this.code instanceof K._CodeOrName?this.code.names:{}}},Cn=class extends Rt{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,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(zw(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>ir(t,r.names),{})}},Et=class extends Cn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Za=class extends Cn{},Ur=class extends Et{};Ur.kind="else";var or=class e extends Et{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 Ur(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Bf(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=Dr(this.condition,t,r),this}get names(){let t=super.names;return us(t,this.condition),this.else&&ir(t,this.else.names),t}};or.kind="if";var sr=class extends Et{};sr.kind="for";var qa=class extends sr{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=Dr(this.iteration,t,r),this}get names(){return ir(super.names,this.iteration.names)}},La=class extends sr{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?ut.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=us(super.names,this.from);return us(t,this.to)}},cs=class extends sr{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}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=Dr(this.iterable,t,r),this}get names(){return ir(super.names,this.iterable.names)}},Nn=class extends Et{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)}};Nn.kind="func";var jn=class extends Cn{render(t){return"return "+super.render(t)}};jn.kind="return";var Fa=class extends Et{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,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&ir(t,this.catch.names),this.finally&&ir(t,this.finally.names),t}},Mn=class extends Et{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Mn.kind="catch";var Un=class extends Et{render(t){return"finally"+super.render(t)}};Un.kind="finally";var Va=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new ut.Scope({parent:t}),this._nodes=[new Za]}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,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ca(t,s,n)),s}const(t,r,n){return this._def(ut.varKinds.const,t,r,n)}let(t,r,n){return this._def(ut.varKinds.let,t,r,n)}var(t,r,n){return this._def(ut.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new as(t,r,n))}add(t,r){return this._leafNode(new Na(t,F.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==K.nil&&this._leafNode(new Da(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,K.addCodeArg)(r,o));return r.push("}"),new K._Code(r)}if(t,r,n){if(this._blockNode(new or(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 or(t))}else(){return this._elseNode(new Ur)}endIf(){return this._endBlockNode(or,Ur)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new qa(t),r)}forRange(t,r,n,o,s=this.opts.es5?ut.varKinds.var:ut.varKinds.let){let i=this._scope.toName(t);return this._for(new La(s,i,r,n),()=>o(i))}forOf(t,r,n,o=ut.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof K.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,K._)`${i}.length`,a=>{this.var(s,(0,K._)`${i}[${a}]`),n(s)})}return this._for(new cs("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?ut.varKinds.var:ut.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,K._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new cs("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(sr)}label(t){return this._leafNode(new ja(t))}break(t){return this._leafNode(new Ma(t))}return(t){let r=new jn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(jn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Fa;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new Mn(s),r(s)}return n&&(this._currNode=o.finally=new Un,this.code(n)),this._endBlockNode(Mn,Un)}throw(t){return this._leafNode(new Ua(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=K.nil,n,o){return this._blockNode(new Nn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Nn)}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 or))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}};F.CodeGen=Va;function ir(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function us(e,t){return t instanceof K._CodeOrName?ir(e,t.names):e}function Dr(e,t,r){if(e instanceof K.Name)return n(e);if(!o(e))return e;return new K._Code(e._items.reduce((s,i)=>(i instanceof K.Name&&(i=n(i)),i instanceof K._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 o(s){return s instanceof K._Code&&s._items.some(i=>i instanceof K.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function zw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Bf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,K._)`!${Ha(e)}`}F.not=Bf;var Pw=Kf(F.operators.AND);function Tw(...e){return e.reduce(Pw)}F.and=Tw;var Rw=Kf(F.operators.OR);function Ew(...e){return e.reduce(Rw)}F.or=Ew;function Kf(e){return(t,r)=>t===K.nil?r:r===K.nil?t:(0,K._)`${Ha(t)} ${e} ${Ha(r)}`}function Ha(e){return e instanceof K.Name?e:(0,K._)`(${e})`}});var J=R(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.checkStrictMode=H.getErrorPath=H.Type=H.useFunc=H.setEvaluated=H.evaluatedPropsToName=H.mergeEvaluated=H.eachItem=H.unescapeJsonPointer=H.escapeJsonPointer=H.escapeFragment=H.unescapeFragment=H.schemaRefOrVal=H.schemaHasRulesButRef=H.schemaHasRules=H.checkUnknownRules=H.alwaysValidSchema=H.toHash=void 0;var se=L(),Iw=An();function Ow(e){let t={};for(let r of e)t[r]=!0;return t}H.toHash=Ow;function Aw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Wf(e,t),!Yf(t,e.self.RULES.all))}H.alwaysValidSchema=Aw;function Wf(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||em(e,`unknown keyword: "${s}"`)}H.checkUnknownRules=Wf;function Yf(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}H.schemaHasRules=Yf;function Cw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}H.schemaHasRulesButRef=Cw;function Nw({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${e}${t}${(0,se.getProperty)(n)}`}H.schemaRefOrVal=Nw;function jw(e){return Qf(decodeURIComponent(e))}H.unescapeFragment=jw;function Mw(e){return encodeURIComponent(Ka(e))}H.escapeFragment=Mw;function Ka(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}H.escapeJsonPointer=Ka;function Qf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}H.unescapeJsonPointer=Qf;function Uw(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}H.eachItem=Uw;function Jf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?e(o,s,i):t(o,s,i),i):s instanceof se.Name?(t(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}H.mergeEvaluated={props:Jf({mergeNames:(e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,se._)`${r} || {}`),Ja(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Xf}),items:Jf({mergeNames:(e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,se._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Xf(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,se._)`{}`);return t!==void 0&&Ja(e,r,t),r}H.evaluatedPropsToName=Xf;function Ja(e,t,r){Object.keys(r).forEach(n=>e.assign((0,se._)`${t}${(0,se.getProperty)(n)}`,!0))}H.setEvaluated=Ja;var Gf={};function Dw(e,t){return e.scopeValue("func",{ref:t,code:Gf[t.code]||(Gf[t.code]=new Iw._Code(t.code))})}H.useFunc=Dw;var Ba;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ba||(H.Type=Ba={}));function Zw(e,t,r){if(e instanceof se.Name){let n=t===Ba.Num;return r?n?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:n?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(e).toString():"/"+Ka(e)}H.getErrorPath=Zw;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)}}H.checkStrictMode=em});var It=R(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Oe=L(),qw={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Ga.default=qw});var Dn=R(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.extendErrors=Ae.resetErrorsCount=Ae.reportExtraError=Ae.reportError=Ae.keyword$DataError=Ae.keywordError=void 0;var G=L(),ds=J(),De=It();Ae.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};Ae.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,G.str)`"${e}" keyword must be ${t} ($data)`:(0,G.str)`"${e}" keyword is invalid ($data)`};function Lw(e,t=Ae.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=nm(e,t,r);n??(i||a)?tm(s,c):rm(o,(0,G._)`[${c}]`)}Ae.reportError=Lw;function Fw(e,t=Ae.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=nm(e,t,r);tm(o,a),s||i||rm(n,De.default.vErrors)}Ae.reportExtraError=Fw;function Vw(e,t){e.assign(De.default.errors,t),e.if((0,G._)`${De.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,G._)`${De.default.vErrors}.length`,t),()=>e.assign(De.default.vErrors,null)))}Ae.resetErrorsCount=Vw;function Hw({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,De.default.errors,a=>{e.const(i,(0,G._)`${De.default.vErrors}[${a}]`),e.if((0,G._)`${i}.instancePath === undefined`,()=>e.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(De.default.instancePath,s.errorPath))),e.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,G._)`${i}.schema`,r),e.assign((0,G._)`${i}.data`,n))})}Ae.extendErrors=Hw;function tm(e,t){let r=e.const("err",t);e.if((0,G._)`${De.default.vErrors} === null`,()=>e.assign(De.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${De.default.vErrors}.push(${r})`),e.code((0,G._)`${De.default.errors}++`)}function rm(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,G._)`new ${e.ValidationError}(${t})`):(r.assign((0,G._)`${n}.errors`,t),r.return(!1))}var ar={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function nm(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,G._)`{}`:Bw(e,t,r)}function Bw(e,t,r={}){let{gen:n,it:o}=e,s=[Kw(o,r),Jw(e,r)];return Gw(e,t,s),n.object(...s)}function Kw({errorPath:e},{instancePath:t}){let r=t?(0,G.str)`${e}${(0,ds.getErrorPath)(t,ds.Type.Str)}`:e;return[De.default.instancePath,(0,G.strConcat)(De.default.instancePath,r)]}function Jw({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,G.str)`${t}/${e}`;return r&&(o=(0,G.str)`${o}${(0,ds.getErrorPath)(r,ds.Type.Str)}`),[ar.schemaPath,o]}function Gw(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([ar.keyword,o],[ar.params,typeof t=="function"?t(e):t||(0,G._)`{}`]),c.messages&&n.push([ar.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([ar.schema,i],[ar.parentSchema,(0,G._)`${l}${d}`],[De.default.data,s]),u&&n.push([ar.propertyName,u])}});var sm=R(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.boolOrEmptySchema=Zr.topBoolOrEmptySchema=void 0;var Ww=Dn(),Yw=L(),Qw=It(),Xw={message:"boolean schema is false"};function e0(e){let{gen:t,schema:r,validateName:n}=e;r===!1?om(e,!1):typeof r=="object"&&r.$async===!0?t.return(Qw.default.data):(t.assign((0,Yw._)`${n}.errors`,null),t.return(!0))}Zr.topBoolOrEmptySchema=e0;function t0(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),om(e)):r.var(t,!0)}Zr.boolOrEmptySchema=t0;function om(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Ww.reportError)(o,Xw,void 0,t)}});var Wa=R(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getRules=qr.isJSONType=void 0;var r0=["string","number","integer","boolean","null","object","array"],n0=new Set(r0);function o0(e){return typeof e=="string"&&n0.has(e)}qr.isJSONType=o0;function s0(){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:{}}}qr.getRules=s0});var Ya=R(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.shouldUseRule=Zt.shouldUseGroup=Zt.schemaHasRulesForType=void 0;function i0({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&im(e,n)}Zt.schemaHasRulesForType=i0;function im(e,t){return t.rules.some(r=>am(e,r))}Zt.shouldUseGroup=im;function am(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))}Zt.shouldUseRule=am});var Zn=R(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.reportTypeError=Ce.checkDataTypes=Ce.checkDataType=Ce.coerceAndCheckDataType=Ce.getJSONTypes=Ce.getSchemaTypes=Ce.DataType=void 0;var a0=Wa(),c0=Ya(),u0=Dn(),q=L(),cm=J(),Lr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Lr||(Ce.DataType=Lr={}));function l0(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}Ce.getSchemaTypes=l0;function um(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(a0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ce.getJSONTypes=um;function d0(e,t){let{gen:r,data:n,opts:o}=e,s=p0(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,c0.schemaHasRulesForType)(e,t[0]));if(i){let a=Xa(t,n,o.strictNumbers,Lr.Wrong);r.if(a,()=>{s.length?f0(e,t,s):ec(e)})}return i}Ce.coerceAndCheckDataType=d0;var lm=new Set(["string","number","integer","boolean","null"]);function p0(e,t){return t?e.filter(r=>lm.has(r)||t==="array"&&r==="array"):[]}function f0(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Xa(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(lm.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ec(e),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),m0(e,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
5
5
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
6
6
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,q._)`+${o}`);return;case"boolean":n.elseIf((0,q._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,q._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,q._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,q._)`${i} === "string" || ${i} === "number"
7
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function m0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,q._)`${t} !== undefined`,()=>e.assign((0,q._)`${t}[${r}]`,n))}function Qa(e,t,r,n=qr.Correct){let o=n===qr.Correct?q.operators.EQ:q.operators.NEQ,s;switch(e){case"null":return(0,q._)`${t} ${o} null`;case"array":s=(0,q._)`Array.isArray(${t})`;break;case"object":s=(0,q._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,q._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${t} ${o} ${e}`}return n===qr.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${t} == "number"`,a,r?(0,q._)`isFinite(${t})`:q.nil)}}Ce.checkDataType=Qa;function Xa(e,t,r,n){if(e.length===1)return Qa(e[0],t,r,n);let o,s=(0,cm.toHash)(e);if(s.array&&s.object){let i=(0,q._)`typeof ${t} != "object"`;o=s.null?i:(0,q._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Qa(i,t,r,n));return o}Ce.checkDataTypes=Xa;var h0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,q._)`{type: ${e}}`:(0,q._)`{type: ${t}}`};function ec(e){let t=g0(e);(0,u0.reportError)(t,h0)}Ce.reportTypeError=ec;function g0(e){let{gen:t,data:r,schema:n}=e,o=(0,cm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var pm=R(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.assignDefaults=void 0;var Lr=L(),_0=J();function y0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)dm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>dm(e,s,o.default))}ds.assignDefaults=y0;function dm(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,Lr._)`${s}${(0,Lr.getProperty)(t)}`;if(o){(0,_0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Lr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Lr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Lr._)`${a} = ${(0,Lr.stringify)(r)}`)}});var rt=R(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.validateUnion=re.validateArray=re.usePattern=re.callValidateCode=re.schemaProperties=re.allSchemaProperties=re.noPropertyInData=re.propertyInData=re.isOwnProperty=re.hasPropFunc=re.reportMissingProp=re.checkMissingProp=re.checkReportMissingProp=void 0;var pe=L(),tc=J(),Zt=Et(),v0=J();function b0(e,t){let{gen:r,data:n,it:o}=e;r.if(nc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}re.checkReportMissingProp=b0;function w0({gen:e,data:t,it:{opts:r}},n,o){return(0,pe.or)(...n.map(s=>(0,pe.and)(nc(e,t,s,r.ownProperties),(0,pe._)`${o} = ${s}`)))}re.checkMissingProp=w0;function $0(e,t){e.setParams({missingProperty:t},!0),e.error()}re.reportMissingProp=$0;function fm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}re.hasPropFunc=fm;function rc(e,t,r){return(0,pe._)`${fm(e)}.call(${t}, ${r})`}re.isOwnProperty=rc;function S0(e,t,r,n){let o=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${o} && ${rc(e,t,r)}`:o}re.propertyInData=S0;function nc(e,t,r,n){let o=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(o,(0,pe.not)(rc(e,t,r))):o}re.noPropertyInData=nc;function mm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}re.allSchemaProperties=mm;function x0(e,t){return mm(t).filter(r=>!(0,tc.alwaysValidSchema)(e,t[r]))}re.schemaProperties=x0;function k0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,pe._)`${e}, ${t}, ${n}${o}`:t,d=[[Zt.default.instancePath,(0,pe.strConcat)(Zt.default.instancePath,s)],[Zt.default.parentData,i.parentData],[Zt.default.parentDataProperty,i.parentDataProperty],[Zt.default.rootData,Zt.default.rootData]];i.opts.dynamicRef&&d.push([Zt.default.dynamicAnchors,Zt.default.dynamicAnchors]);let p=(0,pe._)`${l}, ${r.object(...d)}`;return c!==pe.nil?(0,pe._)`${a}.call(${c}, ${p})`:(0,pe._)`${a}(${p})`}re.callValidateCode=k0;var z0=(0,pe._)`new RegExp`;function T0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,pe._)`${o.code==="new RegExp"?z0:(0,v0.useFunc)(e,o)}(${r}, ${n})`})}re.usePattern=T0;function P0(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:tc.Type.Num},s),t.if((0,pe.not)(s),a)})}}re.validateArray=P0;function R0(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,tc.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,pe._)`${i} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,pe.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}re.validateUnion=R0});var _m=R(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateKeywordUsage=gt.validSchemaType=gt.funcKeywordCode=gt.macroKeywordCode=void 0;var De=L(),ar=Et(),E0=rt(),I0=Un();function O0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=gm(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:De.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}gt.macroKeywordCode=O0;function A0(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;N0(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=gm(n,o,u),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)g(),t.modifying&&hm(e),y(()=>e.error());else{let S=t.async?m():h();t.modifying&&hm(e),y(()=>C0(e,S))}}function m(){let S=n.let("ruleErrs",null);return n.try(()=>g((0,De._)`await `),$=>n.assign(d,!1).if((0,De._)`${$} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,De._)`${$}.errors`),()=>n.throw($))),S}function h(){let S=(0,De._)`${l}.errors`;return n.assign(S,null),g(De.nil),S}function g(S=t.async?(0,De._)`await `:De.nil){let $=c.opts.passContext?ar.default.this:ar.default.self,w=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,De._)`${S}${(0,E0.callValidateCode)(e,l,$,w)}`,t.modifying)}function y(S){var $;n.if((0,De.not)(($=t.valid)!==null&&$!==void 0?$:d),S)}}gt.funcKeywordCode=A0;function hm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,De._)`${n.parentData}[${n.parentDataProperty}]`))}function C0(e,t){let{gen:r}=e;r.if((0,De._)`Array.isArray(${t})`,()=>{r.assign(ar.default.vErrors,(0,De._)`${ar.default.vErrors} === null ? ${t} : ${ar.default.vErrors}.concat(${t})`).assign(ar.default.errors,(0,De._)`${ar.default.vErrors}.length`),(0,I0.extendErrors)(e)},()=>e.error())}function N0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}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,De.stringify)(r)})}function j0(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")}gt.validSchemaType=j0;function M0({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}gt.validateKeywordUsage=M0});var vm=R(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.extendSubschemaMode=qt.extendSubschemaData=qt.getSubschema=void 0;var _t=L(),ym=J();function U0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,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 a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,_t._)`${e.schemaPath}${(0,_t.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,_t._)`${e.schemaPath}${(0,_t.getProperty)(t)}${(0,_t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ym.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}qt.getSubschema=U0;function D0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",(0,_t._)`${t.data}${(0,_t.getProperty)(r)}`,!0);c(p),e.errorPath=(0,_t.str)`${u}${(0,ym.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,_t._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let u=o instanceof _t.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}qt.extendSubschemaData=D0;function Z0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}qt.extendSubschemaMode=Z0});var oc=R((lC,bm)=>{"use strict";bm.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var $m=R((dC,wm)=>{"use strict";var Lt=wm.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ps(t,n,o,e,"",e)};Lt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Lt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Lt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Lt.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 ps(e,t,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Lt.arrayKeywords)for(var p=0;p<d.length;p++)ps(e,t,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in Lt.propsKeywords){if(d&&typeof d=="object")for(var m in d)ps(e,t,r,d[m],o+"/"+l+"/"+q0(m),s,o,l,n,m)}else(l in Lt.keywords||e.allKeys&&!(l in Lt.skipKeywords))&&ps(e,t,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function q0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zn=R(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.getSchemaRefs=Be.resolveUrl=Be.normalizeId=Be._getFullPath=Be.getFullPath=Be.inlineRef=void 0;var L0=J(),F0=oc(),V0=$m(),H0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!sc(e):t?Sm(e)<=t:!1}Be.inlineRef=B0;var K0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function sc(e){for(let t in e){if(K0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(sc)||typeof r=="object"&&sc(r))return!0}return!1}function Sm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!H0.has(r)&&(typeof e[r]=="object"&&(0,L0.eachItem)(e[r],n=>t+=Sm(n)),t===1/0))return 1/0}return t}function xm(e,t="",r){r!==!1&&(t=Fr(t));let n=e.parse(t);return km(e,n)}Be.getFullPath=xm;function km(e,t){return e.serialize(t).split("#")[0]+"#"}Be._getFullPath=km;var J0=/#\/?$/;function Fr(e){return e?e.replace(J0,""):""}Be.normalizeId=Fr;function G0(e,t,r){return r=Fr(r),e.resolve(t,r)}Be.resolveUrl=G0;var W0=/^[a-z_][-a-z0-9._]*$/i;function Y0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Fr(e[r]||t),s={"":o},i=xm(n,o,!1),a={},c=new Set;return V0(e,{allKeys:!0},(d,p,m,h)=>{if(h===void 0)return;let g=i+p,y=s[h];typeof d[r]=="string"&&(y=S.call(this,d[r])),$.call(this,d.$anchor),$.call(this,d.$dynamicAnchor),s[p]=y;function S(w){let P=this.opts.uriResolver.resolve;if(w=Fr(y?P(y,w):w),c.has(w))throw l(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,w):w!==Fr(g)&&(w[0]==="#"?(u(d,a[w],w),a[w]=d):this.refs[w]=g),w}function $(w){if(typeof w=="string"){if(!W0.test(w))throw new Error(`invalid anchor "${w}"`);S.call(this,`#${w}`)}}}),a;function u(d,p,m){if(p!==void 0&&!F0(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Be.getSchemaRefs=Y0});var Fn=R(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.getData=Ft.KeywordCxt=Ft.validateFunctionCode=void 0;var Em=sm(),zm=Dn(),ac=Ya(),fs=Dn(),Q0=pm(),Ln=_m(),ic=vm(),O=L(),D=Et(),X0=Zn(),It=J(),qn=Un();function e$(e){if(Am(e)&&(Cm(e),Om(e))){n$(e);return}Im(e,()=>(0,Em.topBoolOrEmptySchema)(e))}Ft.validateFunctionCode=e$;function Im({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,O._)`${D.default.data}, ${D.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${Tm(r,o)}`),r$(e,o),e.code(s)}):e.func(t,(0,O._)`${D.default.data}, ${t$(o)}`,n.$async,()=>e.code(Tm(r,o)).code(s))}function t$(e){return(0,O._)`{${D.default.instancePath}="", ${D.default.parentData}, ${D.default.parentDataProperty}, ${D.default.rootData}=${D.default.data}${e.dynamicRef?(0,O._)`, ${D.default.dynamicAnchors}={}`:O.nil}}={}`}function r$(e,t){e.if(D.default.valCxt,()=>{e.var(D.default.instancePath,(0,O._)`${D.default.valCxt}.${D.default.instancePath}`),e.var(D.default.parentData,(0,O._)`${D.default.valCxt}.${D.default.parentData}`),e.var(D.default.parentDataProperty,(0,O._)`${D.default.valCxt}.${D.default.parentDataProperty}`),e.var(D.default.rootData,(0,O._)`${D.default.valCxt}.${D.default.rootData}`),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,O._)`${D.default.valCxt}.${D.default.dynamicAnchors}`)},()=>{e.var(D.default.instancePath,(0,O._)`""`),e.var(D.default.parentData,(0,O._)`undefined`),e.var(D.default.parentDataProperty,(0,O._)`undefined`),e.var(D.default.rootData,D.default.data),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,O._)`{}`)})}function n$(e){let{schema:t,opts:r,gen:n}=e;Im(e,()=>{r.$comment&&t.$comment&&jm(e),c$(e),n.let(D.default.vErrors,null),n.let(D.default.errors,0),r.unevaluated&&o$(e),Nm(e),d$(e)})}function o$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,O._)`${r}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}function Tm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}function s$(e,t){if(Am(e)&&(Cm(e),Om(e))){i$(e,t);return}(0,Em.boolOrEmptySchema)(e,t)}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}function Am(e){return typeof e.schema!="boolean"}function i$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&jm(e),u$(e),l$(e);let s=n.const("_errs",D.default.errors);Nm(e,s),n.var(t,(0,O._)`${s} === ${D.default.errors}`)}function Cm(e){(0,It.checkUnknownRules)(e),a$(e)}function Nm(e,t){if(e.opts.jtd)return Pm(e,[],!1,t);let r=(0,zm.getSchemaTypes)(e.schema),n=(0,zm.coerceAndCheckDataType)(e,r);Pm(e,r,!n,t)}function a$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,It.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function c$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,It.checkStrictMode)(e,"default is ignored in the schema root")}function u$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,X0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function l$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function jm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,O._)`${D.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,O.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,O._)`${D.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function d$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,O._)`${D.default.errors} === 0`,()=>t.return(D.default.data),()=>t.throw((0,O._)`new ${o}(${D.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,D.default.vErrors),s.unevaluated&&p$(e),t.return((0,O._)`${D.default.errors} === 0`))}function p$({gen:e,evaluated:t,props:r,items:n}){r instanceof O.Name&&e.assign((0,O._)`${t}.props`,r),n instanceof O.Name&&e.assign((0,O._)`${t}.items`,n)}function Pm(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,It.schemaHasRulesButRef)(s,l))){o.block(()=>Um(e,"$ref",l.all.$ref.definition));return}c.jtd||f$(e,t),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,ac.shouldUseGroup)(s,p)&&(p.type?(o.if((0,fs.checkDataType)(p.type,i,c.strictNumbers)),Rm(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,fs.reportTypeError)(e)),o.endIf()):Rm(e,p),a||o.if((0,O._)`${D.default.errors} === ${n||0}`))}}function Rm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,Q0.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,ac.shouldUseRule)(n,s)&&Um(e,s.keyword,s.definition,t.type)})}function f$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(m$(e,t),e.opts.allowUnionTypes||h$(e,t),g$(e,e.dataTypes))}function m$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Mm(e.dataTypes,r)||cc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),y$(e,t)}}function h$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&cc(e,"use allowUnionTypes to allow union type keyword")}function g$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ac.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>_$(t,i))&&cc(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function _$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Mm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y$(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}function cc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,It.checkStrictMode)(e,t,e.opts.strictTypes)}var ms=class{constructor(t,r,n){if((0,Ln.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,It.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",Dm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Ln.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,O.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,O.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,O._)`${r} !== undefined && (${(0,O.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?qn.reportExtraError:qn.reportError)(this,this.def.error,r)}$dataError(){(0,qn.reportError)(this,this.def.$dataError||qn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,qn.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=O.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,O.or)((0,O._)`${o} === undefined`,r)),t!==O.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==O.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,O.or)(i(),a());function i(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,O._)`${(0,fs.checkDataTypes)(c,r,s.opts.strictNumbers,fs.DataType.Wrong)}`}return O.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,O._)`!${c}(${r})`}return O.nil}}subschema(t,r){let n=(0,ic.getSubschema)(this.it,t);(0,ic.extendSubschemaData)(n,this.it,t),(0,ic.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return s$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=It.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=It.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,O.Name)),!0}};Ft.KeywordCxt=ms;function Um(e,t,r,n){let o=new ms(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ln.funcKeywordCode)(o,r):"macro"in r?(0,Ln.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ln.funcKeywordCode)(o,r)}var v$=/^\/(?:[^~]|~0|~1)*$/,b$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return D.default.rootData;if(e[0]==="/"){if(!v$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=D.default.rootData}else{let u=b$.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(s=r[t-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,O._)`${s}${(0,O.getProperty)((0,It.unescapeJsonPointer)(u))}`,i=(0,O._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Ft.getData=Dm});var hs=R(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var uc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};lc.default=uc});var Vn=R(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var dc=Zn(),pc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,dc.resolveUrl)(t,r,n),this.missingSchema=(0,dc.normalizeId)((0,dc.getFullPath)(t,this.missingRef))}};fc.default=pc});var _s=R(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.resolveSchema=nt.getCompilingSchema=nt.resolveRef=nt.compileSchema=nt.SchemaEnv=void 0;var lt=L(),w$=hs(),cr=Et(),dt=Zn(),Zm=J(),$$=Fn(),Vr=class{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,dt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};nt.SchemaEnv=Vr;function hc(e){let t=qm.call(this,e);if(t)return t;let r=(0,dt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new lt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:w$.default,code:(0,lt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:cr.default.data,parentData:cr.default.parentData,parentDataProperty:cr.default.parentDataProperty,dataNames:[cr.default.data],dataPathArr:[lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,lt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:lt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,$$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(cr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let m=new Function(`${cr.default.self}`,`${cr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof lt.Name?void 0:h,items:g instanceof lt.Name?void 0:g,dynamicProps:h instanceof lt.Name,dynamicItems:g instanceof lt.Name},m.source&&(m.source.evaluated=(0,lt.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(e)}}nt.compileSchema=hc;function S$(e,t,r){var n;r=(0,dt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=z$.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Vr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=x$.call(this,s)}nt.resolveRef=S$;function x$(e){return(0,dt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:hc.call(this,e)}function qm(e){for(let t of this._compilations)if(k$(t,e))return t}nt.getCompilingSchema=qm;function k$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function z$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||gs.call(this,e,t)}function gs(e,t){let r=this.opts.uriResolver.parse(t),n=(0,dt._getFullPath)(this.opts.uriResolver,r),o=(0,dt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return mc.call(this,r,e);let s=(0,dt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=gs.call(this,e,i);return typeof a?.schema!="object"?void 0:mc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||hc.call(this,i),s===(0,dt.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,dt.resolveUrl)(this.opts.uriResolver,o,u)),new Vr({schema:a,schemaId:c,root:e,baseId:o})}return mc.call(this,r,i)}}nt.resolveSchema=gs;var T$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function mc(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Zm.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!T$.has(a)&&u&&(t=(0,dt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Zm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=gs.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Vr({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var Lm=R((_C,P$)=>{P$.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 yc=R((yC,Jm)=>{"use strict";var R$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Vm=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),gc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),E$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function _c(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}var I$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fm(e){return e.length=0,!0}function O$(e,t,r){if(e.length){let n=_c(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function A$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=O$;for(let c=0;c<e.length;c++){let u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Fm}else{o.push(u);continue}}return o.length&&(a===Fm?r.zone=o.join(""):i?n.push(o.join("")):n.push(_c(o))),r.address=n.join(""),r}function Bm(e){if(C$(e,":")<2)return{host:e,isIPV6:!1};let t=A$(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}}}function C$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function N$(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===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("")}var j$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},M$=/[@/?#:]/g,U$=/[@/?#]/g;function Km(e,t){let r=t?U$:M$;return r.lastIndex=0,e.replace(r,n=>j$[n])}function D$(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(gc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Hm(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function Z$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(gc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Hm(s)?t+=s:t+="%"+o,r+=2;continue}}E$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function q$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(gc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function L$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Vm(r)){let n=Bm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Km(r,!1)}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}Jm.exports={nonSimpleDomain:I$,recomposeAuthority:L$,reescapeHostDelimiters:Km,normalizePercentEncoding:D$,normalizePathEncoding:Z$,escapePreservingEscapes:q$,removeDotSegments:N$,isIPv4:Vm,isUUID:R$,normalizeIPv6:Bm,stringArrayToHexStripped:_c}});var Xm=R((vC,Qm)=>{"use strict";var{isUUID:F$}=yc(),V$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,H$=["http","https","ws","wss","urn","urn:uuid"];function B$(e){return H$.indexOf(e)!==-1}function vc(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Gm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Wm(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}function K$(e){return e.secure=vc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function J$(e){if((e.port===(vc(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}function G$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(V$);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=bc(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function W$(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(),o=`${r}:${t.nid||n}`,s=bc(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function Y$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!F$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Q$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ym={scheme:"http",domainHost:!0,parse:Gm,serialize:Wm},X$={scheme:"https",domainHost:Ym.domainHost,parse:Gm,serialize:Wm},ys={scheme:"ws",domainHost:!0,parse:K$,serialize:J$},eS={scheme:"wss",domainHost:ys.domainHost,parse:ys.parse,serialize:ys.serialize},tS={scheme:"urn",parse:G$,serialize:W$,skipNormalize:!0},rS={scheme:"urn:uuid",parse:Y$,serialize:Q$,skipNormalize:!0},vs={http:Ym,https:X$,ws:ys,wss:eS,urn:tS,"urn:uuid":rS};Object.setPrototypeOf(vs,null);function bc(e){return e&&(vs[e]||vs[e.toLowerCase()])||void 0}Qm.exports={wsIsSecure:vc,SCHEMES:vs,isValidSchemeName:B$,getSchemeHandler:bc}});var sh=R((bC,bs)=>{"use strict";var{normalizeIPv6:nS,removeDotSegments:Hn,recomposeAuthority:oS,normalizePercentEncoding:sS,normalizePathEncoding:iS,escapePreservingEscapes:aS,reescapeHostDelimiters:cS,isIPv4:uS,nonSimpleDomain:lS}=yc(),{SCHEMES:dS,getSchemeHandler:th}=Xm();function pS(e,t){return typeof e=="string"?e=yS(e,t):typeof e=="object"&&(e=Hr(ur(e,t),t)),e}function fS(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=rh(Hr(e,n),Hr(t,n),n,!0);return n.skipEscape=!0,ur(o,n)}function rh(e,t,r,n){let o={};return n||(e=Hr(ur(e,r),r),t=Hr(ur(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Hn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Hn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Hn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=Hn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function mS(e,t,r){let n=eh(e,r),o=eh(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function ur(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),o=[],s=th(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=sS(r.path):(r.path=aS(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=oS(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Hn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var hS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function _S(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function nh(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},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(gS);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=e.match(hS);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=_S(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(uS(n.host)===!1){let d=nS(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!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 u=th(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&lS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=cS(unescape(n.host),s))),n.path&&(n.path=iS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Hr(e,t){return nh(e,t).parsed}function yS(e,t){return oh(e,t).normalized}function oh(e,t){let{parsed:r,malformedAuthorityOrPort:n}=nh(e,t);return{normalized:n?e:ur(r,t),malformedAuthorityOrPort:n}}function eh(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=oh(e,t);return n?void 0:r}if(typeof e=="object")return ur(e,t)}var wc={SCHEMES:dS,normalize:pS,resolve:fS,resolveComponent:rh,equal:mS,serialize:ur,parse:Hr};bs.exports=wc;bs.exports.default=wc;bs.exports.fastUri=wc});var ah=R($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var ih=sh();ih.code='require("ajv/dist/runtime/uri").default';$c.default=ih});var hh=R(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 vS=Fn();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:function(){return vS.KeywordCxt}});var Br=L();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return Br._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return Br.str}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return Br.stringify}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return Br.nil}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return Br.Name}});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:function(){return Br.CodeGen}});var bS=hs(),ph=Vn(),wS=Wa(),Bn=_s(),$S=L(),Kn=Zn(),ws=Dn(),xc=J(),ch=Lm(),SS=ah(),fh=(e,t)=>new RegExp(e,t);fh.code="new RegExp";var xS=["removeAdditional","useDefaults","coerceTypes"],kS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),zS={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."},TS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},uh=200;function PS(e){var t,r,n,o,s,i,a,c,u,l,d,p,m,h,g,y,S,$,w,P,v,k,A,W,ie;let be=e.strict,qe=(t=e.code)===null||t===void 0?void 0:t.optimize,je=qe===!0||qe===void 0?1:qe||0,St=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:fh,Qe=(o=e.uriResolver)!==null&&o!==void 0?o:SS.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:be)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:be)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:be)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:be)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:be)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:je,regExp:St}:{optimize:je,regExp:St},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:uh,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:uh,meta:(S=e.meta)!==null&&S!==void 0?S:!0,messages:($=e.messages)!==null&&$!==void 0?$:!0,inlineRefs:(w=e.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(v=e.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(A=e.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(W=e.unicodeRegExp)!==null&&W!==void 0?W:!0,int32range:(ie=e.int32range)!==null&&ie!==void 0?ie:!0,uriResolver:Qe}}var Jn=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...PS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new $S.ValueScope({scope:{},prefixes:kS,es5:r,lines:n}),this.logger=CS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,wS.getRules)(),lh.call(this,zS,t,"NOT SUPPORTED"),lh.call(this,TS,t,"DEPRECATED","warn"),this._metaOpts=OS.call(this),t.formats&&ES.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&IS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),RS.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=ch;n==="id"&&(o={...ch},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[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 o=n(r);return"$async"in n||(this.errors=n.errors),o}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 o.call(this,t,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof ph.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);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,Kn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!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 o=this.validate(n,t);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let r;for(;typeof(r=dh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Bn.SchemaEnv({schema:{},schemaId:n});if(r=Bn.resolveSchema.call(this,o,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=dh.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,Kn.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(jS.call(this,n,r),!r)return(0,xc.eachItem)(n,s=>Sc.call(this,s)),this;US.call(this,r);let o={...r,type:(0,ws.getJSONTypes)(r.type),schemaType:(0,ws.getJSONTypes)(r.schemaType)};return(0,xc.eachItem)(n,o.type.length===0?s=>Sc.call(this,s,o):s=>o.type.forEach(i=>Sc.call(this,s,o,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 o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,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(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=mh(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];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 c=this._cache.get(t);if(c!==void 0)return c;n=(0,Kn.normalizeId)(i||n);let u=Kn.getSchemaRefs.call(this,t,n);return c=new Bn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_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):Bn.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{Bn.compileSchema.call(this,t)}finally{this.opts=r}}};Jn.ValidationError=bS.default;Jn.MissingRefError=ph.default;Te.default=Jn;function lh(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function dh(e){return e=(0,Kn.normalizeId)(e),this.schemas[e]||this.refs[e]}function RS(){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)}function ES(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function IS(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)}}function OS(){let e={...this.opts};for(let t of xS)delete e[t];return e}var AS={log(){},warn(){},error(){}};function CS(e){if(e===!1)return AS;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")}var NS=/^[a-z_$][a-z0-9_$:-]*$/i;function jS(e,t){let{RULES:r}=this;if((0,xc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!NS.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')}function Sc(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,ws.getJSONTypes)(t.type),schemaType:(0,ws.getJSONTypes)(t.schemaType)}};t.before?MS.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function MS(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function US(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=mh(t)),e.validateSchema=this.compile(t,!0))}var DS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mh(e){return{anyOf:[e,DS]}}});var gh=R(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var ZS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};kc.default=ZS});var bh=R(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.callRef=lr.getValidate=void 0;var qS=Vn(),_h=rt(),Ke=L(),Kr=Et(),yh=_s(),$s=J(),LS={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=yh.resolveRef.call(c,u,o,r);if(l===void 0)throw new qS.default(n.opts.uriResolver,o,r);if(l instanceof yh.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return Ss(e,i,s,s.$async);let h=t.scopeValue("root",{ref:u});return Ss(e,(0,Ke._)`${h}.validate`,u,u.$async)}function p(h){let g=vh(e,h);Ss(e,g,h,h.$async)}function m(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Ke.stringify)(h)}:{ref:h}),y=t.name("valid"),S=e.subschema({schema:h,dataTypes:[],schemaPath:Ke.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(S),e.ok(y)}}};function vh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ke._)`${r.scopeValue("wrapper",{ref:t})}.validate`}lr.getValidate=vh;function Ss(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Kr.default.this:Ke.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Ke._)`await ${(0,_h.callValidateCode)(e,t,u)}`),m(t),i||o.assign(h,!0)},g=>{o.if((0,Ke._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,_h.callValidateCode)(e,t,u),()=>m(t),()=>p(t))}function p(h){let g=(0,Ke._)`${h}.errors`;o.assign(Kr.default.vErrors,(0,Ke._)`${Kr.default.vErrors} === null ? ${g} : ${Kr.default.vErrors}.concat(${g})`),o.assign(Kr.default.errors,(0,Ke._)`${Kr.default.vErrors}.length`)}function m(h){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=$s.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,Ke._)`${h}.evaluated.props`);s.props=$s.mergeEvaluated.props(o,S,s.props,Ke.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=$s.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,Ke._)`${h}.evaluated.items`);s.items=$s.mergeEvaluated.items(o,S,s.items,Ke.Name)}}}lr.callRef=Ss;lr.default=LS});var wh=R(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var FS=gh(),VS=bh(),HS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",FS.default,VS.default];zc.default=HS});var $h=R(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var xs=L(),Vt=xs.operators,ks={maximum:{okStr:"<=",ok:Vt.LTE,fail:Vt.GT},minimum:{okStr:">=",ok:Vt.GTE,fail:Vt.LT},exclusiveMaximum:{okStr:"<",ok:Vt.LT,fail:Vt.GTE},exclusiveMinimum:{okStr:">",ok:Vt.GT,fail:Vt.LTE}},BS={message:({keyword:e,schemaCode:t})=>(0,xs.str)`must be ${ks[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,xs._)`{comparison: ${ks[e].okStr}, limit: ${t}}`},KS={keyword:Object.keys(ks),type:"number",schemaType:"number",$data:!0,error:BS,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,xs._)`${r} ${ks[t].fail} ${n} || isNaN(${r})`)}};Tc.default=KS});var Sh=R(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Gn=L(),JS={message:({schemaCode:e})=>(0,Gn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Gn._)`{multipleOf: ${e}}`},GS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,Gn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Gn._)`${i} !== parseInt(${i})`;e.fail$data((0,Gn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Pc.default=GS});var kh=R(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});function xh(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Rc.default=xh;xh.code='require("ajv/dist/runtime/ucs2length").default'});var zh=R(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var dr=L(),WS=J(),YS=kh(),QS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,dr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,dr._)`{limit: ${e}}`},XS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?dr.operators.GT:dr.operators.LT,i=o.opts.unicode===!1?(0,dr._)`${r}.length`:(0,dr._)`${(0,WS.useFunc)(e.gen,YS.default)}(${r})`;e.fail$data((0,dr._)`${i} ${s} ${n}`)}};Ec.default=XS});var Th=R(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var ex=rt(),tx=J(),Jr=L(),rx={message:({schemaCode:e})=>(0,Jr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Jr._)`{pattern: ${e}}`},nx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:rx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Jr._)`new RegExp`:(0,tx.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Jr._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,Jr._)`!${l}`)}else{let c=(0,ex.usePattern)(e,o);e.fail$data((0,Jr._)`!${c}.test(${r})`)}}};Ic.default=nx});var Ph=R(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Wn=L(),ox={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Wn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Wn._)`{limit: ${e}}`},sx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ox,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?Wn.operators.GT:Wn.operators.LT;e.fail$data((0,Wn._)`Object.keys(${r}).length ${o} ${n}`)}};Oc.default=sx});var Rh=R(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Yn=rt(),Qn=L(),ix=J(),ax={message:({params:{missingProperty:e}})=>(0,Qn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Qn._)`{missingProperty: ${e}}`},cx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ax,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,ix.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Qn.nil,d);else for(let m of r)(0,Yn.checkReportMissingProp)(e,m)}function l(){let m=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>p(m,h)),e.ok(h)}else t.if((0,Yn.checkMissingProp)(e,r,m)),(0,Yn.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,Yn.noPropertyInData)(t,o,m,a.ownProperties),()=>e.error())})}function p(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,Yn.propertyInData)(t,o,m,a.ownProperties)),t.if((0,Qn.not)(h),()=>{e.error(),t.break()})},Qn.nil)}}};Ac.default=cx});var Eh=R(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var Xn=L(),ux={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Xn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Xn._)`{limit: ${e}}`},lx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ux,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Xn.operators.GT:Xn.operators.LT;e.fail$data((0,Xn._)`${r}.length ${o} ${n}`)}};Cc.default=lx});var zs=R(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Ih=oc();Ih.code='require("ajv/dist/runtime/equal").default';Nc.default=Ih});var Oh=R(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var jc=Dn(),Pe=L(),dx=J(),px=zs(),fx={message:({params:{i:e,j:t}})=>(0,Pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Pe._)`{i: ${e}, j: ${t}}`},mx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:fx,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),u=s.items?(0,jc.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,Pe._)`${i} === false`),e.ok(c);function l(){let h=t.let("i",(0,Pe._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,Pe._)`${h} > 1`,()=>(d()?p:m)(h,g))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let y=t.name("item"),S=(0,jc.checkDataTypes)(u,y,a.opts.strictNumbers,jc.DataType.Wrong),$=t.const("indices",(0,Pe._)`{}`);t.for((0,Pe._)`;${h}--;`,()=>{t.let(y,(0,Pe._)`${r}[${h}]`),t.if(S,(0,Pe._)`continue`),u.length>1&&t.if((0,Pe._)`typeof ${y} == "string"`,(0,Pe._)`${y} += "_"`),t.if((0,Pe._)`typeof ${$}[${y}] == "number"`,()=>{t.assign(g,(0,Pe._)`${$}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,Pe._)`${$}[${y}] = ${h}`)})}function m(h,g){let y=(0,dx.useFunc)(t,px.default),S=t.name("outer");t.label(S).for((0,Pe._)`;${h}--;`,()=>t.for((0,Pe._)`${g} = ${h}; ${g}--;`,()=>t.if((0,Pe._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(S)})))}}};Mc.default=mx});var Ah=R(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Uc=L(),hx=J(),gx=zs(),_x={message:"must be equal to constant",params:({schemaCode:e})=>(0,Uc._)`{allowedValue: ${e}}`},yx={keyword:"const",$data:!0,error:_x,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Uc._)`!${(0,hx.useFunc)(t,gx.default)}(${r}, ${o})`):e.fail((0,Uc._)`${s} !== ${r}`)}};Dc.default=yx});var Ch=R(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var eo=L(),vx=J(),bx=zs(),wx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,eo._)`{allowedValues: ${e}}`},$x={keyword:"enum",schemaType:"array",$data:!0,error:wx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,vx.useFunc)(t,bx.default)),l;if(a||n)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=t.const("vSchema",s);l=(0,eo.or)(...o.map((h,g)=>p(m,g)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,m=>t.if((0,eo._)`${u()}(${r}, ${m})`,()=>t.assign(l,!0).break()))}function p(m,h){let g=o[h];return typeof g=="object"&&g!==null?(0,eo._)`${u()}(${r}, ${m}[${h}])`:(0,eo._)`${r} === ${g}`}}};Zc.default=$x});var Nh=R(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Sx=$h(),xx=Sh(),kx=zh(),zx=Th(),Tx=Ph(),Px=Rh(),Rx=Eh(),Ex=Oh(),Ix=Ah(),Ox=Ch(),Ax=[Sx.default,xx.default,kx.default,zx.default,Tx.default,Px.default,Rx.default,Ex.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ix.default,Ox.default];qc.default=Ax});var Fc=R(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.validateAdditionalItems=void 0;var pr=L(),Lc=J(),Cx={message:({params:{len:e}})=>(0,pr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,pr._)`{limit: ${e}}`},Nx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Cx,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Lc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}jh(e,n)}};function jh(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,pr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,pr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Lc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,pr._)`${a} <= ${t.length}`);r.if((0,pr.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Lc.Type.Num},u),i.allErrors||r.if((0,pr.not)(u),()=>r.break())})}}to.validateAdditionalItems=jh;to.default=Nx});var Vc=R(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.validateTuple=void 0;var Mh=L(),Ts=J(),jx=rt(),Mx={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,Ts.alwaysValidSchema)(r,t)&&e.ok((0,jx.validateArray)(e))}};function Uh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ts.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Mh._)`${s}.length`);r.forEach((d,p)=>{(0,Ts.alwaysValidSchema)(a,d)||(n.if((0,Mh._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Ts.checkStrictMode)(a,y,p.strictTuples)}}}ro.validateTuple=Uh;ro.default=Mx});var Dh=R(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Ux=Vc(),Dx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ux.validateTuple)(e,"items")};Hc.default=Dx});var qh=R(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Zh=L(),Zx=J(),qx=rt(),Lx=Fc(),Fx={message:({params:{len:e}})=>(0,Zh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zh._)`{limit: ${e}}`},Vx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Fx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,Zx.alwaysValidSchema)(n,t)&&(o?(0,Lx.validateAdditionalItems)(e,o):e.ok((0,qx.validateArray)(e)))}};Bc.default=Vx});var Lh=R(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var ot=L(),Ps=J(),Hx={message:({params:{min:e,max:t}})=>t===void 0?(0,ot.str)`must contain at least ${e} valid item(s)`:(0,ot.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ot._)`{minContains: ${e}}`:(0,ot._)`{minContains: ${e}, maxContains: ${t}}`},Bx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Hx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=t.const("len",(0,ot._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ps.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ps.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ps.alwaysValidSchema)(s,r)){let g=(0,ot._)`${l} >= ${i}`;a!==void 0&&(g=(0,ot._)`${g} && ${l} <= ${a}`),e.pass(g);return}s.items=!0;let d=t.name("valid");a===void 0&&i===1?m(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,!0),a!==void 0&&t.if((0,ot._)`${o}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let g=t.name("_valid"),y=t.let("count",0);m(g,()=>t.if(g,()=>h(y)))}function m(g,y){t.forRange("i",0,l,S=>{e.subschema({keyword:"contains",dataProp:S,dataPropType:Ps.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,ot._)`${g}++`),a===void 0?t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,ot._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Kc.default=Bx});var Hh=R(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.validateSchemaDeps=yt.validatePropertyDeps=yt.error=void 0;var Jc=L(),Kx=J(),no=rt();yt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Jc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Jc._)`{property: ${e},
7
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function m0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,q._)`${t} !== undefined`,()=>e.assign((0,q._)`${t}[${r}]`,n))}function Qa(e,t,r,n=Lr.Correct){let o=n===Lr.Correct?q.operators.EQ:q.operators.NEQ,s;switch(e){case"null":return(0,q._)`${t} ${o} null`;case"array":s=(0,q._)`Array.isArray(${t})`;break;case"object":s=(0,q._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,q._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${t} ${o} ${e}`}return n===Lr.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${t} == "number"`,a,r?(0,q._)`isFinite(${t})`:q.nil)}}Ce.checkDataType=Qa;function Xa(e,t,r,n){if(e.length===1)return Qa(e[0],t,r,n);let o,s=(0,cm.toHash)(e);if(s.array&&s.object){let i=(0,q._)`typeof ${t} != "object"`;o=s.null?i:(0,q._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Qa(i,t,r,n));return o}Ce.checkDataTypes=Xa;var h0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,q._)`{type: ${e}}`:(0,q._)`{type: ${t}}`};function ec(e){let t=g0(e);(0,u0.reportError)(t,h0)}Ce.reportTypeError=ec;function g0(e){let{gen:t,data:r,schema:n}=e,o=(0,cm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var pm=R(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.assignDefaults=void 0;var Fr=L(),_0=J();function y0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)dm(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>dm(e,s,o.default))}ps.assignDefaults=y0;function dm(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,Fr._)`${s}${(0,Fr.getProperty)(t)}`;if(o){(0,_0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Fr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Fr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fr._)`${a} = ${(0,Fr.stringify)(r)}`)}});var rt=R(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var pe=L(),tc=J(),qt=It(),v0=J();function b0(e,t){let{gen:r,data:n,it:o}=e;r.if(nc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}ne.checkReportMissingProp=b0;function w0({gen:e,data:t,it:{opts:r}},n,o){return(0,pe.or)(...n.map(s=>(0,pe.and)(nc(e,t,s,r.ownProperties),(0,pe._)`${o} = ${s}`)))}ne.checkMissingProp=w0;function $0(e,t){e.setParams({missingProperty:t},!0),e.error()}ne.reportMissingProp=$0;function fm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}ne.hasPropFunc=fm;function rc(e,t,r){return(0,pe._)`${fm(e)}.call(${t}, ${r})`}ne.isOwnProperty=rc;function S0(e,t,r,n){let o=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${o} && ${rc(e,t,r)}`:o}ne.propertyInData=S0;function nc(e,t,r,n){let o=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(o,(0,pe.not)(rc(e,t,r))):o}ne.noPropertyInData=nc;function mm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ne.allSchemaProperties=mm;function x0(e,t){return mm(t).filter(r=>!(0,tc.alwaysValidSchema)(e,t[r]))}ne.schemaProperties=x0;function k0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,pe._)`${e}, ${t}, ${n}${o}`:t,d=[[qt.default.instancePath,(0,pe.strConcat)(qt.default.instancePath,s)],[qt.default.parentData,i.parentData],[qt.default.parentDataProperty,i.parentDataProperty],[qt.default.rootData,qt.default.rootData]];i.opts.dynamicRef&&d.push([qt.default.dynamicAnchors,qt.default.dynamicAnchors]);let p=(0,pe._)`${l}, ${r.object(...d)}`;return c!==pe.nil?(0,pe._)`${a}.call(${c}, ${p})`:(0,pe._)`${a}(${p})`}ne.callValidateCode=k0;var z0=(0,pe._)`new RegExp`;function P0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,pe._)`${o.code==="new RegExp"?z0:(0,v0.useFunc)(e,o)}(${r}, ${n})`})}ne.usePattern=P0;function T0(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:tc.Type.Num},s),t.if((0,pe.not)(s),a)})}}ne.validateArray=T0;function R0(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,tc.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,pe._)`${i} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,pe.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}ne.validateUnion=R0});var _m=R(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateKeywordUsage=gt.validSchemaType=gt.funcKeywordCode=gt.macroKeywordCode=void 0;var Ze=L(),cr=It(),E0=rt(),I0=Dn();function O0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=gm(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:Ze.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}gt.macroKeywordCode=O0;function A0(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;N0(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=gm(n,o,u),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)g(),t.modifying&&hm(e),y(()=>e.error());else{let S=t.async?m():h();t.modifying&&hm(e),y(()=>C0(e,S))}}function m(){let S=n.let("ruleErrs",null);return n.try(()=>g((0,Ze._)`await `),$=>n.assign(d,!1).if((0,Ze._)`${$} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Ze._)`${$}.errors`),()=>n.throw($))),S}function h(){let S=(0,Ze._)`${l}.errors`;return n.assign(S,null),g(Ze.nil),S}function g(S=t.async?(0,Ze._)`await `:Ze.nil){let $=c.opts.passContext?cr.default.this:cr.default.self,w=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Ze._)`${S}${(0,E0.callValidateCode)(e,l,$,w)}`,t.modifying)}function y(S){var $;n.if((0,Ze.not)(($=t.valid)!==null&&$!==void 0?$:d),S)}}gt.funcKeywordCode=A0;function hm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ze._)`${n.parentData}[${n.parentDataProperty}]`))}function C0(e,t){let{gen:r}=e;r.if((0,Ze._)`Array.isArray(${t})`,()=>{r.assign(cr.default.vErrors,(0,Ze._)`${cr.default.vErrors} === null ? ${t} : ${cr.default.vErrors}.concat(${t})`).assign(cr.default.errors,(0,Ze._)`${cr.default.vErrors}.length`),(0,I0.extendErrors)(e)},()=>e.error())}function N0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}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,Ze.stringify)(r)})}function j0(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")}gt.validSchemaType=j0;function M0({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}gt.validateKeywordUsage=M0});var vm=R(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.extendSubschemaMode=Lt.extendSubschemaData=Lt.getSubschema=void 0;var _t=L(),ym=J();function U0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,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 a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,_t._)`${e.schemaPath}${(0,_t.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,_t._)`${e.schemaPath}${(0,_t.getProperty)(t)}${(0,_t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ym.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Lt.getSubschema=U0;function D0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",(0,_t._)`${t.data}${(0,_t.getProperty)(r)}`,!0);c(p),e.errorPath=(0,_t.str)`${u}${(0,ym.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,_t._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let u=o instanceof _t.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}Lt.extendSubschemaData=D0;function Z0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}Lt.extendSubschemaMode=Z0});var oc=R((dC,bm)=>{"use strict";bm.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var $m=R((pC,wm)=>{"use strict";var Ft=wm.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};fs(t,n,o,e,"",e)};Ft.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ft.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ft.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ft.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 fs(e,t,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Ft.arrayKeywords)for(var p=0;p<d.length;p++)fs(e,t,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in Ft.propsKeywords){if(d&&typeof d=="object")for(var m in d)fs(e,t,r,d[m],o+"/"+l+"/"+q0(m),s,o,l,n,m)}else(l in Ft.keywords||e.allKeys&&!(l in Ft.skipKeywords))&&fs(e,t,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function q0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var qn=R(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.getSchemaRefs=Be.resolveUrl=Be.normalizeId=Be._getFullPath=Be.getFullPath=Be.inlineRef=void 0;var L0=J(),F0=oc(),V0=$m(),H0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!sc(e):t?Sm(e)<=t:!1}Be.inlineRef=B0;var K0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function sc(e){for(let t in e){if(K0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(sc)||typeof r=="object"&&sc(r))return!0}return!1}function Sm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!H0.has(r)&&(typeof e[r]=="object"&&(0,L0.eachItem)(e[r],n=>t+=Sm(n)),t===1/0))return 1/0}return t}function xm(e,t="",r){r!==!1&&(t=Vr(t));let n=e.parse(t);return km(e,n)}Be.getFullPath=xm;function km(e,t){return e.serialize(t).split("#")[0]+"#"}Be._getFullPath=km;var J0=/#\/?$/;function Vr(e){return e?e.replace(J0,""):""}Be.normalizeId=Vr;function G0(e,t,r){return r=Vr(r),e.resolve(t,r)}Be.resolveUrl=G0;var W0=/^[a-z_][-a-z0-9._]*$/i;function Y0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Vr(e[r]||t),s={"":o},i=xm(n,o,!1),a={},c=new Set;return V0(e,{allKeys:!0},(d,p,m,h)=>{if(h===void 0)return;let g=i+p,y=s[h];typeof d[r]=="string"&&(y=S.call(this,d[r])),$.call(this,d.$anchor),$.call(this,d.$dynamicAnchor),s[p]=y;function S(w){let T=this.opts.uriResolver.resolve;if(w=Vr(y?T(y,w):w),c.has(w))throw l(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,w):w!==Vr(g)&&(w[0]==="#"?(u(d,a[w],w),a[w]=d):this.refs[w]=g),w}function $(w){if(typeof w=="string"){if(!W0.test(w))throw new Error(`invalid anchor "${w}"`);S.call(this,`#${w}`)}}}),a;function u(d,p,m){if(p!==void 0&&!F0(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Be.getSchemaRefs=Y0});var Vn=R(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getData=Vt.KeywordCxt=Vt.validateFunctionCode=void 0;var Em=sm(),zm=Zn(),ac=Ya(),ms=Zn(),Q0=pm(),Fn=_m(),ic=vm(),O=L(),D=It(),X0=qn(),Ot=J(),Ln=Dn();function e$(e){if(Am(e)&&(Cm(e),Om(e))){n$(e);return}Im(e,()=>(0,Em.topBoolOrEmptySchema)(e))}Vt.validateFunctionCode=e$;function Im({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,O._)`${D.default.data}, ${D.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${Pm(r,o)}`),r$(e,o),e.code(s)}):e.func(t,(0,O._)`${D.default.data}, ${t$(o)}`,n.$async,()=>e.code(Pm(r,o)).code(s))}function t$(e){return(0,O._)`{${D.default.instancePath}="", ${D.default.parentData}, ${D.default.parentDataProperty}, ${D.default.rootData}=${D.default.data}${e.dynamicRef?(0,O._)`, ${D.default.dynamicAnchors}={}`:O.nil}}={}`}function r$(e,t){e.if(D.default.valCxt,()=>{e.var(D.default.instancePath,(0,O._)`${D.default.valCxt}.${D.default.instancePath}`),e.var(D.default.parentData,(0,O._)`${D.default.valCxt}.${D.default.parentData}`),e.var(D.default.parentDataProperty,(0,O._)`${D.default.valCxt}.${D.default.parentDataProperty}`),e.var(D.default.rootData,(0,O._)`${D.default.valCxt}.${D.default.rootData}`),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,O._)`${D.default.valCxt}.${D.default.dynamicAnchors}`)},()=>{e.var(D.default.instancePath,(0,O._)`""`),e.var(D.default.parentData,(0,O._)`undefined`),e.var(D.default.parentDataProperty,(0,O._)`undefined`),e.var(D.default.rootData,D.default.data),t.dynamicRef&&e.var(D.default.dynamicAnchors,(0,O._)`{}`)})}function n$(e){let{schema:t,opts:r,gen:n}=e;Im(e,()=>{r.$comment&&t.$comment&&jm(e),c$(e),n.let(D.default.vErrors,null),n.let(D.default.errors,0),r.unevaluated&&o$(e),Nm(e),d$(e)})}function o$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,O._)`${r}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}function Pm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}function s$(e,t){if(Am(e)&&(Cm(e),Om(e))){i$(e,t);return}(0,Em.boolOrEmptySchema)(e,t)}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}function Am(e){return typeof e.schema!="boolean"}function i$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&jm(e),u$(e),l$(e);let s=n.const("_errs",D.default.errors);Nm(e,s),n.var(t,(0,O._)`${s} === ${D.default.errors}`)}function Cm(e){(0,Ot.checkUnknownRules)(e),a$(e)}function Nm(e,t){if(e.opts.jtd)return Tm(e,[],!1,t);let r=(0,zm.getSchemaTypes)(e.schema),n=(0,zm.coerceAndCheckDataType)(e,r);Tm(e,r,!n,t)}function a$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Ot.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function c$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ot.checkStrictMode)(e,"default is ignored in the schema root")}function u$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,X0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function l$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function jm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,O._)`${D.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,O.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,O._)`${D.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function d$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,O._)`${D.default.errors} === 0`,()=>t.return(D.default.data),()=>t.throw((0,O._)`new ${o}(${D.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,D.default.vErrors),s.unevaluated&&p$(e),t.return((0,O._)`${D.default.errors} === 0`))}function p$({gen:e,evaluated:t,props:r,items:n}){r instanceof O.Name&&e.assign((0,O._)`${t}.props`,r),n instanceof O.Name&&e.assign((0,O._)`${t}.items`,n)}function Tm(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Ot.schemaHasRulesButRef)(s,l))){o.block(()=>Um(e,"$ref",l.all.$ref.definition));return}c.jtd||f$(e,t),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,ac.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ms.checkDataType)(p.type,i,c.strictNumbers)),Rm(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,ms.reportTypeError)(e)),o.endIf()):Rm(e,p),a||o.if((0,O._)`${D.default.errors} === ${n||0}`))}}function Rm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,Q0.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,ac.shouldUseRule)(n,s)&&Um(e,s.keyword,s.definition,t.type)})}function f$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(m$(e,t),e.opts.allowUnionTypes||h$(e,t),g$(e,e.dataTypes))}function m$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Mm(e.dataTypes,r)||cc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),y$(e,t)}}function h$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&cc(e,"use allowUnionTypes to allow union type keyword")}function g$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ac.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>_$(t,i))&&cc(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function _$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Mm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y$(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}function cc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Ot.checkStrictMode)(e,t,e.opts.strictTypes)}var hs=class{constructor(t,r,n){if((0,Fn.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,Ot.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",Dm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Fn.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,O.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,O.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,O._)`${r} !== undefined && (${(0,O.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?Ln.reportExtraError:Ln.reportError)(this,this.def.error,r)}$dataError(){(0,Ln.reportError)(this,this.def.$dataError||Ln.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ln.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=O.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,O.or)((0,O._)`${o} === undefined`,r)),t!==O.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==O.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,O.or)(i(),a());function i(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,O._)`${(0,ms.checkDataTypes)(c,r,s.opts.strictNumbers,ms.DataType.Wrong)}`}return O.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,O._)`!${c}(${r})`}return O.nil}}subschema(t,r){let n=(0,ic.getSubschema)(this.it,t);(0,ic.extendSubschemaData)(n,this.it,t),(0,ic.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return s$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Ot.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Ot.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,O.Name)),!0}};Vt.KeywordCxt=hs;function Um(e,t,r,n){let o=new hs(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Fn.funcKeywordCode)(o,r):"macro"in r?(0,Fn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Fn.funcKeywordCode)(o,r)}var v$=/^\/(?:[^~]|~0|~1)*$/,b$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return D.default.rootData;if(e[0]==="/"){if(!v$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=D.default.rootData}else{let u=b$.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(s=r[t-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,O._)`${s}${(0,O.getProperty)((0,Ot.unescapeJsonPointer)(u))}`,i=(0,O._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Vt.getData=Dm});var gs=R(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var uc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};lc.default=uc});var Hn=R(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var dc=qn(),pc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,dc.resolveUrl)(t,r,n),this.missingSchema=(0,dc.normalizeId)((0,dc.getFullPath)(t,this.missingRef))}};fc.default=pc});var ys=R(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.resolveSchema=nt.getCompilingSchema=nt.resolveRef=nt.compileSchema=nt.SchemaEnv=void 0;var lt=L(),w$=gs(),ur=It(),dt=qn(),Zm=J(),$$=Vn(),Hr=class{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,dt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};nt.SchemaEnv=Hr;function hc(e){let t=qm.call(this,e);if(t)return t;let r=(0,dt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new lt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:w$.default,code:(0,lt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ur.default.data,parentData:ur.default.parentData,parentDataProperty:ur.default.parentDataProperty,dataNames:[ur.default.data],dataPathArr:[lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,lt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:lt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,$$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ur.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let m=new Function(`${ur.default.self}`,`${ur.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof lt.Name?void 0:h,items:g instanceof lt.Name?void 0:g,dynamicProps:h instanceof lt.Name,dynamicItems:g instanceof lt.Name},m.source&&(m.source.evaluated=(0,lt.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(e)}}nt.compileSchema=hc;function S$(e,t,r){var n;r=(0,dt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=z$.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Hr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=x$.call(this,s)}nt.resolveRef=S$;function x$(e){return(0,dt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:hc.call(this,e)}function qm(e){for(let t of this._compilations)if(k$(t,e))return t}nt.getCompilingSchema=qm;function k$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function z$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||_s.call(this,e,t)}function _s(e,t){let r=this.opts.uriResolver.parse(t),n=(0,dt._getFullPath)(this.opts.uriResolver,r),o=(0,dt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return mc.call(this,r,e);let s=(0,dt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=_s.call(this,e,i);return typeof a?.schema!="object"?void 0:mc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||hc.call(this,i),s===(0,dt.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,dt.resolveUrl)(this.opts.uriResolver,o,u)),new Hr({schema:a,schemaId:c,root:e,baseId:o})}return mc.call(this,r,i)}}nt.resolveSchema=_s;var P$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function mc(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Zm.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!P$.has(a)&&u&&(t=(0,dt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Zm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=_s.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Hr({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var Lm=R((yC,T$)=>{T$.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 yc=R((vC,Jm)=>{"use strict";var R$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Vm=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),gc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),E$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function _c(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}var I$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fm(e){return e.length=0,!0}function O$(e,t,r){if(e.length){let n=_c(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function A$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=O$;for(let c=0;c<e.length;c++){let u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Fm}else{o.push(u);continue}}return o.length&&(a===Fm?r.zone=o.join(""):i?n.push(o.join("")):n.push(_c(o))),r.address=n.join(""),r}function Bm(e){if(C$(e,":")<2)return{host:e,isIPV6:!1};let t=A$(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}}}function C$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function N$(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===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("")}var j$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},M$=/[@/?#:]/g,U$=/[@/?#]/g;function Km(e,t){let r=t?U$:M$;return r.lastIndex=0,e.replace(r,n=>j$[n])}function D$(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(gc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Hm(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function Z$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(gc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Hm(s)?t+=s:t+="%"+o,r+=2;continue}}E$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function q$(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(gc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function L$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Vm(r)){let n=Bm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Km(r,!1)}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}Jm.exports={nonSimpleDomain:I$,recomposeAuthority:L$,reescapeHostDelimiters:Km,normalizePercentEncoding:D$,normalizePathEncoding:Z$,escapePreservingEscapes:q$,removeDotSegments:N$,isIPv4:Vm,isUUID:R$,normalizeIPv6:Bm,stringArrayToHexStripped:_c}});var Xm=R((bC,Qm)=>{"use strict";var{isUUID:F$}=yc(),V$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,H$=["http","https","ws","wss","urn","urn:uuid"];function B$(e){return H$.indexOf(e)!==-1}function vc(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Gm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Wm(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}function K$(e){return e.secure=vc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function J$(e){if((e.port===(vc(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}function G$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(V$);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=bc(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function W$(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(),o=`${r}:${t.nid||n}`,s=bc(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function Y$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!F$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Q$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ym={scheme:"http",domainHost:!0,parse:Gm,serialize:Wm},X$={scheme:"https",domainHost:Ym.domainHost,parse:Gm,serialize:Wm},vs={scheme:"ws",domainHost:!0,parse:K$,serialize:J$},eS={scheme:"wss",domainHost:vs.domainHost,parse:vs.parse,serialize:vs.serialize},tS={scheme:"urn",parse:G$,serialize:W$,skipNormalize:!0},rS={scheme:"urn:uuid",parse:Y$,serialize:Q$,skipNormalize:!0},bs={http:Ym,https:X$,ws:vs,wss:eS,urn:tS,"urn:uuid":rS};Object.setPrototypeOf(bs,null);function bc(e){return e&&(bs[e]||bs[e.toLowerCase()])||void 0}Qm.exports={wsIsSecure:vc,SCHEMES:bs,isValidSchemeName:B$,getSchemeHandler:bc}});var sh=R((wC,ws)=>{"use strict";var{normalizeIPv6:nS,removeDotSegments:Bn,recomposeAuthority:oS,normalizePercentEncoding:sS,normalizePathEncoding:iS,escapePreservingEscapes:aS,reescapeHostDelimiters:cS,isIPv4:uS,nonSimpleDomain:lS}=yc(),{SCHEMES:dS,getSchemeHandler:th}=Xm();function pS(e,t){return typeof e=="string"?e=yS(e,t):typeof e=="object"&&(e=Br(lr(e,t),t)),e}function fS(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=rh(Br(e,n),Br(t,n),n,!0);return n.skipEscape=!0,lr(o,n)}function rh(e,t,r,n){let o={};return n||(e=Br(lr(e,r),r),t=Br(lr(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Bn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Bn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Bn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=Bn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function mS(e,t,r){let n=eh(e,r),o=eh(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function lr(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),o=[],s=th(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=sS(r.path):(r.path=aS(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=oS(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Bn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var hS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function _S(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function nh(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},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(gS);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=e.match(hS);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=_S(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(uS(n.host)===!1){let d=nS(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!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 u=th(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&lS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=cS(unescape(n.host),s))),n.path&&(n.path=iS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Br(e,t){return nh(e,t).parsed}function yS(e,t){return oh(e,t).normalized}function oh(e,t){let{parsed:r,malformedAuthorityOrPort:n}=nh(e,t);return{normalized:n?e:lr(r,t),malformedAuthorityOrPort:n}}function eh(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=oh(e,t);return n?void 0:r}if(typeof e=="object")return lr(e,t)}var wc={SCHEMES:dS,normalize:pS,resolve:fS,resolveComponent:rh,equal:mS,serialize:lr,parse:Br};ws.exports=wc;ws.exports.default=wc;ws.exports.fastUri=wc});var ah=R($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var ih=sh();ih.code='require("ajv/dist/runtime/uri").default';$c.default=ih});var hh=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var vS=Vn();Object.defineProperty(Pe,"KeywordCxt",{enumerable:!0,get:function(){return vS.KeywordCxt}});var Kr=L();Object.defineProperty(Pe,"_",{enumerable:!0,get:function(){return Kr._}});Object.defineProperty(Pe,"str",{enumerable:!0,get:function(){return Kr.str}});Object.defineProperty(Pe,"stringify",{enumerable:!0,get:function(){return Kr.stringify}});Object.defineProperty(Pe,"nil",{enumerable:!0,get:function(){return Kr.nil}});Object.defineProperty(Pe,"Name",{enumerable:!0,get:function(){return Kr.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:!0,get:function(){return Kr.CodeGen}});var bS=gs(),ph=Hn(),wS=Wa(),Kn=ys(),$S=L(),Jn=qn(),$s=Zn(),xc=J(),ch=Lm(),SS=ah(),fh=(e,t)=>new RegExp(e,t);fh.code="new RegExp";var xS=["removeAdditional","useDefaults","coerceTypes"],kS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),zS={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."},PS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},uh=200;function TS(e){var t,r,n,o,s,i,a,c,u,l,d,p,m,h,g,y,S,$,w,T,v,k,A,W,ie;let be=e.strict,qe=(t=e.code)===null||t===void 0?void 0:t.optimize,Me=qe===!0||qe===void 0?1:qe||0,xt=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:fh,Qe=(o=e.uriResolver)!==null&&o!==void 0?o:SS.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:be)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:be)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:be)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:be)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:be)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:Me,regExp:xt}:{optimize:Me,regExp:xt},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:uh,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:uh,meta:(S=e.meta)!==null&&S!==void 0?S:!0,messages:($=e.messages)!==null&&$!==void 0?$:!0,inlineRefs:(w=e.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(T=e.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(v=e.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(A=e.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(W=e.unicodeRegExp)!==null&&W!==void 0?W:!0,int32range:(ie=e.int32range)!==null&&ie!==void 0?ie:!0,uriResolver:Qe}}var Gn=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...TS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new $S.ValueScope({scope:{},prefixes:kS,es5:r,lines:n}),this.logger=CS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,wS.getRules)(),lh.call(this,zS,t,"NOT SUPPORTED"),lh.call(this,PS,t,"DEPRECATED","warn"),this._metaOpts=OS.call(this),t.formats&&ES.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&IS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),RS.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=ch;n==="id"&&(o={...ch},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[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 o=n(r);return"$async"in n||(this.errors=n.errors),o}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 o.call(this,t,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof ph.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);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,Jn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!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 o=this.validate(n,t);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let r;for(;typeof(r=dh.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Kn.SchemaEnv({schema:{},schemaId:n});if(r=Kn.resolveSchema.call(this,o,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=dh.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,Jn.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(jS.call(this,n,r),!r)return(0,xc.eachItem)(n,s=>Sc.call(this,s)),this;US.call(this,r);let o={...r,type:(0,$s.getJSONTypes)(r.type),schemaType:(0,$s.getJSONTypes)(r.schemaType)};return(0,xc.eachItem)(n,o.type.length===0?s=>Sc.call(this,s,o):s=>o.type.forEach(i=>Sc.call(this,s,o,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 o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,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(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=mh(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];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 c=this._cache.get(t);if(c!==void 0)return c;n=(0,Jn.normalizeId)(i||n);let u=Jn.getSchemaRefs.call(this,t,n);return c=new Kn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_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):Kn.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{Kn.compileSchema.call(this,t)}finally{this.opts=r}}};Gn.ValidationError=bS.default;Gn.MissingRefError=ph.default;Pe.default=Gn;function lh(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function dh(e){return e=(0,Jn.normalizeId)(e),this.schemas[e]||this.refs[e]}function RS(){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)}function ES(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function IS(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)}}function OS(){let e={...this.opts};for(let t of xS)delete e[t];return e}var AS={log(){},warn(){},error(){}};function CS(e){if(e===!1)return AS;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")}var NS=/^[a-z_$][a-z0-9_$:-]*$/i;function jS(e,t){let{RULES:r}=this;if((0,xc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!NS.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')}function Sc(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,$s.getJSONTypes)(t.type),schemaType:(0,$s.getJSONTypes)(t.schemaType)}};t.before?MS.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function MS(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function US(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=mh(t)),e.validateSchema=this.compile(t,!0))}var DS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mh(e){return{anyOf:[e,DS]}}});var gh=R(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var ZS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};kc.default=ZS});var bh=R(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.callRef=dr.getValidate=void 0;var qS=Hn(),_h=rt(),Ke=L(),Jr=It(),yh=ys(),Ss=J(),LS={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=yh.resolveRef.call(c,u,o,r);if(l===void 0)throw new qS.default(n.opts.uriResolver,o,r);if(l instanceof yh.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return xs(e,i,s,s.$async);let h=t.scopeValue("root",{ref:u});return xs(e,(0,Ke._)`${h}.validate`,u,u.$async)}function p(h){let g=vh(e,h);xs(e,g,h,h.$async)}function m(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Ke.stringify)(h)}:{ref:h}),y=t.name("valid"),S=e.subschema({schema:h,dataTypes:[],schemaPath:Ke.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(S),e.ok(y)}}};function vh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ke._)`${r.scopeValue("wrapper",{ref:t})}.validate`}dr.getValidate=vh;function xs(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Jr.default.this:Ke.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Ke._)`await ${(0,_h.callValidateCode)(e,t,u)}`),m(t),i||o.assign(h,!0)},g=>{o.if((0,Ke._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,_h.callValidateCode)(e,t,u),()=>m(t),()=>p(t))}function p(h){let g=(0,Ke._)`${h}.errors`;o.assign(Jr.default.vErrors,(0,Ke._)`${Jr.default.vErrors} === null ? ${g} : ${Jr.default.vErrors}.concat(${g})`),o.assign(Jr.default.errors,(0,Ke._)`${Jr.default.vErrors}.length`)}function m(h){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Ss.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,Ke._)`${h}.evaluated.props`);s.props=Ss.mergeEvaluated.props(o,S,s.props,Ke.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ss.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,Ke._)`${h}.evaluated.items`);s.items=Ss.mergeEvaluated.items(o,S,s.items,Ke.Name)}}}dr.callRef=xs;dr.default=LS});var wh=R(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var FS=gh(),VS=bh(),HS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",FS.default,VS.default];zc.default=HS});var $h=R(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var ks=L(),Ht=ks.operators,zs={maximum:{okStr:"<=",ok:Ht.LTE,fail:Ht.GT},minimum:{okStr:">=",ok:Ht.GTE,fail:Ht.LT},exclusiveMaximum:{okStr:"<",ok:Ht.LT,fail:Ht.GTE},exclusiveMinimum:{okStr:">",ok:Ht.GT,fail:Ht.LTE}},BS={message:({keyword:e,schemaCode:t})=>(0,ks.str)`must be ${zs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ks._)`{comparison: ${zs[e].okStr}, limit: ${t}}`},KS={keyword:Object.keys(zs),type:"number",schemaType:"number",$data:!0,error:BS,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ks._)`${r} ${zs[t].fail} ${n} || isNaN(${r})`)}};Pc.default=KS});var Sh=R(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Wn=L(),JS={message:({schemaCode:e})=>(0,Wn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Wn._)`{multipleOf: ${e}}`},GS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,Wn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Wn._)`${i} !== parseInt(${i})`;e.fail$data((0,Wn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Tc.default=GS});var kh=R(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});function xh(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Rc.default=xh;xh.code='require("ajv/dist/runtime/ucs2length").default'});var zh=R(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var pr=L(),WS=J(),YS=kh(),QS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,pr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,pr._)`{limit: ${e}}`},XS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?pr.operators.GT:pr.operators.LT,i=o.opts.unicode===!1?(0,pr._)`${r}.length`:(0,pr._)`${(0,WS.useFunc)(e.gen,YS.default)}(${r})`;e.fail$data((0,pr._)`${i} ${s} ${n}`)}};Ec.default=XS});var Ph=R(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var ex=rt(),tx=J(),Gr=L(),rx={message:({schemaCode:e})=>(0,Gr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Gr._)`{pattern: ${e}}`},nx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:rx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Gr._)`new RegExp`:(0,tx.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Gr._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,Gr._)`!${l}`)}else{let c=(0,ex.usePattern)(e,o);e.fail$data((0,Gr._)`!${c}.test(${r})`)}}};Ic.default=nx});var Th=R(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Yn=L(),ox={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Yn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Yn._)`{limit: ${e}}`},sx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ox,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?Yn.operators.GT:Yn.operators.LT;e.fail$data((0,Yn._)`Object.keys(${r}).length ${o} ${n}`)}};Oc.default=sx});var Rh=R(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Qn=rt(),Xn=L(),ix=J(),ax={message:({params:{missingProperty:e}})=>(0,Xn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Xn._)`{missingProperty: ${e}}`},cx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ax,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,ix.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Xn.nil,d);else for(let m of r)(0,Qn.checkReportMissingProp)(e,m)}function l(){let m=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>p(m,h)),e.ok(h)}else t.if((0,Qn.checkMissingProp)(e,r,m)),(0,Qn.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,Qn.noPropertyInData)(t,o,m,a.ownProperties),()=>e.error())})}function p(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,Qn.propertyInData)(t,o,m,a.ownProperties)),t.if((0,Xn.not)(h),()=>{e.error(),t.break()})},Xn.nil)}}};Ac.default=cx});var Eh=R(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var eo=L(),ux={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,eo.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,eo._)`{limit: ${e}}`},lx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ux,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?eo.operators.GT:eo.operators.LT;e.fail$data((0,eo._)`${r}.length ${o} ${n}`)}};Cc.default=lx});var Ps=R(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Ih=oc();Ih.code='require("ajv/dist/runtime/equal").default';Nc.default=Ih});var Oh=R(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var jc=Zn(),Te=L(),dx=J(),px=Ps(),fx={message:({params:{i:e,j:t}})=>(0,Te.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Te._)`{i: ${e}, j: ${t}}`},mx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:fx,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),u=s.items?(0,jc.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,Te._)`${i} === false`),e.ok(c);function l(){let h=t.let("i",(0,Te._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,Te._)`${h} > 1`,()=>(d()?p:m)(h,g))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let y=t.name("item"),S=(0,jc.checkDataTypes)(u,y,a.opts.strictNumbers,jc.DataType.Wrong),$=t.const("indices",(0,Te._)`{}`);t.for((0,Te._)`;${h}--;`,()=>{t.let(y,(0,Te._)`${r}[${h}]`),t.if(S,(0,Te._)`continue`),u.length>1&&t.if((0,Te._)`typeof ${y} == "string"`,(0,Te._)`${y} += "_"`),t.if((0,Te._)`typeof ${$}[${y}] == "number"`,()=>{t.assign(g,(0,Te._)`${$}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,Te._)`${$}[${y}] = ${h}`)})}function m(h,g){let y=(0,dx.useFunc)(t,px.default),S=t.name("outer");t.label(S).for((0,Te._)`;${h}--;`,()=>t.for((0,Te._)`${g} = ${h}; ${g}--;`,()=>t.if((0,Te._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(S)})))}}};Mc.default=mx});var Ah=R(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Uc=L(),hx=J(),gx=Ps(),_x={message:"must be equal to constant",params:({schemaCode:e})=>(0,Uc._)`{allowedValue: ${e}}`},yx={keyword:"const",$data:!0,error:_x,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Uc._)`!${(0,hx.useFunc)(t,gx.default)}(${r}, ${o})`):e.fail((0,Uc._)`${s} !== ${r}`)}};Dc.default=yx});var Ch=R(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var to=L(),vx=J(),bx=Ps(),wx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,to._)`{allowedValues: ${e}}`},$x={keyword:"enum",schemaType:"array",$data:!0,error:wx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,vx.useFunc)(t,bx.default)),l;if(a||n)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=t.const("vSchema",s);l=(0,to.or)(...o.map((h,g)=>p(m,g)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,m=>t.if((0,to._)`${u()}(${r}, ${m})`,()=>t.assign(l,!0).break()))}function p(m,h){let g=o[h];return typeof g=="object"&&g!==null?(0,to._)`${u()}(${r}, ${m}[${h}])`:(0,to._)`${r} === ${g}`}}};Zc.default=$x});var Nh=R(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Sx=$h(),xx=Sh(),kx=zh(),zx=Ph(),Px=Th(),Tx=Rh(),Rx=Eh(),Ex=Oh(),Ix=Ah(),Ox=Ch(),Ax=[Sx.default,xx.default,kx.default,zx.default,Px.default,Tx.default,Rx.default,Ex.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ix.default,Ox.default];qc.default=Ax});var Fc=R(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.validateAdditionalItems=void 0;var fr=L(),Lc=J(),Cx={message:({params:{len:e}})=>(0,fr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,fr._)`{limit: ${e}}`},Nx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Cx,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Lc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}jh(e,n)}};function jh(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,fr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,fr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Lc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,fr._)`${a} <= ${t.length}`);r.if((0,fr.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Lc.Type.Num},u),i.allErrors||r.if((0,fr.not)(u),()=>r.break())})}}ro.validateAdditionalItems=jh;ro.default=Nx});var Vc=R(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.validateTuple=void 0;var Mh=L(),Ts=J(),jx=rt(),Mx={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,Ts.alwaysValidSchema)(r,t)&&e.ok((0,jx.validateArray)(e))}};function Uh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ts.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Mh._)`${s}.length`);r.forEach((d,p)=>{(0,Ts.alwaysValidSchema)(a,d)||(n.if((0,Mh._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Ts.checkStrictMode)(a,y,p.strictTuples)}}}no.validateTuple=Uh;no.default=Mx});var Dh=R(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Ux=Vc(),Dx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ux.validateTuple)(e,"items")};Hc.default=Dx});var qh=R(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Zh=L(),Zx=J(),qx=rt(),Lx=Fc(),Fx={message:({params:{len:e}})=>(0,Zh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zh._)`{limit: ${e}}`},Vx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Fx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,Zx.alwaysValidSchema)(n,t)&&(o?(0,Lx.validateAdditionalItems)(e,o):e.ok((0,qx.validateArray)(e)))}};Bc.default=Vx});var Lh=R(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var ot=L(),Rs=J(),Hx={message:({params:{min:e,max:t}})=>t===void 0?(0,ot.str)`must contain at least ${e} valid item(s)`:(0,ot.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ot._)`{minContains: ${e}}`:(0,ot._)`{minContains: ${e}, maxContains: ${t}}`},Bx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Hx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=t.const("len",(0,ot._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Rs.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Rs.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Rs.alwaysValidSchema)(s,r)){let g=(0,ot._)`${l} >= ${i}`;a!==void 0&&(g=(0,ot._)`${g} && ${l} <= ${a}`),e.pass(g);return}s.items=!0;let d=t.name("valid");a===void 0&&i===1?m(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,!0),a!==void 0&&t.if((0,ot._)`${o}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let g=t.name("_valid"),y=t.let("count",0);m(g,()=>t.if(g,()=>h(y)))}function m(g,y){t.forRange("i",0,l,S=>{e.subschema({keyword:"contains",dataProp:S,dataPropType:Rs.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,ot._)`${g}++`),a===void 0?t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,ot._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,ot._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Kc.default=Bx});var Hh=R(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.validateSchemaDeps=yt.validatePropertyDeps=yt.error=void 0;var Jc=L(),Kx=J(),oo=rt();yt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Jc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Jc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var Jx={keyword:"dependencies",type:"object",schemaType:"object",error:yt.error,code(e){let[t,r]=Gx(e);Fh(e,t),Vh(e,r)}};function Gx({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Fh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,no.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,no.checkReportMissingProp)(e,u)}):(r.if((0,Jc._)`${c} && (${(0,no.checkMissingProp)(e,a,s)})`),(0,no.reportMissingProp)(e,s),r.else())}}yt.validatePropertyDeps=Fh;function Vh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,Kx.alwaysValidSchema)(s,t[a])||(r.if((0,no.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i))}yt.validateSchemaDeps=Vh;yt.default=Jx});var Kh=R(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Bh=L(),Wx=J(),Yx={message:"property name must be valid",params:({params:e})=>(0,Bh._)`{propertyName: ${e.propertyName}}`},Qx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Yx,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Wx.alwaysValidSchema)(o,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,Bh.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Gc.default=Qx});var Yc=R(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Rs=rt(),pt=L(),Xx=Et(),Es=J(),ek={message:"must NOT have additional properties",params:({params:e})=>(0,pt._)`{additionalProperty: ${e.additionalProperty}}`},tk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ek,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Es.alwaysValidSchema)(i,r))return;let u=(0,Rs.allSchemaProperties)(n.properties),l=(0,Rs.allSchemaProperties)(n.patternProperties);d(),e.ok((0,pt._)`${s} === ${Xx.default.errors}`);function d(){t.forIn("key",o,y=>{!u.length&&!l.length?h(y):t.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let $=(0,Es.schemaRefOrVal)(i,n.properties,"properties");S=(0,Rs.isOwnProperty)(t,$,y)}else u.length?S=(0,pt.or)(...u.map($=>(0,pt._)`${y} === ${$}`)):S=pt.nil;return l.length&&(S=(0,pt.or)(S,...l.map($=>(0,pt._)`${(0,Rs.usePattern)(e,$)}.test(${y})`))),(0,pt.not)(S)}function m(y){t.code((0,pt._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Es.alwaysValidSchema)(i,r)){let S=t.name("valid");c.removeAdditional==="failing"?(g(y,S,!1),t.if((0,pt.not)(S),()=>{e.reset(),m(y)})):(g(y,S),a||t.if((0,pt.not)(S),()=>t.break()))}}function g(y,S,$){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Es.Type.Str};$===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,S)}}};Wc.default=tk});var Wh=R(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var rk=Fn(),Jh=rt(),Qc=J(),Gh=Yc(),nk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Gh.default.code(new rk.KeywordCxt(s,Gh.default,"additionalProperties"));let i=(0,Jh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Qc.mergeEvaluated.props(t,(0,Qc.toHash)(i),s.props));let a=i.filter(d=>!(0,Qc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)u(d)?l(d):(t.if((0,Jh.propertyInData)(t,o,d,s.opts.ownProperties)),l(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Xc.default=nk});var eg=R(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Yh=rt(),Is=L(),Qh=J(),Xh=J(),ok={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Yh.allSchemaProperties)(r),c=a.filter(g=>(0,Qh.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof Is.Name)&&(s.props=(0,Xh.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&m(g),s.allErrors?h(g):(t.var(l,!0),h(g),t.if(l))}function m(g){for(let y in u)new RegExp(g).test(y)&&(0,Qh.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,Is._)`${(0,Yh.usePattern)(e,g)}.test(${y})`,()=>{let S=c.includes(g);S||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Xh.Type.Str},l),s.opts.unevaluated&&d!==!0?t.assign((0,Is._)`${d}[${y}]`,!0):!S&&!s.allErrors&&t.if((0,Is.not)(l),()=>t.break())})})}}};eu.default=ok});var tg=R(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var sk=J(),ik={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,sk.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};tu.default=ik});var rg=R(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var ak=rt(),ck={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ak.validateUnion,error:{message:"must match a schema in anyOf"}};ru.default=ck});var ng=R(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Os=L(),uk=J(),lk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Os._)`{passingSchemas: ${e.passing}}`},dk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lk,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;(0,uk.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Os._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Os._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),p&&e.mergeEvaluated(p,Os.Name)})})}}};nu.default=dk});var og=R(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var pk=J(),fk={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 o=t.name("valid");r.forEach((s,i)=>{if((0,pk.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};ou.default=fk});var ag=R(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var As=L(),ig=J(),mk={message:({params:e})=>(0,As.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,As._)`{failingKeyword: ${e.ifClause}}`},hk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,ig.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=sg(n,"then"),s=sg(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,As.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),d?t.assign(d,(0,As._)`${l}`):e.setParams({ifClause:l})}}}};function sg(e,t){let r=e.schema[t];return r!==void 0&&!(0,ig.alwaysValidSchema)(e,r)}su.default=hk});var cg=R(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var gk=J(),_k={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,gk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};iu.default=_k});var ug=R(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var yk=Fc(),vk=Dh(),bk=Vc(),wk=qh(),$k=Lh(),Sk=Hh(),xk=Kh(),kk=Yc(),zk=Wh(),Tk=eg(),Pk=tg(),Rk=rg(),Ek=ng(),Ik=og(),Ok=ag(),Ak=cg();function Ck(e=!1){let t=[Pk.default,Rk.default,Ek.default,Ik.default,Ok.default,Ak.default,xk.default,kk.default,Sk.default,zk.default,Tk.default];return e?t.push(vk.default,wk.default):t.push(yk.default,bk.default),t.push($k.default),t}au.default=Ck});var lg=R(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var ye=L(),Nk={message:({schemaCode:e})=>(0,ye.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ye._)`{format: ${e}}`},jk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Nk,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ye._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,ye._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ye._)`${g}.type || "string"`).assign(S,(0,ye._)`${g}.validate`),()=>r.assign(y,(0,ye._)`"string"`).assign(S,g)),e.fail$data((0,ye.or)($(),w()));function $(){return c.strictSchema===!1?ye.nil:(0,ye._)`${i} && !${S}`}function w(){let P=l.$async?(0,ye._)`(${g}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,ye._)`${S}(${n})`,v=(0,ye._)`(typeof ${S} == "function" ? ${P} : ${S}.test(${n}))`;return(0,ye._)`${S} && ${S} !== true && ${y} === ${t} && !${v}`}}function m(){let h=d.formats[s];if(!h){$();return}if(h===!0)return;let[g,y,S]=w(h);g===t&&e.pass(P());function $(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(v){let k=v instanceof RegExp?(0,ye.regexpCode)(v):c.code.formats?(0,ye._)`${c.code.formats}${(0,ye.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:v,code:k});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,ye._)`${A}.validate`]:["string",v,A]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ye._)`await ${S}(${n})`}return typeof y=="function"?(0,ye._)`${S}(${n})`:(0,ye._)`${S}.test(${n})`}}}};cu.default=jk});var dg=R(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var Mk=lg(),Uk=[Mk.default];uu.default=Uk});var pg=R(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.contentVocabulary=Gr.metadataVocabulary=void 0;Gr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Gr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var mg=R(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var Dk=wh(),Zk=Nh(),qk=ug(),Lk=dg(),fg=pg(),Fk=[Dk.default,Zk.default,(0,qk.default)(),Lk.default,fg.metadataVocabulary,fg.contentVocabulary];lu.default=Fk});var gg=R(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.DiscrError=void 0;var hg;(function(e){e.Tag="tag",e.Mapping="mapping"})(hg||(Cs.DiscrError=hg={}))});var yg=R(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var Wr=L(),du=gg(),_g=_s(),Vk=Vn(),Hk=J(),Bk={message:({params:{discrError:e,tagName:t}})=>e===du.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Wr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Kk={keyword:"discriminator",type:"object",schemaType:"object",error:Bk,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="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 c=t.let("valid",!1),u=t.const("tag",(0,Wr._)`${r}${(0,Wr.getProperty)(a)}`);t.if((0,Wr._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:du.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let m=p();t.if(!1);for(let h in m)t.elseIf((0,Wr._)`${u} === ${h}`),t.assign(c,d(m[h]));t.else(),e.error(!1,{discrError:du.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(m){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(g,Wr.Name),h}function p(){var m;let h={},g=S(o),y=!0;for(let P=0;P<i.length;P++){let v=i[P];if(v?.$ref&&!(0,Hk.schemaHasRulesButRef)(v,s.self.RULES)){let A=v.$ref;if(v=_g.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),v instanceof _g.SchemaEnv&&(v=v.schema),v===void 0)throw new Vk.default(s.opts.uriResolver,s.baseId,A)}let k=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||S(v)),$(k,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:P}){return Array.isArray(P)&&P.includes(a)}function $(P,v){if(P.const)w(P.const,v);else if(P.enum)for(let k of P.enum)w(k,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(P,v){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=v}}}};pu.default=Kk});var vg=R((c1,Jk)=>{Jk.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 mu=R((fe,fu)=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.MissingRefError=fe.ValidationError=fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=fe.Ajv=void 0;var Gk=hh(),Wk=mg(),Yk=yg(),bg=vg(),Qk=["/properties"],Ns="http://json-schema.org/draft-07/schema",Yr=class extends Gk.default{_addVocabularies(){super._addVocabularies(),Wk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Yk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(bg,Qk):bg;this.addMetaSchema(t,Ns,!1),this.refs["http://json-schema.org/schema"]=Ns}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ns)?Ns:void 0)}};fe.Ajv=Yr;fu.exports=fe=Yr;fu.exports.Ajv=Yr;Object.defineProperty(fe,"__esModule",{value:!0});fe.default=Yr;var Xk=Fn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return Xk.KeywordCxt}});var Qr=L();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return Qr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return Qr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return Qr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return Qr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return Qr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return Qr.CodeGen}});var ez=hs();Object.defineProperty(fe,"ValidationError",{enumerable:!0,get:function(){return ez.default}});var tz=Vn();Object.defineProperty(fe,"MissingRefError",{enumerable:!0,get:function(){return tz.default}})});var Pg=R(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.formatNames=bt.fastFormats=bt.fullFormats=void 0;function vt(e,t){return{validate:e,compare:t}}bt.fullFormats={date:vt(xg,yu),time:vt(gu(!0),vu),"date-time":vt(wg(!0),zg),"iso-time":vt(gu(),kg),"iso-date-time":vt(wg(),Tg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:az,"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:mz,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:cz,int32:{type:"number",validate:dz},int64:{type:"number",validate:pz},float:{type:"number",validate:Sg},double:{type:"number",validate:Sg},password:!0,binary:!0};bt.fastFormats={...bt.fullFormats,date:vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yu),time:vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,vu),"date-time":vt(/^\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,zg),"iso-time":vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,kg),"iso-date-time":vt(/^\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,Tg),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};bt.formatNames=Object.keys(bt.fullFormats);function rz(e){return e%4===0&&(e%100!==0||e%400===0)}var nz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function xg(e){let t=nz.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&rz(r)?29:oz[n])}function yu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var hu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gu(e){return function(r){let n=hu.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function vu(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}function kg(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}var _u=/t|\s/i;function wg(e){let t=gu(e);return function(n){let o=n.split(_u);return o.length===2&&xg(o[0])&&t(o[1])}}function zg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Tg(e,t){if(!(e&&t))return;let[r,n]=e.split(_u),[o,s]=t.split(_u),i=yu(r,o);if(i!==void 0)return i||vu(n,s)}var sz=/\/|:/,iz=/^(?:[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 az(e){return sz.test(e)&&iz.test(e)}var $g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function cz(e){return $g.lastIndex=0,$g.test(e)}var uz=-(2**31),lz=2**31-1;function dz(e){return Number.isInteger(e)&&e<=lz&&e>=uz}function pz(e){return Number.isInteger(e)}function Sg(){return!0}var fz=/[^\\]\\Z/;function mz(e){if(fz.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Rg=R(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.formatLimitDefinition=void 0;var hz=mu(),ft=L(),Ht=ft.operators,js={formatMaximum:{okStr:"<=",ok:Ht.LTE,fail:Ht.GT},formatMinimum:{okStr:">=",ok:Ht.GTE,fail:Ht.LT},formatExclusiveMaximum:{okStr:"<",ok:Ht.LT,fail:Ht.GTE},formatExclusiveMinimum:{okStr:">",ok:Ht.GT,fail:Ht.LTE}},gz={message:({keyword:e,schemaCode:t})=>(0,ft.str)`should be ${js[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ft._)`{comparison: ${js[e].okStr}, limit: ${t}}`};Xr.formatLimitDefinition={keyword:Object.keys(js),type:"string",schemaType:"string",$data:!0,error:gz,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new hz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=t.const("fmt",(0,ft._)`${p}[${c.schemaCode}]`);e.fail$data((0,ft.or)((0,ft._)`typeof ${m} != "object"`,(0,ft._)`${m} instanceof RegExp`,(0,ft._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=t.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,ft._)`${i.code.formats}${(0,ft.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,ft._)`${p}.compare(${r}, ${n}) ${js[o].fail} 0`}},dependencies:["format"]};var _z=e=>(e.addKeyword(Xr.formatLimitDefinition),e);Xr.default=_z});var Ag=R((oo,Og)=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var en=Pg(),yz=Rg(),bu=L(),Eg=new bu.Name("fullFormats"),vz=new bu.Name("fastFormats"),wu=(e,t={keywords:!0})=>{if(Array.isArray(t))return Ig(e,t,en.fullFormats,Eg),e;let[r,n]=t.mode==="fast"?[en.fastFormats,vz]:[en.fullFormats,Eg],o=t.formats||en.formatNames;return Ig(e,o,r,n),t.keywords&&(0,yz.default)(e),e};wu.get=(e,t="full")=>{let n=(t==="fast"?en.fastFormats:en.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Ig(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,bu._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}Og.exports=oo=wu;Object.defineProperty(oo,"__esModule",{value:!0});oo.default=wu});import{spawn as D_,spawnSync as on}from"node:child_process";import{connect as GT}from"node:net";import{homedir as Z_,userInfo as Fu}from"node:os";import{resolve as q_,join as Ct,dirname as Ju}from"node:path";import{fileURLToPath as WT,pathToFileURL as YT}from"node:url";import{createInterface as Qs}from"node:readline/promises";import*as H from"node:fs";var ci=Object.freeze({status:"aborted"});function _(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var py=Symbol("zod_brand"),kt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},To={};function Je(e){return e&&Object.assign(To,e),To}var X={};ai(X,{BIGINT_FORMAT_RANGES:()=>sl,Class:()=>li,NUMBER_FORMAT_RANGES:()=>yi,aborted:()=>Yt,allowsEval:()=>hi,assert:()=>_y,assertEqual:()=>fy,assertIs:()=>hy,assertNever:()=>gy,assertNotEqual:()=>my,assignProp:()=>mi,cached:()=>pn,captureStackTrace:()=>Ro,cleanEnum:()=>Ey,cleanRegex:()=>mn,clone:()=>st,createTransparentProxy:()=>Sy,defineLazy:()=>ae,esc:()=>Wt,escapeRegex:()=>Nt,extend:()=>zy,finalizeIssue:()=>it,floatSafeRemainder:()=>fi,getElementAtPath:()=>yy,getEnumValues:()=>di,getLengthableOrigin:()=>hn,getParsedType:()=>$y,getSizableOrigin:()=>il,isObject:()=>xr,isPlainObject:()=>kr,issue:()=>vi,joinValues:()=>Po,jsonStringifyReplacer:()=>pi,merge:()=>Ty,normalizeParams:()=>C,nullish:()=>fn,numKeys:()=>wy,omit:()=>ky,optionalKeys:()=>_i,partial:()=>Py,pick:()=>xy,prefixIssues:()=>ht,primitiveTypes:()=>ol,promiseAllObject:()=>vy,propertyKeyTypes:()=>gi,randomString:()=>by,required:()=>Ry,stringifyPrimitive:()=>Eo,unwrapMessage:()=>dn});function fy(e){return e}function my(e){return e}function hy(e){}function gy(e){throw new Error}function _y(e){}function di(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Po(e,t="|"){return e.map(r=>Eo(r)).join(t)}function pi(e,t){return typeof t=="bigint"?t.toString():t}function pn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function fn(e){return e==null}function mn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function fi(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function ae(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function mi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yy(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function vy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function by(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Wt(e){return JSON.stringify(e)}var Ro=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var hi=pn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function kr(e){if(xr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(xr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wy(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var $y=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},gi=new Set(["string","number","symbol"]),ol=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function C(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Sy(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Eo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function _i(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var yi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xy(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return st(e,{...e._zod.def,shape:r,checks:[]})}function ky(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return st(e,{...e._zod.def,shape:r,checks:[]})}function zy(e,t){if(!kr(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return mi(this,"shape",n),n},checks:[]};return st(e,r)}function Ty(e,t){return st(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return mi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Py(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return st(t,{...t._zod.def,shape:o,checks:[]})}function Ry(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return st(t,{...t._zod.def,shape:o,checks:[]})}function Yt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ht(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function dn(e){return typeof e=="string"?e:e?.message}function it(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=dn(e.inst?._zod.def?.error?.(e))??dn(t?.error?.(e))??dn(r.customError?.(e))??dn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function il(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function hn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function vi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Ey(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var li=class{constructor(...t){}};var al=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,pi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Io=_("$ZodError",al),bi=_("$ZodError",al,{Parent:Error});function wi(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function $i(e,t){let r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(e),n}var cl=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kt;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Je())));throw Ro(a,o?.callee),a}return i.value};var ul=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Je())));throw Ro(a,o?.callee),a}return i.value};var Si=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new kt;return s.issues.length?{success:!1,error:new(e??Io)(s.issues.map(i=>it(i,o,Je())))}:{success:!0,data:s.value}},gn=Si(bi),xi=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>it(i,o,Je())))}:{success:!0,data:s.value}},Oo=xi(bi);var ll=/^[cC][^\s-]{8,}$/,dl=/^[0-9a-z]+$/,pl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fl=/^[0-9a-vA-V]{20}$/,ml=/^[A-Za-z0-9]{27}$/,hl=/^[a-zA-Z0-9_-]{21}$/,gl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _l=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ki=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var yl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Oy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vl(){return new RegExp(Oy,"u")}var bl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$l=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Sl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zi=/^[A-Za-z0-9_-]*$/,kl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var zl=/^\+(?:[0-9]){6,14}[0-9]$/,Tl="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Pl=new RegExp(`^${Tl}$`);function Rl(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function El(e){return new RegExp(`^${Rl(e)}$`)}function Il(e){let t=Rl({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Tl}T(?:${n})$`)}var Ol=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Al=/^\d+n?$/,Cl=/^\d+$/,Nl=/^-?\d+(?:\.\d+)?/i,jl=/true|false/i,Ml=/null/i;var Ul=/^[^A-Z]*$/,Dl=/^[^a-z]*$/;var Ie=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Zl={number:"number",bigint:"bigint",object:"date"},Ti=_("$ZodCheckLessThan",(e,t)=>{Ie.init(e,t);let r=Zl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Pi=_("$ZodCheckGreaterThan",(e,t)=>{Ie.init(e,t);let r=Zl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ql=_("$ZodCheckMultipleOf",(e,t)=>{Ie.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):fi(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ll=_("$ZodCheckNumberFormat",(e,t)=>{Ie.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=yi[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Cl)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var Fl=_("$ZodCheckMaxLength",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=hn(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vl=_("$ZodCheckMinLength",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=hn(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Hl=_("$ZodCheckLengthEquals",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=hn(o),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),_n=_("$ZodCheckStringFormat",(e,t)=>{var r,n;Ie.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Bl=_("$ZodCheckRegex",(e,t)=>{_n.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Kl=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ul),_n.init(e,t)}),Jl=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Dl),_n.init(e,t)}),Gl=_("$ZodCheckIncludes",(e,t)=>{Ie.init(e,t);let r=Nt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Wl=_("$ZodCheckStartsWith",(e,t)=>{Ie.init(e,t);let r=new RegExp(`^${Nt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Yl=_("$ZodCheckEndsWith",(e,t)=>{Ie.init(e,t);let r=new RegExp(`.*${Nt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Ql=_("$ZodCheckOverwrite",(e,t)=>{Ie.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Co=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
10
+ deps: ${r}}`};var Jx={keyword:"dependencies",type:"object",schemaType:"object",error:yt.error,code(e){let[t,r]=Gx(e);Fh(e,t),Vh(e,r)}};function Gx({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Fh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,oo.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,oo.checkReportMissingProp)(e,u)}):(r.if((0,Jc._)`${c} && (${(0,oo.checkMissingProp)(e,a,s)})`),(0,oo.reportMissingProp)(e,s),r.else())}}yt.validatePropertyDeps=Fh;function Vh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,Kx.alwaysValidSchema)(s,t[a])||(r.if((0,oo.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i))}yt.validateSchemaDeps=Vh;yt.default=Jx});var Kh=R(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Bh=L(),Wx=J(),Yx={message:"property name must be valid",params:({params:e})=>(0,Bh._)`{propertyName: ${e.propertyName}}`},Qx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Yx,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Wx.alwaysValidSchema)(o,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,Bh.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Gc.default=Qx});var Yc=R(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Es=rt(),pt=L(),Xx=It(),Is=J(),ek={message:"must NOT have additional properties",params:({params:e})=>(0,pt._)`{additionalProperty: ${e.additionalProperty}}`},tk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ek,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Is.alwaysValidSchema)(i,r))return;let u=(0,Es.allSchemaProperties)(n.properties),l=(0,Es.allSchemaProperties)(n.patternProperties);d(),e.ok((0,pt._)`${s} === ${Xx.default.errors}`);function d(){t.forIn("key",o,y=>{!u.length&&!l.length?h(y):t.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let $=(0,Is.schemaRefOrVal)(i,n.properties,"properties");S=(0,Es.isOwnProperty)(t,$,y)}else u.length?S=(0,pt.or)(...u.map($=>(0,pt._)`${y} === ${$}`)):S=pt.nil;return l.length&&(S=(0,pt.or)(S,...l.map($=>(0,pt._)`${(0,Es.usePattern)(e,$)}.test(${y})`))),(0,pt.not)(S)}function m(y){t.code((0,pt._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Is.alwaysValidSchema)(i,r)){let S=t.name("valid");c.removeAdditional==="failing"?(g(y,S,!1),t.if((0,pt.not)(S),()=>{e.reset(),m(y)})):(g(y,S),a||t.if((0,pt.not)(S),()=>t.break()))}}function g(y,S,$){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Is.Type.Str};$===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,S)}}};Wc.default=tk});var Wh=R(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var rk=Vn(),Jh=rt(),Qc=J(),Gh=Yc(),nk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Gh.default.code(new rk.KeywordCxt(s,Gh.default,"additionalProperties"));let i=(0,Jh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Qc.mergeEvaluated.props(t,(0,Qc.toHash)(i),s.props));let a=i.filter(d=>!(0,Qc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)u(d)?l(d):(t.if((0,Jh.propertyInData)(t,o,d,s.opts.ownProperties)),l(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Xc.default=nk});var eg=R(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Yh=rt(),Os=L(),Qh=J(),Xh=J(),ok={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Yh.allSchemaProperties)(r),c=a.filter(g=>(0,Qh.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof Os.Name)&&(s.props=(0,Xh.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&m(g),s.allErrors?h(g):(t.var(l,!0),h(g),t.if(l))}function m(g){for(let y in u)new RegExp(g).test(y)&&(0,Qh.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,Os._)`${(0,Yh.usePattern)(e,g)}.test(${y})`,()=>{let S=c.includes(g);S||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Xh.Type.Str},l),s.opts.unevaluated&&d!==!0?t.assign((0,Os._)`${d}[${y}]`,!0):!S&&!s.allErrors&&t.if((0,Os.not)(l),()=>t.break())})})}}};eu.default=ok});var tg=R(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var sk=J(),ik={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,sk.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};tu.default=ik});var rg=R(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var ak=rt(),ck={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ak.validateUnion,error:{message:"must match a schema in anyOf"}};ru.default=ck});var ng=R(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var As=L(),uk=J(),lk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,As._)`{passingSchemas: ${e.passing}}`},dk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lk,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;(0,uk.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,As._)`${c} && ${i}`).assign(i,!1).assign(a,(0,As._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),p&&e.mergeEvaluated(p,As.Name)})})}}};nu.default=dk});var og=R(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var pk=J(),fk={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 o=t.name("valid");r.forEach((s,i)=>{if((0,pk.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};ou.default=fk});var ag=R(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Cs=L(),ig=J(),mk={message:({params:e})=>(0,Cs.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Cs._)`{failingKeyword: ${e.ifClause}}`},hk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,ig.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=sg(n,"then"),s=sg(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,Cs.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),d?t.assign(d,(0,Cs._)`${l}`):e.setParams({ifClause:l})}}}};function sg(e,t){let r=e.schema[t];return r!==void 0&&!(0,ig.alwaysValidSchema)(e,r)}su.default=hk});var cg=R(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var gk=J(),_k={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,gk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};iu.default=_k});var ug=R(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var yk=Fc(),vk=Dh(),bk=Vc(),wk=qh(),$k=Lh(),Sk=Hh(),xk=Kh(),kk=Yc(),zk=Wh(),Pk=eg(),Tk=tg(),Rk=rg(),Ek=ng(),Ik=og(),Ok=ag(),Ak=cg();function Ck(e=!1){let t=[Tk.default,Rk.default,Ek.default,Ik.default,Ok.default,Ak.default,xk.default,kk.default,Sk.default,zk.default,Pk.default];return e?t.push(vk.default,wk.default):t.push(yk.default,bk.default),t.push($k.default),t}au.default=Ck});var lg=R(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var ye=L(),Nk={message:({schemaCode:e})=>(0,ye.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ye._)`{format: ${e}}`},jk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Nk,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ye._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,ye._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ye._)`${g}.type || "string"`).assign(S,(0,ye._)`${g}.validate`),()=>r.assign(y,(0,ye._)`"string"`).assign(S,g)),e.fail$data((0,ye.or)($(),w()));function $(){return c.strictSchema===!1?ye.nil:(0,ye._)`${i} && !${S}`}function w(){let T=l.$async?(0,ye._)`(${g}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,ye._)`${S}(${n})`,v=(0,ye._)`(typeof ${S} == "function" ? ${T} : ${S}.test(${n}))`;return(0,ye._)`${S} && ${S} !== true && ${y} === ${t} && !${v}`}}function m(){let h=d.formats[s];if(!h){$();return}if(h===!0)return;let[g,y,S]=w(h);g===t&&e.pass(T());function $(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(v){let k=v instanceof RegExp?(0,ye.regexpCode)(v):c.code.formats?(0,ye._)`${c.code.formats}${(0,ye.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:v,code:k});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,ye._)`${A}.validate`]:["string",v,A]}function T(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ye._)`await ${S}(${n})`}return typeof y=="function"?(0,ye._)`${S}(${n})`:(0,ye._)`${S}.test(${n})`}}}};cu.default=jk});var dg=R(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var Mk=lg(),Uk=[Mk.default];uu.default=Uk});var pg=R(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.contentVocabulary=Wr.metadataVocabulary=void 0;Wr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var mg=R(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var Dk=wh(),Zk=Nh(),qk=ug(),Lk=dg(),fg=pg(),Fk=[Dk.default,Zk.default,(0,qk.default)(),Lk.default,fg.metadataVocabulary,fg.contentVocabulary];lu.default=Fk});var gg=R(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.DiscrError=void 0;var hg;(function(e){e.Tag="tag",e.Mapping="mapping"})(hg||(Ns.DiscrError=hg={}))});var yg=R(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var Yr=L(),du=gg(),_g=ys(),Vk=Hn(),Hk=J(),Bk={message:({params:{discrError:e,tagName:t}})=>e===du.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Yr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Kk={keyword:"discriminator",type:"object",schemaType:"object",error:Bk,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="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 c=t.let("valid",!1),u=t.const("tag",(0,Yr._)`${r}${(0,Yr.getProperty)(a)}`);t.if((0,Yr._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:du.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let m=p();t.if(!1);for(let h in m)t.elseIf((0,Yr._)`${u} === ${h}`),t.assign(c,d(m[h]));t.else(),e.error(!1,{discrError:du.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(m){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(g,Yr.Name),h}function p(){var m;let h={},g=S(o),y=!0;for(let T=0;T<i.length;T++){let v=i[T];if(v?.$ref&&!(0,Hk.schemaHasRulesButRef)(v,s.self.RULES)){let A=v.$ref;if(v=_g.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),v instanceof _g.SchemaEnv&&(v=v.schema),v===void 0)throw new Vk.default(s.opts.uriResolver,s.baseId,A)}let k=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||S(v)),$(k,T)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:T}){return Array.isArray(T)&&T.includes(a)}function $(T,v){if(T.const)w(T.const,v);else if(T.enum)for(let k of T.enum)w(k,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(T,v){if(typeof T!="string"||T in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[T]=v}}}};pu.default=Kk});var vg=R((u1,Jk)=>{Jk.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 mu=R((fe,fu)=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.MissingRefError=fe.ValidationError=fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=fe.Ajv=void 0;var Gk=hh(),Wk=mg(),Yk=yg(),bg=vg(),Qk=["/properties"],js="http://json-schema.org/draft-07/schema",Qr=class extends Gk.default{_addVocabularies(){super._addVocabularies(),Wk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Yk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(bg,Qk):bg;this.addMetaSchema(t,js,!1),this.refs["http://json-schema.org/schema"]=js}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(js)?js:void 0)}};fe.Ajv=Qr;fu.exports=fe=Qr;fu.exports.Ajv=Qr;Object.defineProperty(fe,"__esModule",{value:!0});fe.default=Qr;var Xk=Vn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return Xk.KeywordCxt}});var Xr=L();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return Xr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return Xr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return Xr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return Xr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return Xr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return Xr.CodeGen}});var ez=gs();Object.defineProperty(fe,"ValidationError",{enumerable:!0,get:function(){return ez.default}});var tz=Hn();Object.defineProperty(fe,"MissingRefError",{enumerable:!0,get:function(){return tz.default}})});var Tg=R(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.formatNames=bt.fastFormats=bt.fullFormats=void 0;function vt(e,t){return{validate:e,compare:t}}bt.fullFormats={date:vt(xg,yu),time:vt(gu(!0),vu),"date-time":vt(wg(!0),zg),"iso-time":vt(gu(),kg),"iso-date-time":vt(wg(),Pg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:az,"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:mz,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:cz,int32:{type:"number",validate:dz},int64:{type:"number",validate:pz},float:{type:"number",validate:Sg},double:{type:"number",validate:Sg},password:!0,binary:!0};bt.fastFormats={...bt.fullFormats,date:vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yu),time:vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,vu),"date-time":vt(/^\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,zg),"iso-time":vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,kg),"iso-date-time":vt(/^\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,Pg),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};bt.formatNames=Object.keys(bt.fullFormats);function rz(e){return e%4===0&&(e%100!==0||e%400===0)}var nz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function xg(e){let t=nz.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&rz(r)?29:oz[n])}function yu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var hu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gu(e){return function(r){let n=hu.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function vu(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}function kg(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}var _u=/t|\s/i;function wg(e){let t=gu(e);return function(n){let o=n.split(_u);return o.length===2&&xg(o[0])&&t(o[1])}}function zg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Pg(e,t){if(!(e&&t))return;let[r,n]=e.split(_u),[o,s]=t.split(_u),i=yu(r,o);if(i!==void 0)return i||vu(n,s)}var sz=/\/|:/,iz=/^(?:[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 az(e){return sz.test(e)&&iz.test(e)}var $g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function cz(e){return $g.lastIndex=0,$g.test(e)}var uz=-(2**31),lz=2**31-1;function dz(e){return Number.isInteger(e)&&e<=lz&&e>=uz}function pz(e){return Number.isInteger(e)}function Sg(){return!0}var fz=/[^\\]\\Z/;function mz(e){if(fz.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Rg=R(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.formatLimitDefinition=void 0;var hz=mu(),ft=L(),Bt=ft.operators,Ms={formatMaximum:{okStr:"<=",ok:Bt.LTE,fail:Bt.GT},formatMinimum:{okStr:">=",ok:Bt.GTE,fail:Bt.LT},formatExclusiveMaximum:{okStr:"<",ok:Bt.LT,fail:Bt.GTE},formatExclusiveMinimum:{okStr:">",ok:Bt.GT,fail:Bt.LTE}},gz={message:({keyword:e,schemaCode:t})=>(0,ft.str)`should be ${Ms[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ft._)`{comparison: ${Ms[e].okStr}, limit: ${t}}`};en.formatLimitDefinition={keyword:Object.keys(Ms),type:"string",schemaType:"string",$data:!0,error:gz,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new hz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=t.const("fmt",(0,ft._)`${p}[${c.schemaCode}]`);e.fail$data((0,ft.or)((0,ft._)`typeof ${m} != "object"`,(0,ft._)`${m} instanceof RegExp`,(0,ft._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=t.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,ft._)`${i.code.formats}${(0,ft.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,ft._)`${p}.compare(${r}, ${n}) ${Ms[o].fail} 0`}},dependencies:["format"]};var _z=e=>(e.addKeyword(en.formatLimitDefinition),e);en.default=_z});var Ag=R((so,Og)=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});var tn=Tg(),yz=Rg(),bu=L(),Eg=new bu.Name("fullFormats"),vz=new bu.Name("fastFormats"),wu=(e,t={keywords:!0})=>{if(Array.isArray(t))return Ig(e,t,tn.fullFormats,Eg),e;let[r,n]=t.mode==="fast"?[tn.fastFormats,vz]:[tn.fullFormats,Eg],o=t.formats||tn.formatNames;return Ig(e,o,r,n),t.keywords&&(0,yz.default)(e),e};wu.get=(e,t="full")=>{let n=(t==="fast"?tn.fastFormats:tn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Ig(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,bu._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}Og.exports=so=wu;Object.defineProperty(so,"__esModule",{value:!0});so.default=wu});import{spawn as D_,spawnSync as on}from"node:child_process";import{connect as GP}from"node:net";import{homedir as Z_,userInfo as Fu}from"node:os";import{resolve as q_,join as $t,dirname as Ju}from"node:path";import{fileURLToPath as WP,pathToFileURL as YP}from"node:url";import{createInterface as Qs}from"node:readline/promises";import*as V from"node:fs";var ci=Object.freeze({status:"aborted"});function _(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var py=Symbol("zod_brand"),zt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},To={};function Je(e){return e&&Object.assign(To,e),To}var X={};ai(X,{BIGINT_FORMAT_RANGES:()=>sl,Class:()=>li,NUMBER_FORMAT_RANGES:()=>yi,aborted:()=>Qt,allowsEval:()=>hi,assert:()=>_y,assertEqual:()=>fy,assertIs:()=>hy,assertNever:()=>gy,assertNotEqual:()=>my,assignProp:()=>mi,cached:()=>fn,captureStackTrace:()=>Eo,cleanEnum:()=>Ey,cleanRegex:()=>hn,clone:()=>st,createTransparentProxy:()=>Sy,defineLazy:()=>ae,esc:()=>Yt,escapeRegex:()=>jt,extend:()=>zy,finalizeIssue:()=>it,floatSafeRemainder:()=>fi,getElementAtPath:()=>yy,getEnumValues:()=>di,getLengthableOrigin:()=>gn,getParsedType:()=>$y,getSizableOrigin:()=>il,isObject:()=>kr,isPlainObject:()=>zr,issue:()=>vi,joinValues:()=>Ro,jsonStringifyReplacer:()=>pi,merge:()=>Py,normalizeParams:()=>C,nullish:()=>mn,numKeys:()=>wy,omit:()=>ky,optionalKeys:()=>_i,partial:()=>Ty,pick:()=>xy,prefixIssues:()=>ht,primitiveTypes:()=>ol,promiseAllObject:()=>vy,propertyKeyTypes:()=>gi,randomString:()=>by,required:()=>Ry,stringifyPrimitive:()=>Io,unwrapMessage:()=>pn});function fy(e){return e}function my(e){return e}function hy(e){}function gy(e){throw new Error}function _y(e){}function di(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Ro(e,t="|"){return e.map(r=>Io(r)).join(t)}function pi(e,t){return typeof t=="bigint"?t.toString():t}function fn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function mn(e){return e==null}function hn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function fi(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function ae(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function mi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yy(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function vy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function by(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Yt(e){return JSON.stringify(e)}var Eo=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var hi=fn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function zr(e){if(kr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(kr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wy(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var $y=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},gi=new Set(["string","number","symbol"]),ol=new Set(["string","number","bigint","boolean","symbol","undefined"]);function jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function C(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Sy(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Io(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function _i(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var yi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xy(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return st(e,{...e._zod.def,shape:r,checks:[]})}function ky(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return st(e,{...e._zod.def,shape:r,checks:[]})}function zy(e,t){if(!zr(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return mi(this,"shape",n),n},checks:[]};return st(e,r)}function Py(e,t){return st(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return mi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Ty(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return st(t,{...t._zod.def,shape:o,checks:[]})}function Ry(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return st(t,{...t._zod.def,shape:o,checks:[]})}function Qt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ht(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function pn(e){return typeof e=="string"?e:e?.message}function it(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=pn(e.inst?._zod.def?.error?.(e))??pn(t?.error?.(e))??pn(r.customError?.(e))??pn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function il(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function gn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function vi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Ey(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var li=class{constructor(...t){}};var al=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,pi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Oo=_("$ZodError",al),bi=_("$ZodError",al,{Parent:Error});function wi(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function $i(e,t){let r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(e),n}var cl=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new zt;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Je())));throw Eo(a,o?.callee),a}return i.value};var ul=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>it(c,s,Je())));throw Eo(a,o?.callee),a}return i.value};var Si=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new zt;return s.issues.length?{success:!1,error:new(e??Oo)(s.issues.map(i=>it(i,o,Je())))}:{success:!0,data:s.value}},_n=Si(bi),xi=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>it(i,o,Je())))}:{success:!0,data:s.value}},Ao=xi(bi);var ll=/^[cC][^\s-]{8,}$/,dl=/^[0-9a-z]+$/,pl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fl=/^[0-9a-vA-V]{20}$/,ml=/^[A-Za-z0-9]{27}$/,hl=/^[a-zA-Z0-9_-]{21}$/,gl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _l=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ki=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var yl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Oy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vl(){return new RegExp(Oy,"u")}var bl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$l=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Sl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zi=/^[A-Za-z0-9_-]*$/,kl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var zl=/^\+(?:[0-9]){6,14}[0-9]$/,Pl="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Tl=new RegExp(`^${Pl}$`);function Rl(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function El(e){return new RegExp(`^${Rl(e)}$`)}function Il(e){let t=Rl({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Pl}T(?:${n})$`)}var Ol=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Al=/^\d+n?$/,Cl=/^\d+$/,Nl=/^-?\d+(?:\.\d+)?/i,jl=/true|false/i,Ml=/null/i;var Ul=/^[^A-Z]*$/,Dl=/^[^a-z]*$/;var Ie=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Zl={number:"number",bigint:"bigint",object:"date"},Pi=_("$ZodCheckLessThan",(e,t)=>{Ie.init(e,t);let r=Zl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ti=_("$ZodCheckGreaterThan",(e,t)=>{Ie.init(e,t);let r=Zl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ql=_("$ZodCheckMultipleOf",(e,t)=>{Ie.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):fi(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ll=_("$ZodCheckNumberFormat",(e,t)=>{Ie.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=yi[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Cl)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var Fl=_("$ZodCheckMaxLength",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!mn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=gn(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vl=_("$ZodCheckMinLength",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!mn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=gn(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Hl=_("$ZodCheckLengthEquals",(e,t)=>{var r;Ie.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!mn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=gn(o),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),yn=_("$ZodCheckStringFormat",(e,t)=>{var r,n;Ie.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Bl=_("$ZodCheckRegex",(e,t)=>{yn.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Kl=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ul),yn.init(e,t)}),Jl=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Dl),yn.init(e,t)}),Gl=_("$ZodCheckIncludes",(e,t)=>{Ie.init(e,t);let r=jt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Wl=_("$ZodCheckStartsWith",(e,t)=>{Ie.init(e,t);let r=new RegExp(`^${jt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Yl=_("$ZodCheckEndsWith",(e,t)=>{Ie.init(e,t);let r=new RegExp(`.*${jt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Ql=_("$ZodCheckOverwrite",(e,t)=>{Ie.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var No=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
11
11
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
12
- `))}};var ed={major:4,minor:0,patch:0};var te=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ed;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,i,a)=>{let c=Yt(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new kt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Yt(s,d)))});else{if(s.issues.length===d)continue;c||(c=Yt(s,d))}}return u?u.then(()=>s):s};e._zod.run=(s,i)=>{let a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new kt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=gn(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Oo(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),jo=_("$ZodString",(e,t)=>{te.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ol(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),le=_("$ZodStringFormat",(e,t)=>{_n.init(e,t),jo.init(e,t)}),ld=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_l),le.init(e,t)}),dd=_("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ki(n))}else t.pattern??(t.pattern=ki());le.init(e,t)}),pd=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yl),le.init(e,t)}),fd=_("$ZodURL",(e,t)=>{le.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kl.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),md=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=vl()),le.init(e,t)}),hd=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=hl),le.init(e,t)}),gd=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ll),le.init(e,t)}),_d=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=dl),le.init(e,t)}),yd=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=pl),le.init(e,t)}),vd=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fl),le.init(e,t)}),bd=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ml),le.init(e,t)}),wd=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Il(t)),le.init(e,t)}),$d=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Pl),le.init(e,t)}),Sd=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=El(t)),le.init(e,t)}),xd=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=gl),le.init(e,t)}),kd=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=bl),le.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),zd=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wl),le.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Td=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$l),le.init(e,t)}),Pd=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Sl),le.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Rd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ed=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xl),le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Rd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Ay(e){if(!zi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Rd(r)}var Id=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=zi),le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Ay(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Od=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zl),le.init(e,t)});function Cy(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Ad=_("$ZodJWT",(e,t)=>{le.init(e,t),e._zod.check=r=>{Cy(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ei=_("$ZodNumber",(e,t)=>{te.init(e,t),e._zod.pattern=e._zod.bag.pattern??Nl,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Cd=_("$ZodNumber",(e,t)=>{Ll.init(e,t),Ei.init(e,t)}),Nd=_("$ZodBoolean",(e,t)=>{te.init(e,t),e._zod.pattern=jl,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),jd=_("$ZodBigInt",(e,t)=>{te.init(e,t),e._zod.pattern=Al,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var Md=_("$ZodNull",(e,t)=>{te.init(e,t),e._zod.pattern=Ml,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),Ud=_("$ZodAny",(e,t)=>{te.init(e,t),e._zod.parse=r=>r}),Dd=_("$ZodUnknown",(e,t)=>{te.init(e,t),e._zod.parse=r=>r}),Zd=_("$ZodNever",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var qd=_("$ZodDate",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),r}});function td(e,t,r){e.issues.length&&t.issues.push(...ht(r,e.issues)),t.value[r]=e.value}var Ld=_("$ZodArray",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>td(u,r,i))):td(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function No(e,t,r){e.issues.length&&t.issues.push(...ht(r,e.issues)),t.value[r]=e.value}function rd(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...ht(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Fd=_("$ZodObject",(e,t)=>{te.init(e,t);let r=pn(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof te))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=_i(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});ae(e._zod,"propValues",()=>{let d=t.shape,p={};for(let m in d){let h=d[m]._zod;if(h.values){p[m]??(p[m]=new Set);for(let g of h.values)p[m].add(g)}}return p});let n=d=>{let p=new Co(["shape","payload","ctx"]),m=r.value,h=$=>{let w=Wt($);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let $ of m.keys)g[$]=`key_${y++}`;p.write("const newResult = {}");for(let $ of m.keys)if(m.optionalKeys.has($)){let w=g[$];p.write(`const ${w} = ${h($)};`);let P=Wt($);p.write(`
12
+ `))}};var ed={major:4,minor:0,patch:0};var te=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ed;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,i,a)=>{let c=Qt(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new zt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Qt(s,d)))});else{if(s.issues.length===d)continue;c||(c=Qt(s,d))}}return u?u.then(()=>s):s};e._zod.run=(s,i)=>{let a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new zt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=_n(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ao(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Mo=_("$ZodString",(e,t)=>{te.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ol(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),le=_("$ZodStringFormat",(e,t)=>{yn.init(e,t),Mo.init(e,t)}),ld=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_l),le.init(e,t)}),dd=_("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ki(n))}else t.pattern??(t.pattern=ki());le.init(e,t)}),pd=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yl),le.init(e,t)}),fd=_("$ZodURL",(e,t)=>{le.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kl.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),md=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=vl()),le.init(e,t)}),hd=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=hl),le.init(e,t)}),gd=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ll),le.init(e,t)}),_d=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=dl),le.init(e,t)}),yd=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=pl),le.init(e,t)}),vd=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fl),le.init(e,t)}),bd=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ml),le.init(e,t)}),wd=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Il(t)),le.init(e,t)}),$d=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Tl),le.init(e,t)}),Sd=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=El(t)),le.init(e,t)}),xd=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=gl),le.init(e,t)}),kd=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=bl),le.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),zd=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wl),le.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Pd=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$l),le.init(e,t)}),Td=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Sl),le.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Rd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ed=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xl),le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Rd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Ay(e){if(!zi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Rd(r)}var Id=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=zi),le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Ay(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Od=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zl),le.init(e,t)});function Cy(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Ad=_("$ZodJWT",(e,t)=>{le.init(e,t),e._zod.check=r=>{Cy(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ei=_("$ZodNumber",(e,t)=>{te.init(e,t),e._zod.pattern=e._zod.bag.pattern??Nl,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Cd=_("$ZodNumber",(e,t)=>{Ll.init(e,t),Ei.init(e,t)}),Nd=_("$ZodBoolean",(e,t)=>{te.init(e,t),e._zod.pattern=jl,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),jd=_("$ZodBigInt",(e,t)=>{te.init(e,t),e._zod.pattern=Al,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var Md=_("$ZodNull",(e,t)=>{te.init(e,t),e._zod.pattern=Ml,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),Ud=_("$ZodAny",(e,t)=>{te.init(e,t),e._zod.parse=r=>r}),Dd=_("$ZodUnknown",(e,t)=>{te.init(e,t),e._zod.parse=r=>r}),Zd=_("$ZodNever",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var qd=_("$ZodDate",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),r}});function td(e,t,r){e.issues.length&&t.issues.push(...ht(r,e.issues)),t.value[r]=e.value}var Ld=_("$ZodArray",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>td(u,r,i))):td(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function jo(e,t,r){e.issues.length&&t.issues.push(...ht(r,e.issues)),t.value[r]=e.value}function rd(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...ht(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Fd=_("$ZodObject",(e,t)=>{te.init(e,t);let r=fn(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof te))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=_i(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});ae(e._zod,"propValues",()=>{let d=t.shape,p={};for(let m in d){let h=d[m]._zod;if(h.values){p[m]??(p[m]=new Set);for(let g of h.values)p[m].add(g)}}return p});let n=d=>{let p=new No(["shape","payload","ctx"]),m=r.value,h=$=>{let w=Yt($);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let $ of m.keys)g[$]=`key_${y++}`;p.write("const newResult = {}");for(let $ of m.keys)if(m.optionalKeys.has($)){let w=g[$];p.write(`const ${w} = ${h($)};`);let T=Yt($);p.write(`
13
13
  if (${w}.issues.length) {
14
- if (input[${P}] === undefined) {
15
- if (${P} in input) {
16
- newResult[${P}] = undefined;
14
+ if (input[${T}] === undefined) {
15
+ if (${T} in input) {
16
+ newResult[${T}] = undefined;
17
17
  }
18
18
  } else {
19
19
  payload.issues = payload.issues.concat(
20
20
  ${w}.issues.map((iss) => ({
21
21
  ...iss,
22
- path: iss.path ? [${P}, ...iss.path] : [${P}],
22
+ path: iss.path ? [${T}, ...iss.path] : [${T}],
23
23
  }))
24
24
  );
25
25
  }
26
26
  } else if (${w}.value === undefined) {
27
- if (${P} in input) newResult[${P}] = undefined;
27
+ if (${T} in input) newResult[${T}] = undefined;
28
28
  } else {
29
- newResult[${P}] = ${w}.value;
29
+ newResult[${T}] = ${w}.value;
30
30
  }
31
31
  `)}else{let w=g[$];p.write(`const ${w} = ${h($)};`),p.write(`
32
32
  if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
33
33
  ...iss,
34
- path: iss.path ? [${Wt($)}, ...iss.path] : [${Wt($)}]
35
- })));`),p.write(`newResult[${Wt($)}] = ${w}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return($,w)=>S(d,$,w)},o,s=xr,i=!To.jitless,c=i&&hi.value,u=t.catchall,l;e._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;let h=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let w=l.shape;for(let P of l.keys){let v=w[P],k=v._zod.run({value:m[P],issues:[]},p),A=v._zod.optin==="optional"&&v._zod.optout==="optional";k instanceof Promise?h.push(k.then(W=>A?rd(W,d,P,m):No(W,d,P))):A?rd(k,d,P,m):No(k,d,P)}}if(!u)return h.length?Promise.all(h).then(()=>d):d;let g=[],y=l.keySet,S=u._zod,$=S.def.type;for(let w of Object.keys(m)){if(y.has(w))continue;if($==="never"){g.push(w);continue}let P=S.run({value:m[w],issues:[]},p);P instanceof Promise?h.push(P.then(v=>No(v,d,w))):No(P,d,w)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function nd(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>it(s,n,Je())))}),t}var Ii=_("$ZodUnion",(e,t)=>{te.init(e,t),ae(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ae(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ae(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ae(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>mn(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of t.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>nd(i,r,e,n)):nd(s,r,e,n)}}),Vd=_("$ZodDiscriminatedUnion",(e,t)=>{Ii.init(e,t);let r=e._zod.parse;ae(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=pn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!xr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),Hd=_("$ZodIntersection",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>od(r,c,u)):od(r,s,i)}});function Ri(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(kr(e)&&kr(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=Ri(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=Ri(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function od(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Yt(e))return e;let n=Ri(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Bd=_("$ZodRecord",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!kr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[];if(t.keyType._zod.values){let i=t.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ht(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ht(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=t.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>it(u,n,Je())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ht(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ht(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Kd=_("$ZodEnum",(e,t)=>{te.init(e,t);let r=di(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>gi.has(typeof n)).map(n=>typeof n=="string"?Nt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Jd=_("$ZodLiteral",(e,t)=>{te.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Nt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Gd=_("$ZodTransform",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new kt;return r.value=o,r}}),Wd=_("$ZodOptional",(e,t)=>{te.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ae(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${mn(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Yd=_("$ZodNullable",(e,t)=>{te.init(e,t),ae(e._zod,"optin",()=>t.innerType._zod.optin),ae(e._zod,"optout",()=>t.innerType._zod.optout),ae(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${mn(r.source)}|null)$`):void 0}),ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Qd=_("$ZodDefault",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sd(s,t)):sd(o,t)}});function sd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Xd=_("$ZodPrefault",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),ep=_("$ZodNonOptional",(e,t)=>{te.init(e,t),ae(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>id(s,e)):id(o,e)}});function id(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var tp=_("$ZodCatch",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"optout",()=>t.innerType._zod.optout),ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>it(i,n,Je()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>it(s,n,Je()))},input:r.value}),r.issues=[]),r)}});var rp=_("$ZodPipe",(e,t)=>{te.init(e,t),ae(e._zod,"values",()=>t.in._zod.values),ae(e._zod,"optin",()=>t.in._zod.optin),ae(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ad(s,t,n)):ad(o,t,n)}});function ad(e,t,r){return Yt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var np=_("$ZodReadonly",(e,t)=>{te.init(e,t),ae(e._zod,"propValues",()=>t.innerType._zod.propValues),ae(e._zod,"values",()=>t.innerType._zod.values),ae(e._zod,"optin",()=>t.innerType._zod.optin),ae(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(cd):cd(o)}});function cd(e){return e.value=Object.freeze(e.value),e}var op=_("$ZodCustom",(e,t)=>{Ie.init(e,t),te.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>ud(s,r,n,e));ud(o,r,n,e)}});function ud(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(vi(o))}}var Ny=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},jy=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Ny(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Eo(n.values[0])}`:`Invalid option: expected one of ${Po(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Po(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function sp(){return{localeError:jy()}}var My=Symbol("ZodOutput"),Uy=Symbol("ZodInput"),Oi=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function ip(){return new Oi}var zr=ip();function ap(e,t){return new e({type:"string",...C(t)})}function cp(e,t){return new e({type:"string",coerce:!0,...C(t)})}function up(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})}function Ai(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})}function lp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})}function dp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})}function pp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})}function fp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})}function Ci(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})}function mp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})}function hp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})}function gp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})}function _p(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})}function yp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})}function vp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})}function bp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})}function wp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})}function $p(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})}function Sp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})}function xp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})}function kp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})}function zp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})}function Tp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})}function Pp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})}function Rp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})}function Ep(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})}function Ip(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})}function Op(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})}function Ap(e,t){return new e({type:"number",checks:[],...C(t)})}function Cp(e,t){return new e({type:"number",coerce:!0,checks:[],...C(t)})}function Np(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})}function jp(e,t){return new e({type:"boolean",...C(t)})}function Mp(e,t){return new e({type:"boolean",coerce:!0,...C(t)})}function Up(e,t){return new e({type:"bigint",coerce:!0,...C(t)})}function Dp(e,t){return new e({type:"null",...C(t)})}function Zp(e){return new e({type:"any"})}function qp(e){return new e({type:"unknown"})}function Lp(e,t){return new e({type:"never",...C(t)})}function Fp(e,t){return new e({type:"date",coerce:!0,...C(t)})}function Tr(e,t){return new Ti({check:"less_than",...C(t),value:e,inclusive:!1})}function zt(e,t){return new Ti({check:"less_than",...C(t),value:e,inclusive:!0})}function Pr(e,t){return new Pi({check:"greater_than",...C(t),value:e,inclusive:!1})}function at(e,t){return new Pi({check:"greater_than",...C(t),value:e,inclusive:!0})}function yn(e,t){return new ql({check:"multiple_of",...C(t),value:e})}function Mo(e,t){return new Fl({check:"max_length",...C(t),maximum:e})}function Rr(e,t){return new Vl({check:"min_length",...C(t),minimum:e})}function Uo(e,t){return new Hl({check:"length_equals",...C(t),length:e})}function Ni(e,t){return new Bl({check:"string_format",format:"regex",...C(t),pattern:e})}function ji(e){return new Kl({check:"string_format",format:"lowercase",...C(e)})}function Mi(e){return new Jl({check:"string_format",format:"uppercase",...C(e)})}function Ui(e,t){return new Gl({check:"string_format",format:"includes",...C(t),includes:e})}function Di(e,t){return new Wl({check:"string_format",format:"starts_with",...C(t),prefix:e})}function Zi(e,t){return new Yl({check:"string_format",format:"ends_with",...C(t),suffix:e})}function Qt(e){return new Ql({check:"overwrite",tx:e})}function qi(e){return Qt(t=>t.normalize(e))}function Li(){return Qt(e=>e.trim())}function Fi(){return Qt(e=>e.toLowerCase())}function Vi(){return Qt(e=>e.toUpperCase())}function Vp(e,t,r){return new e({type:"array",element:t,...C(r)})}function Hp(e,t,r){let n=C(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Bp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})}function Ir(e){return!!e._zod}function ct(e,t){return Ir(e)?gn(e,t):e.safeParse(t)}function Do(e){if(!e)return;let t;if(Ir(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Kp(e){if(Ir(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}var vn={};ai(vn,{ZodISODate:()=>Gp,ZodISODateTime:()=>Jp,ZodISODuration:()=>Yp,ZodISOTime:()=>Wp,date:()=>Bi,datetime:()=>Hi,duration:()=>Ji,time:()=>Ki});var Jp=_("ZodISODateTime",(e,t)=>{wd.init(e,t),me.init(e,t)});function Hi(e){return Rp(Jp,e)}var Gp=_("ZodISODate",(e,t)=>{$d.init(e,t),me.init(e,t)});function Bi(e){return Ep(Gp,e)}var Wp=_("ZodISOTime",(e,t)=>{Sd.init(e,t),me.init(e,t)});function Ki(e){return Ip(Wp,e)}var Yp=_("ZodISODuration",(e,t)=>{xd.init(e,t),me.init(e,t)});function Ji(e){return Op(Yp,e)}var Xp=(e,t)=>{Io.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>$i(e,r)},flatten:{value:r=>wi(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},gR=_("ZodError",Xp),bn=_("ZodError",Xp,{Parent:Error});var ef=cl(bn),tf=ul(bn),rf=Si(bn),nf=xi(bn);var ce=_("ZodType",(e,t)=>(te.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>st(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>ef(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>rf(e,r,n),e.parseAsync=async(r,n)=>tf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>nf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Ov(r,n)),e.superRefine=r=>e.check(Av(r)),e.overwrite=r=>e.check(Qt(r)),e.optional=()=>ge(e),e.nullable=()=>af(e),e.nullish=()=>ge(af(e)),e.nonoptional=r=>kv(e,r),e.array=()=>z(e),e.or=r=>de([e,r]),e.and=r=>Lo(e,r),e.transform=r=>Wi(e,_f(r)),e.default=r=>$v(e,r),e.prefault=r=>xv(e,r),e.catch=r=>Tv(e,r),e.pipe=r=>Wi(e,r),e.readonly=()=>Ev(e),e.describe=r=>{let n=e.clone();return zr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return zr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return zr.get(e);let n=e.clone();return zr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),cf=_("_ZodString",(e,t)=>{jo.init(e,t),ce.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Ni(...n)),e.includes=(...n)=>e.check(Ui(...n)),e.startsWith=(...n)=>e.check(Di(...n)),e.endsWith=(...n)=>e.check(Zi(...n)),e.min=(...n)=>e.check(Rr(...n)),e.max=(...n)=>e.check(Mo(...n)),e.length=(...n)=>e.check(Uo(...n)),e.nonempty=(...n)=>e.check(Rr(1,...n)),e.lowercase=n=>e.check(ji(n)),e.uppercase=n=>e.check(Mi(n)),e.trim=()=>e.check(Li()),e.normalize=(...n)=>e.check(qi(...n)),e.toLowerCase=()=>e.check(Fi()),e.toUpperCase=()=>e.check(Vi())}),Yi=_("ZodString",(e,t)=>{jo.init(e,t),cf.init(e,t),e.email=r=>e.check(up(By,r)),e.url=r=>e.check(Ci(uf,r)),e.jwt=r=>e.check(Pp(av,r)),e.emoji=r=>e.check(mp(Ky,r)),e.guid=r=>e.check(Ai(of,r)),e.uuid=r=>e.check(lp(Zo,r)),e.uuidv4=r=>e.check(dp(Zo,r)),e.uuidv6=r=>e.check(pp(Zo,r)),e.uuidv7=r=>e.check(fp(Zo,r)),e.nanoid=r=>e.check(hp(Jy,r)),e.guid=r=>e.check(Ai(of,r)),e.cuid=r=>e.check(gp(Gy,r)),e.cuid2=r=>e.check(_p(Wy,r)),e.ulid=r=>e.check(yp(Yy,r)),e.base64=r=>e.check(kp(ov,r)),e.base64url=r=>e.check(zp(sv,r)),e.xid=r=>e.check(vp(Qy,r)),e.ksuid=r=>e.check(bp(Xy,r)),e.ipv4=r=>e.check(wp(ev,r)),e.ipv6=r=>e.check($p(tv,r)),e.cidrv4=r=>e.check(Sp(rv,r)),e.cidrv6=r=>e.check(xp(nv,r)),e.e164=r=>e.check(Tp(iv,r)),e.datetime=r=>e.check(Hi(r)),e.date=r=>e.check(Bi(r)),e.time=r=>e.check(Ki(r)),e.duration=r=>e.check(Ji(r))});function f(e){return ap(Yi,e)}var me=_("ZodStringFormat",(e,t)=>{le.init(e,t),cf.init(e,t)}),By=_("ZodEmail",(e,t)=>{pd.init(e,t),me.init(e,t)});var of=_("ZodGUID",(e,t)=>{ld.init(e,t),me.init(e,t)});var Zo=_("ZodUUID",(e,t)=>{dd.init(e,t),me.init(e,t)});var uf=_("ZodURL",(e,t)=>{fd.init(e,t),me.init(e,t)});function lf(e){return Ci(uf,e)}var Ky=_("ZodEmoji",(e,t)=>{md.init(e,t),me.init(e,t)});var Jy=_("ZodNanoID",(e,t)=>{hd.init(e,t),me.init(e,t)});var Gy=_("ZodCUID",(e,t)=>{gd.init(e,t),me.init(e,t)});var Wy=_("ZodCUID2",(e,t)=>{_d.init(e,t),me.init(e,t)});var Yy=_("ZodULID",(e,t)=>{yd.init(e,t),me.init(e,t)});var Qy=_("ZodXID",(e,t)=>{vd.init(e,t),me.init(e,t)});var Xy=_("ZodKSUID",(e,t)=>{bd.init(e,t),me.init(e,t)});var ev=_("ZodIPv4",(e,t)=>{kd.init(e,t),me.init(e,t)});var tv=_("ZodIPv6",(e,t)=>{zd.init(e,t),me.init(e,t)});var rv=_("ZodCIDRv4",(e,t)=>{Td.init(e,t),me.init(e,t)});var nv=_("ZodCIDRv6",(e,t)=>{Pd.init(e,t),me.init(e,t)});var ov=_("ZodBase64",(e,t)=>{Ed.init(e,t),me.init(e,t)});var sv=_("ZodBase64URL",(e,t)=>{Id.init(e,t),me.init(e,t)});var iv=_("ZodE164",(e,t)=>{Od.init(e,t),me.init(e,t)});var av=_("ZodJWT",(e,t)=>{Ad.init(e,t),me.init(e,t)});var qo=_("ZodNumber",(e,t)=>{Ei.init(e,t),ce.init(e,t),e.gt=(n,o)=>e.check(Pr(n,o)),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.lt=(n,o)=>e.check(Tr(n,o)),e.lte=(n,o)=>e.check(zt(n,o)),e.max=(n,o)=>e.check(zt(n,o)),e.int=n=>e.check(sf(n)),e.safe=n=>e.check(sf(n)),e.positive=n=>e.check(Pr(0,n)),e.nonnegative=n=>e.check(at(0,n)),e.negative=n=>e.check(Tr(0,n)),e.nonpositive=n=>e.check(zt(0,n)),e.multipleOf=(n,o)=>e.check(yn(n,o)),e.step=(n,o)=>e.check(yn(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Y(e){return Ap(qo,e)}var cv=_("ZodNumberFormat",(e,t)=>{Cd.init(e,t),qo.init(e,t)});function sf(e){return Np(cv,e)}var Qi=_("ZodBoolean",(e,t)=>{Nd.init(e,t),ce.init(e,t)});function ne(e){return jp(Qi,e)}var df=_("ZodBigInt",(e,t)=>{jd.init(e,t),ce.init(e,t),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.gt=(n,o)=>e.check(Pr(n,o)),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.lt=(n,o)=>e.check(Tr(n,o)),e.lte=(n,o)=>e.check(zt(n,o)),e.max=(n,o)=>e.check(zt(n,o)),e.positive=n=>e.check(Pr(BigInt(0),n)),e.negative=n=>e.check(Tr(BigInt(0),n)),e.nonpositive=n=>e.check(zt(BigInt(0),n)),e.nonnegative=n=>e.check(at(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(yn(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var uv=_("ZodNull",(e,t)=>{Md.init(e,t),ce.init(e,t)});function pf(e){return Dp(uv,e)}var lv=_("ZodAny",(e,t)=>{Ud.init(e,t),ce.init(e,t)});function ff(){return Zp(lv)}var dv=_("ZodUnknown",(e,t)=>{Dd.init(e,t),ce.init(e,t)});function he(){return qp(dv)}var pv=_("ZodNever",(e,t)=>{Zd.init(e,t),ce.init(e,t)});function fv(e){return Lp(pv,e)}var mf=_("ZodDate",(e,t)=>{qd.init(e,t),ce.init(e,t),e.min=(n,o)=>e.check(at(n,o)),e.max=(n,o)=>e.check(zt(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var mv=_("ZodArray",(e,t)=>{Ld.init(e,t),ce.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Rr(r,n)),e.nonempty=r=>e.check(Rr(1,r)),e.max=(r,n)=>e.check(Mo(r,n)),e.length=(r,n)=>e.check(Uo(r,n)),e.unwrap=()=>e.element});function z(e,t){return Vp(mv,e,t)}var hf=_("ZodObject",(e,t)=>{Fd.init(e,t),ce.init(e,t),X.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Fe(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:he()}),e.loose=()=>e.clone({...e._zod.def,catchall:he()}),e.strict=()=>e.clone({...e._zod.def,catchall:fv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>X.extend(e,r),e.merge=r=>X.merge(e,r),e.pick=r=>X.pick(e,r),e.omit=r=>X.omit(e,r),e.partial=(...r)=>X.partial(yf,e,r[0]),e.required=(...r)=>X.required(vf,e,r[0])});function T(e,t){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...e}),this.shape},...X.normalizeParams(t)};return new hf(r)}function $e(e,t){return new hf({type:"object",get shape(){return X.assignProp(this,"shape",{...e}),this.shape},catchall:he(),...X.normalizeParams(t)})}var gf=_("ZodUnion",(e,t)=>{Ii.init(e,t),ce.init(e,t),e.options=t.options});function de(e,t){return new gf({type:"union",options:e,...X.normalizeParams(t)})}var hv=_("ZodDiscriminatedUnion",(e,t)=>{gf.init(e,t),Vd.init(e,t)});function Xi(e,t,r){return new hv({type:"union",options:t,discriminator:e,...X.normalizeParams(r)})}var gv=_("ZodIntersection",(e,t)=>{Hd.init(e,t),ce.init(e,t)});function Lo(e,t){return new gv({type:"intersection",left:e,right:t})}var _v=_("ZodRecord",(e,t)=>{Bd.init(e,t),ce.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ue(e,t,r){return new _v({type:"record",keyType:e,valueType:t,...X.normalizeParams(r)})}var Gi=_("ZodEnum",(e,t)=>{Kd.init(e,t),ce.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...t,checks:[],...X.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...t,checks:[],...X.normalizeParams(o),entries:s})}});function Fe(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Gi({type:"enum",entries:r,...X.normalizeParams(t)})}var yv=_("ZodLiteral",(e,t)=>{Jd.init(e,t),ce.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function E(e,t){return new yv({type:"literal",values:Array.isArray(e)?e:[e],...X.normalizeParams(t)})}var vv=_("ZodTransform",(e,t)=>{Gd.init(e,t),ce.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(X.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(X.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function _f(e){return new vv({type:"transform",transform:e})}var yf=_("ZodOptional",(e,t)=>{Wd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ge(e){return new yf({type:"optional",innerType:e})}var bv=_("ZodNullable",(e,t)=>{Yd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function af(e){return new bv({type:"nullable",innerType:e})}var wv=_("ZodDefault",(e,t)=>{Qd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $v(e,t){return new wv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Sv=_("ZodPrefault",(e,t)=>{Xd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function xv(e,t){return new Sv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var vf=_("ZodNonOptional",(e,t)=>{ep.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function kv(e,t){return new vf({type:"nonoptional",innerType:e,...X.normalizeParams(t)})}var zv=_("ZodCatch",(e,t)=>{tp.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Tv(e,t){return new zv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Pv=_("ZodPipe",(e,t)=>{rp.init(e,t),ce.init(e,t),e.in=t.in,e.out=t.out});function Wi(e,t){return new Pv({type:"pipe",in:e,out:t})}var Rv=_("ZodReadonly",(e,t)=>{np.init(e,t),ce.init(e,t)});function Ev(e){return new Rv({type:"readonly",innerType:e})}var bf=_("ZodCustom",(e,t)=>{op.init(e,t),ce.init(e,t)});function Iv(e){let t=new Ie({check:"custom"});return t._zod.check=e,t}function wf(e,t){return Hp(bf,e??(()=>!0),t)}function Ov(e,t={}){return Bp(bf,e,t)}function Av(e){let t=Iv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(X.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(X.issue(o))}},e(r.value,r)));return t}function ea(e,t){return Wi(_f(e),t)}var $f={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Fo={};ai(Fo,{bigint:()=>Mv,boolean:()=>jv,date:()=>Uv,number:()=>Nv,string:()=>Cv});function Cv(e){return cp(Yi,e)}function Nv(e){return Cp(qo,e)}function jv(e){return Mp(Qi,e)}function Mv(e){return Up(df,e)}function Uv(e){return Fp(mf,e)}Je(sp());var Ar="2025-11-25";var Sf=[Ar,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],jt="io.modelcontextprotocol/related-task",Ho="2.0",Se=wf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),xf=de([f(),Y().int()]),kf=f(),lE=$e({ttl:Y().optional(),pollInterval:Y().optional()}),Zv=T({ttl:Y().optional()}),qv=T({taskId:f()}),ra=$e({progressToken:xf.optional(),[jt]:qv.optional()}),Ge=T({_meta:ra.optional()}),wn=Ge.extend({task:Zv.optional()}),zf=e=>wn.safeParse(e).success,xe=T({method:f(),params:Ge.loose().optional()}),Xe=T({_meta:ra.optional()}),et=T({method:f(),params:Xe.loose().optional()}),ke=$e({_meta:ra.optional()}),Bo=de([f(),Y().int()]),Tf=T({jsonrpc:E(Ho),id:Bo,...xe.shape}).strict(),$n=e=>Tf.safeParse(e).success,Pf=T({jsonrpc:E(Ho),...et.shape}).strict(),Rf=e=>Pf.safeParse(e).success,na=T({jsonrpc:E(Ho),id:Bo,result:ke}).strict(),Xt=e=>na.safeParse(e).success;var U;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var oa=T({jsonrpc:E(Ho),id:Bo.optional(),error:T({code:Y().int(),message:f(),data:he().optional()})}).strict();var Ef=e=>oa.safeParse(e).success;var Cr=de([Tf,Pf,na,oa]),dE=de([na,oa]),er=ke.strict(),Lv=Xe.extend({requestId:Bo.optional(),reason:f().optional()}),Ko=et.extend({method:E("notifications/cancelled"),params:Lv}),Fv=T({src:f(),mimeType:f().optional(),sizes:z(f()).optional(),theme:Fe(["light","dark"]).optional()}),Sn=T({icons:z(Fv).optional()}),Or=T({name:f(),title:f().optional()}),If=Or.extend({...Or.shape,...Sn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),Vv=Lo(T({applyDefaults:ne().optional()}),ue(f(),he())),Hv=ea(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Lo(T({form:Vv.optional(),url:Se.optional()}),ue(f(),he()).optional())),Bv=$e({list:Se.optional(),cancel:Se.optional(),requests:$e({sampling:$e({createMessage:Se.optional()}).optional(),elicitation:$e({create:Se.optional()}).optional()}).optional()}),Kv=$e({list:Se.optional(),cancel:Se.optional(),requests:$e({tools:$e({call:Se.optional()}).optional()}).optional()}),Jv=T({experimental:ue(f(),Se).optional(),sampling:T({context:Se.optional(),tools:Se.optional()}).optional(),elicitation:Hv.optional(),roots:T({listChanged:ne().optional()}).optional(),tasks:Bv.optional(),extensions:ue(f(),Se).optional()}),Gv=Ge.extend({protocolVersion:f(),capabilities:Jv,clientInfo:If}),Wv=xe.extend({method:E("initialize"),params:Gv});var Yv=T({experimental:ue(f(),Se).optional(),logging:Se.optional(),completions:Se.optional(),prompts:T({listChanged:ne().optional()}).optional(),resources:T({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:T({listChanged:ne().optional()}).optional(),tasks:Kv.optional(),extensions:ue(f(),Se).optional()}),sa=ke.extend({protocolVersion:f(),capabilities:Yv,serverInfo:If,instructions:f().optional()}),Of=et.extend({method:E("notifications/initialized"),params:Xe.optional()}),Af=e=>Of.safeParse(e).success,Jo=xe.extend({method:E("ping"),params:Ge.optional()}),Qv=T({progress:Y(),total:ge(Y()),message:ge(f())}),Xv=T({...Xe.shape,...Qv.shape,progressToken:xf}),Go=et.extend({method:E("notifications/progress"),params:Xv}),eb=Ge.extend({cursor:kf.optional()}),xn=xe.extend({params:eb.optional()}),kn=ke.extend({nextCursor:kf.optional()}),tb=Fe(["working","input_required","completed","failed","cancelled"]),zn=T({taskId:f(),status:tb,ttl:de([Y(),pf()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ge(Y()),statusMessage:ge(f())}),tr=ke.extend({task:zn}),rb=Xe.merge(zn),Tn=et.extend({method:E("notifications/tasks/status"),params:rb}),Wo=xe.extend({method:E("tasks/get"),params:Ge.extend({taskId:f()})}),Yo=ke.merge(zn),Qo=xe.extend({method:E("tasks/result"),params:Ge.extend({taskId:f()})}),pE=ke.loose(),Xo=xn.extend({method:E("tasks/list")}),es=kn.extend({tasks:z(zn)}),ts=xe.extend({method:E("tasks/cancel"),params:Ge.extend({taskId:f()})}),Cf=ke.merge(zn),Nf=T({uri:f(),mimeType:ge(f()),_meta:ue(f(),he()).optional()}),jf=Nf.extend({text:f()}),ia=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mf=Nf.extend({blob:ia}),Pn=Fe(["user","assistant"]),Nr=T({audience:z(Pn).optional(),priority:Y().min(0).max(1).optional(),lastModified:vn.datetime({offset:!0}).optional()}),Uf=T({...Or.shape,...Sn.shape,uri:f(),description:ge(f()),mimeType:ge(f()),size:ge(Y()),annotations:Nr.optional(),_meta:ge($e({}))}),nb=T({...Or.shape,...Sn.shape,uriTemplate:f(),description:ge(f()),mimeType:ge(f()),annotations:Nr.optional(),_meta:ge($e({}))}),ob=xn.extend({method:E("resources/list")}),aa=kn.extend({resources:z(Uf)}),sb=xn.extend({method:E("resources/templates/list")}),ca=kn.extend({resourceTemplates:z(nb)}),ua=Ge.extend({uri:f()}),ib=ua,ab=xe.extend({method:E("resources/read"),params:ib}),la=ke.extend({contents:z(de([jf,Mf]))}),da=et.extend({method:E("notifications/resources/list_changed"),params:Xe.optional()}),cb=ua,ub=xe.extend({method:E("resources/subscribe"),params:cb}),lb=ua,db=xe.extend({method:E("resources/unsubscribe"),params:lb}),pb=Xe.extend({uri:f()}),fb=et.extend({method:E("notifications/resources/updated"),params:pb}),mb=T({name:f(),description:ge(f()),required:ge(ne())}),hb=T({...Or.shape,...Sn.shape,description:ge(f()),arguments:ge(z(mb)),_meta:ge($e({}))}),gb=xn.extend({method:E("prompts/list")}),pa=kn.extend({prompts:z(hb)}),_b=Ge.extend({name:f(),arguments:ue(f(),f()).optional()}),yb=xe.extend({method:E("prompts/get"),params:_b}),fa=T({type:E("text"),text:f(),annotations:Nr.optional(),_meta:ue(f(),he()).optional()}),ma=T({type:E("image"),data:ia,mimeType:f(),annotations:Nr.optional(),_meta:ue(f(),he()).optional()}),ha=T({type:E("audio"),data:ia,mimeType:f(),annotations:Nr.optional(),_meta:ue(f(),he()).optional()}),vb=T({type:E("tool_use"),name:f(),id:f(),input:ue(f(),he()),_meta:ue(f(),he()).optional()}),bb=T({type:E("resource"),resource:de([jf,Mf]),annotations:Nr.optional(),_meta:ue(f(),he()).optional()}),wb=Uf.extend({type:E("resource_link")}),ga=de([fa,ma,ha,wb,bb]),$b=T({role:Pn,content:ga}),_a=ke.extend({description:f().optional(),messages:z($b)}),ya=et.extend({method:E("notifications/prompts/list_changed"),params:Xe.optional()}),Sb=T({title:f().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),xb=T({taskSupport:Fe(["required","optional","forbidden"]).optional()}),Df=T({...Or.shape,...Sn.shape,description:f().optional(),inputSchema:T({type:E("object"),properties:ue(f(),Se).optional(),required:z(f()).optional()}).catchall(he()),outputSchema:T({type:E("object"),properties:ue(f(),Se).optional(),required:z(f()).optional()}).catchall(he()).optional(),annotations:Sb.optional(),execution:xb.optional(),_meta:ue(f(),he()).optional()}),kb=xn.extend({method:E("tools/list")}),va=kn.extend({tools:z(Df)}),jr=ke.extend({content:z(ga).default([]),structuredContent:ue(f(),he()).optional(),isError:ne().optional()}),fE=jr.or(ke.extend({toolResult:he()})),zb=wn.extend({name:f(),arguments:ue(f(),he()).optional()}),Tb=xe.extend({method:E("tools/call"),params:zb}),ba=et.extend({method:E("notifications/tools/list_changed"),params:Xe.optional()}),Zf=T({autoRefresh:ne().default(!0),debounceMs:Y().int().nonnegative().default(300)}),qf=Fe(["debug","info","notice","warning","error","critical","alert","emergency"]),Pb=Ge.extend({level:qf}),Rb=xe.extend({method:E("logging/setLevel"),params:Pb}),Eb=Xe.extend({level:qf,logger:f().optional(),data:he()}),Ib=et.extend({method:E("notifications/message"),params:Eb}),Ob=T({name:f().optional()}),Ab=T({hints:z(Ob).optional(),costPriority:Y().min(0).max(1).optional(),speedPriority:Y().min(0).max(1).optional(),intelligencePriority:Y().min(0).max(1).optional()}),Cb=T({mode:Fe(["auto","required","none"]).optional()}),Nb=T({type:E("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:z(ga).default([]),structuredContent:T({}).loose().optional(),isError:ne().optional(),_meta:ue(f(),he()).optional()}),jb=Xi("type",[fa,ma,ha]),Vo=Xi("type",[fa,ma,ha,vb,Nb]),Mb=T({role:Pn,content:de([Vo,z(Vo)]),_meta:ue(f(),he()).optional()}),Ub=wn.extend({messages:z(Mb),modelPreferences:Ab.optional(),systemPrompt:f().optional(),includeContext:Fe(["none","thisServer","allServers"]).optional(),temperature:Y().optional(),maxTokens:Y().int(),stopSequences:z(f()).optional(),metadata:Se.optional(),tools:z(Df).optional(),toolChoice:Cb.optional()}),wa=xe.extend({method:E("sampling/createMessage"),params:Ub}),$a=ke.extend({model:f(),stopReason:ge(Fe(["endTurn","stopSequence","maxTokens"]).or(f())),role:Pn,content:jb}),Sa=ke.extend({model:f(),stopReason:ge(Fe(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:Pn,content:de([Vo,z(Vo)])}),Db=T({type:E("boolean"),title:f().optional(),description:f().optional(),default:ne().optional()}),Zb=T({type:E("string"),title:f().optional(),description:f().optional(),minLength:Y().optional(),maxLength:Y().optional(),format:Fe(["email","uri","date","date-time"]).optional(),default:f().optional()}),qb=T({type:Fe(["number","integer"]),title:f().optional(),description:f().optional(),minimum:Y().optional(),maximum:Y().optional(),default:Y().optional()}),Lb=T({type:E("string"),title:f().optional(),description:f().optional(),enum:z(f()),default:f().optional()}),Fb=T({type:E("string"),title:f().optional(),description:f().optional(),oneOf:z(T({const:f(),title:f()})),default:f().optional()}),Vb=T({type:E("string"),title:f().optional(),description:f().optional(),enum:z(f()),enumNames:z(f()).optional(),default:f().optional()}),Hb=de([Lb,Fb]),Bb=T({type:E("array"),title:f().optional(),description:f().optional(),minItems:Y().optional(),maxItems:Y().optional(),items:T({type:E("string"),enum:z(f())}),default:z(f()).optional()}),Kb=T({type:E("array"),title:f().optional(),description:f().optional(),minItems:Y().optional(),maxItems:Y().optional(),items:T({anyOf:z(T({const:f(),title:f()}))}),default:z(f()).optional()}),Jb=de([Bb,Kb]),Gb=de([Vb,Hb,Jb]),Wb=de([Gb,Db,Zb,qb]),Yb=wn.extend({mode:E("form").optional(),message:f(),requestedSchema:T({type:E("object"),properties:ue(f(),Wb),required:z(f()).optional()})}),Qb=wn.extend({mode:E("url"),message:f(),elicitationId:f(),url:f().url()}),Xb=de([Yb,Qb]),xa=xe.extend({method:E("elicitation/create"),params:Xb}),ew=Xe.extend({elicitationId:f()}),tw=et.extend({method:E("notifications/elicitation/complete"),params:ew}),ka=ke.extend({action:Fe(["accept","decline","cancel"]),content:ea(e=>e===null?void 0:e,ue(f(),de([f(),Y(),ne(),z(f())])).optional())}),rw=T({type:E("ref/resource"),uri:f()});var nw=T({type:E("ref/prompt"),name:f()}),ow=Ge.extend({ref:de([nw,rw]),argument:T({name:f(),value:f()}),context:T({arguments:ue(f(),f()).optional()}).optional()}),sw=xe.extend({method:E("completion/complete"),params:ow});var za=ke.extend({completion:$e({values:z(f()).max(100),total:ge(Y().int()),hasMore:ge(ne())})}),iw=T({uri:f().startsWith("file://"),name:f().optional(),_meta:ue(f(),he()).optional()}),aw=xe.extend({method:E("roots/list"),params:Ge.optional()}),cw=ke.extend({roots:z(iw)}),uw=et.extend({method:E("notifications/roots/list_changed"),params:Xe.optional()}),mE=de([Jo,Wv,sw,Rb,yb,gb,ob,sb,ab,ub,db,Tb,kb,Wo,Qo,Xo,ts]),hE=de([Ko,Go,Of,uw,Tn]),gE=de([er,$a,Sa,ka,cw,Yo,es,tr]),_E=de([Jo,wa,xa,aw,Wo,Qo,Xo,ts]),yE=de([Ko,Go,Ib,fb,da,ba,ya,Tn,tw]),vE=de([er,sa,za,_a,pa,aa,ca,la,jr,va,Yo,es,tr]),j=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===U.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ta(o.elicitations,r)}return new e(t,r,n)}},ta=class extends j{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Mt(e){return e==="completed"||e==="failed"||e==="cancelled"}var lw=Symbol("Let zodToJsonSchema decide on which parser to use");var QE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ta(e){let r=Do(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Kp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Pa(e,t){let r=ct(e,t);if(!r.success)throw r.error;return r.data}var gw=6e4,rs=class{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(Ko,r=>{this._oncancel(r)}),this.setNotificationHandler(Go,r=>{this._onprogress(r)}),this.setRequestHandler(Jo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Wo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Qo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new j(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new j(U.InvalidParams,`Task not found: ${s}`);if(!Mt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[jt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Xo,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new j(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ts,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mt(o.status))throw new j(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new j(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof j?o:new j(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){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),j.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Xt(s)||Ef(s)?this._onresponse(s):$n(s)?this._onrequest(s,i):Rf(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=j.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[jt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let a=zf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new j(U.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:t.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).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,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xt(t))n(t);else{let i=new j(t.error.code,t.error.message,t.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Xt(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Xt(t))o(t);else{let i=j.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof j?i:new j(U.InternalError,String(i))}}return}let s;try{let i=await this.request(t,tr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new j(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Mt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new j(U.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new j(U.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof j?i:new j(U.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch($){d($);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[jt]:c}});let h=$=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String($)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let w=$ instanceof j?$:new j(U.RequestTimeout,String($));l(w)};this._responseHandlers.set(p,$=>{if(!n?.signal?.aborted){if($ instanceof Error)return l($);try{let w=ct(r,$.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??gw,y=()=>h(j.fromError(U.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let $=w=>{let P=this._responseHandlers.get(p);P?P(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,$),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),l(w)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>{this._cleanupTimeout(p),l($)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Yo,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},es,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Cf,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 a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[jt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,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 a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[jt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[jt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=Ta(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Pa(t,o);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=Ta(t);this._notificationHandlers.set(n,o=>{let s=Pa(t,o);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 o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&$n(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new j(U.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 o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new j(U.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new j(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Tn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new j(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mt(a.status))throw new j(U.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Tn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Lf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ff(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];Lf(i)&&Lf(s)?r[o]={...i,...s}:r[o]=s}return r}var Cg=nl(mu(),1),Ng=nl(Ag(),1);function bz(){let e=new Cg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ng.default)(e),e}var Ms=class{constructor(t){this._ajv=t??bz()}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 Us=class{constructor(t){this._client=t}async*callToolStream(t,r=jr,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new j(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof j){yield{type:"error",error:l};return}yield{type:"error",error:new j(U.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}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 jg(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}}function Mg(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}}function Ds(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 o of Object.keys(n)){let s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Ds(s,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ds(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ds(r,t)}}function wz(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}}var Zs=class extends rs{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 Ms,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ba,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ya,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",da,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Us(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ff(this._capabilities,t)}setRequestHandler(t,r){let o=Do(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ir(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=ct(xa,c);if(!l.success){let $=l.error instanceof Error?l.error.message:String(l.error);throw new j(U.InvalidParams,`Invalid elicitation request: ${$}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:m}=wz(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new j(U.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!m)throw new j(U.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let $=ct(tr,h);if(!$.success){let w=$.error instanceof Error?$.error.message:String($.error);throw new j(U.InvalidParams,`Invalid task creation result: ${w}`)}return $.data}let g=ct(ka,h);if(!g.success){let $=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid elicitation result: ${$}`)}let y=g.data,S=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Ds(S,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=ct(wa,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new j(U.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let y=ct(tr,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new j(U.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=d.tools||d.toolChoice?Sa:$a,g=ct(h,p);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(t,a)}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:Ar,capabilities:this._capabilities,clientInfo:this._clientInfo}},sa,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sf.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){jg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Mg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},er,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},za,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},er,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},_a,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},pa,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},aa,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ca,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},la,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},er,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},er,r)}async callTool(t,r=jr,n){if(this.isToolTaskRequired(t.name))throw new j(U.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new j(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof j?i:new j(U.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}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},va,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=Zf.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:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(t,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function qs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Ug(e=fetch,t){return t?async(r,n)=>{let o={...t,...n,headers:n?.headers?{...qs(t.headers),...qs(n.headers)}:t.headers};return e(r,o)}:e}var $u;$u=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function $z(e){return(await $u).getRandomValues(new Uint8Array(e))}async function Sz(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await $z(e-n.length);for(let s of o)s<r&&(n+=t[s%t.length])}return n}async function xz(e){return await Sz(e)}async function kz(e){let t=await(await $u).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Su(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await xz(e),r=await kz(t);return{code_verifier:t,code_challenge:r}}var Re=lf().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:$f.custom,message:"URL must be parseable",fatal:!0}),ci}).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"}),Zg=$e({resource:f().url(),authorization_servers:z(Re).optional(),jwks_uri:f().url().optional(),scopes_supported:z(f()).optional(),bearer_methods_supported:z(f()).optional(),resource_signing_alg_values_supported:z(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:ne().optional(),authorization_details_types_supported:z(f()).optional(),dpop_signing_alg_values_supported:z(f()).optional(),dpop_bound_access_tokens_required:ne().optional()}),xu=$e({issuer:f(),authorization_endpoint:Re,token_endpoint:Re,registration_endpoint:Re.optional(),scopes_supported:z(f()).optional(),response_types_supported:z(f()),response_modes_supported:z(f()).optional(),grant_types_supported:z(f()).optional(),token_endpoint_auth_methods_supported:z(f()).optional(),token_endpoint_auth_signing_alg_values_supported:z(f()).optional(),service_documentation:Re.optional(),revocation_endpoint:Re.optional(),revocation_endpoint_auth_methods_supported:z(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:z(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(f()).optional(),code_challenge_methods_supported:z(f()).optional(),client_id_metadata_document_supported:ne().optional()}),zz=$e({issuer:f(),authorization_endpoint:Re,token_endpoint:Re,userinfo_endpoint:Re.optional(),jwks_uri:Re,registration_endpoint:Re.optional(),scopes_supported:z(f()).optional(),response_types_supported:z(f()),response_modes_supported:z(f()).optional(),grant_types_supported:z(f()).optional(),acr_values_supported:z(f()).optional(),subject_types_supported:z(f()),id_token_signing_alg_values_supported:z(f()),id_token_encryption_alg_values_supported:z(f()).optional(),id_token_encryption_enc_values_supported:z(f()).optional(),userinfo_signing_alg_values_supported:z(f()).optional(),userinfo_encryption_alg_values_supported:z(f()).optional(),userinfo_encryption_enc_values_supported:z(f()).optional(),request_object_signing_alg_values_supported:z(f()).optional(),request_object_encryption_alg_values_supported:z(f()).optional(),request_object_encryption_enc_values_supported:z(f()).optional(),token_endpoint_auth_methods_supported:z(f()).optional(),token_endpoint_auth_signing_alg_values_supported:z(f()).optional(),display_values_supported:z(f()).optional(),claim_types_supported:z(f()).optional(),claims_supported:z(f()).optional(),service_documentation:f().optional(),claims_locales_supported:z(f()).optional(),ui_locales_supported:z(f()).optional(),claims_parameter_supported:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:Re.optional(),op_tos_uri:Re.optional(),client_id_metadata_document_supported:ne().optional()}),qg=T({...zz.shape,...xu.pick({code_challenge_methods_supported:!0}).shape}),Lg=T({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Fo.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Fg=T({error:f(),error_description:f().optional(),error_uri:f().optional()}),Dg=Re.optional().or(E("").transform(()=>{})),Tz=T({redirect_uris:z(Re),token_endpoint_auth_method:f().optional(),grant_types:z(f()).optional(),response_types:z(f()).optional(),client_name:f().optional(),client_uri:Re.optional(),logo_uri:Dg,scope:f().optional(),contacts:z(f()).optional(),tos_uri:Dg,policy_uri:f().optional(),jwks_uri:Re.optional(),jwks:ff().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Pz=T({client_id:f(),client_secret:f().optional(),client_id_issued_at:Y().optional(),client_secret_expires_at:Y().optional()}).strip(),Vg=Tz.merge(Pz),x1=T({error:f(),error_description:f().optional()}).strip(),k1=T({token:f(),token_type_hint:f().optional()}).strip();function Hg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Bg({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 o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var ve=class extends Error{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}},so=class extends ve{};so.errorCode="invalid_request";var fr=class extends ve{};fr.errorCode="invalid_client";var mr=class extends ve{};mr.errorCode="invalid_grant";var hr=class extends ve{};hr.errorCode="unauthorized_client";var io=class extends ve{};io.errorCode="unsupported_grant_type";var ao=class extends ve{};ao.errorCode="invalid_scope";var co=class extends ve{};co.errorCode="access_denied";var Ot=class extends ve{};Ot.errorCode="server_error";var uo=class extends ve{};uo.errorCode="temporarily_unavailable";var lo=class extends ve{};lo.errorCode="unsupported_response_type";var po=class extends ve{};po.errorCode="unsupported_token_type";var fo=class extends ve{};fo.errorCode="invalid_token";var mo=class extends ve{};mo.errorCode="method_not_allowed";var ho=class extends ve{};ho.errorCode="too_many_requests";var gr=class extends ve{};gr.errorCode="invalid_client_metadata";var go=class extends ve{};go.errorCode="insufficient_scope";var _o=class extends ve{};_o.errorCode="invalid_target";var Kg={[so.errorCode]:so,[fr.errorCode]:fr,[mr.errorCode]:mr,[hr.errorCode]:hr,[io.errorCode]:io,[ao.errorCode]:ao,[co.errorCode]:co,[Ot.errorCode]:Ot,[uo.errorCode]:uo,[lo.errorCode]:lo,[po.errorCode]:po,[fo.errorCode]:fo,[mo.errorCode]:mo,[ho.errorCode]:ho,[gr.errorCode]:gr,[go.errorCode]:go,[_o.errorCode]:_o};var At=class extends Error{constructor(t){super(t??"Unauthorized")}};function Rz(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var ku="code",zu="S256";function Ez(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Rz(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"}function Iz(e,t,r,n){let{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":Oz(o,s,r);return;case"client_secret_post":Az(o,s,n);return;case"none":Cz(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Oz(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}`)}function Az(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function Cz(e,t){t.set("client_id",e)}async function Gg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Fg.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Kg[o]||Ot;return new a(s||"",i)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Ot(o)}}async function yo(e,t){try{return await Tu(e,t)}catch(r){if(r instanceof fr||r instanceof hr)return await e.invalidateCredentials?.("all"),await Tu(e,t);if(r instanceof mr)return await e.invalidateCredentials?.("tokens"),await Tu(e,t);throw r}}async function Tu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await e.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await Yg(c,{fetchFn:s}),!a)try{a=await Wg(t,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let w=await qz(t,{resourceMetadataUrl:l,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await jz(t,e,a),p=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,m=await Promise.resolve(e.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!Nz(P))throw new gr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if(w&&P)m={client_id:P},await e.saveClientInformation?.(m);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let k=await Bz(c,{metadata:u,clientMetadata:e.clientMetadata,scope:p,fetchFn:s});await e.saveClientInformation(k),m=k}}let h=!e.redirectUrl;if(r!==void 0||h){let w=await Hz(e,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}let g=await e.tokens();if(g?.refresh_token)try{let w=await Vz(c,{metadata:u,clientInformation:m,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof ve)||w instanceof Ot))throw w}let y=e.state?await e.state():void 0,{authorizationUrl:S,codeVerifier:$}=await Lz(c,{metadata:u,clientInformation:m,state:y,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier($),await e.redirectToAuthorization(S),"REDIRECT"}function Nz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function jz(e,t,r){let n=Hg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Bg({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ru(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Pu(e,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Pu(e,"scope")||void 0,a=Pu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Pu(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function Wg(e,t,r=fetch){let n=await Dz(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 Zg.parse(await n.json())}async function Eu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Eu(e,void 0,r):void 0;throw n}}function Mz(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Jg(e,t,r=fetch){return await Eu(e,{"MCP-Protocol-Version":t},r)}function Uz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Dz(e,t,r,n){let o=new URL(e),s=n?.protocolVersion??Ar,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=Mz(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Jg(i,s,r);if(!n?.metadataUrl&&Uz(a,o.pathname)){let c=new URL(`/.well-known/${t}`,o);a=await Jg(c,s,r)}return a}function Zz(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 o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function Yg(e,{fetchFn:t=fetch,protocolVersion:r=Ar}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Zz(e);for(let{url:s,type:i}of o){let a=await Eu(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?xu.parse(await a.json()):qg.parse(await a.json())}}}async function qz(e,t){let r,n;try{r=await Wg(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 o=await Yg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Lz(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ku))throw new Error(`Incompatible auth server: does not support response type ${ku}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(zu))throw new Error(`Incompatible auth server: does not support code challenge method ${zu}`)}else a=new URL("/authorize",e);let c=await Su(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",ku),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",zu),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function Fz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Qg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){let a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,a,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],d=Ez(n,l);Iz(d,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await Gg(u);return Lg.parse(await u.json())}async function Vz(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Qg(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function Hz(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=e.clientMetadata.scope,a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await e.codeVerifier();a=Fz(o,u,e.redirectUrl)}let c=await e.clientInformation();return Qg(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Bz(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){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(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await Gg(i);return Vg.parse(await i.json())}var vo=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},Xg=10,Kz=13,_r=32;function Iu(e){}function r_(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Iu,onError:r=Iu,onRetry:n=Iu,onComment:o,maxBufferSize:s}=e,i=[],a=0,c=!0,u,l="",d=0,p,m=!1;function h(v){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){let W=y(v);W!==""&&(i.push(W),a=W.length),g();return}if(v.indexOf(`
36
- `)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let k=i.join("");i.length=0,a=0;let A=y(k);A!==""&&(i.push(A),a=A.length),g()}function g(){s!==void 0&&(a+l.length<=s||(m=!0,i.length=0,a=0,u=void 0,l="",d=0,p=void 0,r(new vo(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let k=0;if(v.indexOf("\r")===-1){let A=v.indexOf(`
34
+ path: iss.path ? [${Yt($)}, ...iss.path] : [${Yt($)}]
35
+ })));`),p.write(`newResult[${Yt($)}] = ${w}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return($,w)=>S(d,$,w)},o,s=kr,i=!To.jitless,c=i&&hi.value,u=t.catchall,l;e._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;let h=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let w=l.shape;for(let T of l.keys){let v=w[T],k=v._zod.run({value:m[T],issues:[]},p),A=v._zod.optin==="optional"&&v._zod.optout==="optional";k instanceof Promise?h.push(k.then(W=>A?rd(W,d,T,m):jo(W,d,T))):A?rd(k,d,T,m):jo(k,d,T)}}if(!u)return h.length?Promise.all(h).then(()=>d):d;let g=[],y=l.keySet,S=u._zod,$=S.def.type;for(let w of Object.keys(m)){if(y.has(w))continue;if($==="never"){g.push(w);continue}let T=S.run({value:m[w],issues:[]},p);T instanceof Promise?h.push(T.then(v=>jo(v,d,w))):jo(T,d,w)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function nd(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>it(s,n,Je())))}),t}var Ii=_("$ZodUnion",(e,t)=>{te.init(e,t),ae(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ae(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ae(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ae(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>hn(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of t.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>nd(i,r,e,n)):nd(s,r,e,n)}}),Vd=_("$ZodDiscriminatedUnion",(e,t)=>{Ii.init(e,t);let r=e._zod.parse;ae(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=fn(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!kr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),Hd=_("$ZodIntersection",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>od(r,c,u)):od(r,s,i)}});function Ri(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(zr(e)&&zr(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=Ri(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=Ri(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function od(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Qt(e))return e;let n=Ri(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Bd=_("$ZodRecord",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!zr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[];if(t.keyType._zod.values){let i=t.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ht(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ht(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=t.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>it(u,n,Je())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ht(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ht(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Kd=_("$ZodEnum",(e,t)=>{te.init(e,t);let r=di(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>gi.has(typeof n)).map(n=>typeof n=="string"?jt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Jd=_("$ZodLiteral",(e,t)=>{te.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?jt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Gd=_("$ZodTransform",(e,t)=>{te.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new zt;return r.value=o,r}}),Wd=_("$ZodOptional",(e,t)=>{te.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ae(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${hn(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Yd=_("$ZodNullable",(e,t)=>{te.init(e,t),ae(e._zod,"optin",()=>t.innerType._zod.optin),ae(e._zod,"optout",()=>t.innerType._zod.optout),ae(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${hn(r.source)}|null)$`):void 0}),ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Qd=_("$ZodDefault",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sd(s,t)):sd(o,t)}});function sd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Xd=_("$ZodPrefault",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),ep=_("$ZodNonOptional",(e,t)=>{te.init(e,t),ae(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>id(s,e)):id(o,e)}});function id(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var tp=_("$ZodCatch",(e,t)=>{te.init(e,t),e._zod.optin="optional",ae(e._zod,"optout",()=>t.innerType._zod.optout),ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>it(i,n,Je()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>it(s,n,Je()))},input:r.value}),r.issues=[]),r)}});var rp=_("$ZodPipe",(e,t)=>{te.init(e,t),ae(e._zod,"values",()=>t.in._zod.values),ae(e._zod,"optin",()=>t.in._zod.optin),ae(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ad(s,t,n)):ad(o,t,n)}});function ad(e,t,r){return Qt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var np=_("$ZodReadonly",(e,t)=>{te.init(e,t),ae(e._zod,"propValues",()=>t.innerType._zod.propValues),ae(e._zod,"values",()=>t.innerType._zod.values),ae(e._zod,"optin",()=>t.innerType._zod.optin),ae(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(cd):cd(o)}});function cd(e){return e.value=Object.freeze(e.value),e}var op=_("$ZodCustom",(e,t)=>{Ie.init(e,t),te.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>ud(s,r,n,e));ud(o,r,n,e)}});function ud(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(vi(o))}}var Ny=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},jy=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Ny(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Io(n.values[0])}`:`Invalid option: expected one of ${Ro(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ro(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function sp(){return{localeError:jy()}}var My=Symbol("ZodOutput"),Uy=Symbol("ZodInput"),Oi=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function ip(){return new Oi}var Pr=ip();function ap(e,t){return new e({type:"string",...C(t)})}function cp(e,t){return new e({type:"string",coerce:!0,...C(t)})}function up(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})}function Ai(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})}function lp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})}function dp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})}function pp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})}function fp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})}function Ci(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})}function mp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})}function hp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})}function gp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})}function _p(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})}function yp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})}function vp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})}function bp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})}function wp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})}function $p(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})}function Sp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})}function xp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})}function kp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})}function zp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})}function Pp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})}function Tp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})}function Rp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})}function Ep(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})}function Ip(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})}function Op(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})}function Ap(e,t){return new e({type:"number",checks:[],...C(t)})}function Cp(e,t){return new e({type:"number",coerce:!0,checks:[],...C(t)})}function Np(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})}function jp(e,t){return new e({type:"boolean",...C(t)})}function Mp(e,t){return new e({type:"boolean",coerce:!0,...C(t)})}function Up(e,t){return new e({type:"bigint",coerce:!0,...C(t)})}function Dp(e,t){return new e({type:"null",...C(t)})}function Zp(e){return new e({type:"any"})}function qp(e){return new e({type:"unknown"})}function Lp(e,t){return new e({type:"never",...C(t)})}function Fp(e,t){return new e({type:"date",coerce:!0,...C(t)})}function Tr(e,t){return new Pi({check:"less_than",...C(t),value:e,inclusive:!1})}function Pt(e,t){return new Pi({check:"less_than",...C(t),value:e,inclusive:!0})}function Rr(e,t){return new Ti({check:"greater_than",...C(t),value:e,inclusive:!1})}function at(e,t){return new Ti({check:"greater_than",...C(t),value:e,inclusive:!0})}function vn(e,t){return new ql({check:"multiple_of",...C(t),value:e})}function Uo(e,t){return new Fl({check:"max_length",...C(t),maximum:e})}function Er(e,t){return new Vl({check:"min_length",...C(t),minimum:e})}function Do(e,t){return new Hl({check:"length_equals",...C(t),length:e})}function Ni(e,t){return new Bl({check:"string_format",format:"regex",...C(t),pattern:e})}function ji(e){return new Kl({check:"string_format",format:"lowercase",...C(e)})}function Mi(e){return new Jl({check:"string_format",format:"uppercase",...C(e)})}function Ui(e,t){return new Gl({check:"string_format",format:"includes",...C(t),includes:e})}function Di(e,t){return new Wl({check:"string_format",format:"starts_with",...C(t),prefix:e})}function Zi(e,t){return new Yl({check:"string_format",format:"ends_with",...C(t),suffix:e})}function Xt(e){return new Ql({check:"overwrite",tx:e})}function qi(e){return Xt(t=>t.normalize(e))}function Li(){return Xt(e=>e.trim())}function Fi(){return Xt(e=>e.toLowerCase())}function Vi(){return Xt(e=>e.toUpperCase())}function Vp(e,t,r){return new e({type:"array",element:t,...C(r)})}function Hp(e,t,r){let n=C(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Bp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})}function Or(e){return!!e._zod}function ct(e,t){return Or(e)?_n(e,t):e.safeParse(t)}function Zo(e){if(!e)return;let t;if(Or(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Kp(e){if(Or(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}var bn={};ai(bn,{ZodISODate:()=>Gp,ZodISODateTime:()=>Jp,ZodISODuration:()=>Yp,ZodISOTime:()=>Wp,date:()=>Bi,datetime:()=>Hi,duration:()=>Ji,time:()=>Ki});var Jp=_("ZodISODateTime",(e,t)=>{wd.init(e,t),me.init(e,t)});function Hi(e){return Rp(Jp,e)}var Gp=_("ZodISODate",(e,t)=>{$d.init(e,t),me.init(e,t)});function Bi(e){return Ep(Gp,e)}var Wp=_("ZodISOTime",(e,t)=>{Sd.init(e,t),me.init(e,t)});function Ki(e){return Ip(Wp,e)}var Yp=_("ZodISODuration",(e,t)=>{xd.init(e,t),me.init(e,t)});function Ji(e){return Op(Yp,e)}var Xp=(e,t)=>{Oo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>$i(e,r)},flatten:{value:r=>wi(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},_R=_("ZodError",Xp),wn=_("ZodError",Xp,{Parent:Error});var ef=cl(wn),tf=ul(wn),rf=Si(wn),nf=xi(wn);var ce=_("ZodType",(e,t)=>(te.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>st(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>ef(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>rf(e,r,n),e.parseAsync=async(r,n)=>tf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>nf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Ov(r,n)),e.superRefine=r=>e.check(Av(r)),e.overwrite=r=>e.check(Xt(r)),e.optional=()=>ge(e),e.nullable=()=>af(e),e.nullish=()=>ge(af(e)),e.nonoptional=r=>kv(e,r),e.array=()=>z(e),e.or=r=>de([e,r]),e.and=r=>Fo(e,r),e.transform=r=>Wi(e,_f(r)),e.default=r=>$v(e,r),e.prefault=r=>xv(e,r),e.catch=r=>Pv(e,r),e.pipe=r=>Wi(e,r),e.readonly=()=>Ev(e),e.describe=r=>{let n=e.clone();return Pr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Pr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Pr.get(e);let n=e.clone();return Pr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),cf=_("_ZodString",(e,t)=>{Mo.init(e,t),ce.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Ni(...n)),e.includes=(...n)=>e.check(Ui(...n)),e.startsWith=(...n)=>e.check(Di(...n)),e.endsWith=(...n)=>e.check(Zi(...n)),e.min=(...n)=>e.check(Er(...n)),e.max=(...n)=>e.check(Uo(...n)),e.length=(...n)=>e.check(Do(...n)),e.nonempty=(...n)=>e.check(Er(1,...n)),e.lowercase=n=>e.check(ji(n)),e.uppercase=n=>e.check(Mi(n)),e.trim=()=>e.check(Li()),e.normalize=(...n)=>e.check(qi(...n)),e.toLowerCase=()=>e.check(Fi()),e.toUpperCase=()=>e.check(Vi())}),Yi=_("ZodString",(e,t)=>{Mo.init(e,t),cf.init(e,t),e.email=r=>e.check(up(By,r)),e.url=r=>e.check(Ci(uf,r)),e.jwt=r=>e.check(Tp(av,r)),e.emoji=r=>e.check(mp(Ky,r)),e.guid=r=>e.check(Ai(of,r)),e.uuid=r=>e.check(lp(qo,r)),e.uuidv4=r=>e.check(dp(qo,r)),e.uuidv6=r=>e.check(pp(qo,r)),e.uuidv7=r=>e.check(fp(qo,r)),e.nanoid=r=>e.check(hp(Jy,r)),e.guid=r=>e.check(Ai(of,r)),e.cuid=r=>e.check(gp(Gy,r)),e.cuid2=r=>e.check(_p(Wy,r)),e.ulid=r=>e.check(yp(Yy,r)),e.base64=r=>e.check(kp(ov,r)),e.base64url=r=>e.check(zp(sv,r)),e.xid=r=>e.check(vp(Qy,r)),e.ksuid=r=>e.check(bp(Xy,r)),e.ipv4=r=>e.check(wp(ev,r)),e.ipv6=r=>e.check($p(tv,r)),e.cidrv4=r=>e.check(Sp(rv,r)),e.cidrv6=r=>e.check(xp(nv,r)),e.e164=r=>e.check(Pp(iv,r)),e.datetime=r=>e.check(Hi(r)),e.date=r=>e.check(Bi(r)),e.time=r=>e.check(Ki(r)),e.duration=r=>e.check(Ji(r))});function f(e){return ap(Yi,e)}var me=_("ZodStringFormat",(e,t)=>{le.init(e,t),cf.init(e,t)}),By=_("ZodEmail",(e,t)=>{pd.init(e,t),me.init(e,t)});var of=_("ZodGUID",(e,t)=>{ld.init(e,t),me.init(e,t)});var qo=_("ZodUUID",(e,t)=>{dd.init(e,t),me.init(e,t)});var uf=_("ZodURL",(e,t)=>{fd.init(e,t),me.init(e,t)});function lf(e){return Ci(uf,e)}var Ky=_("ZodEmoji",(e,t)=>{md.init(e,t),me.init(e,t)});var Jy=_("ZodNanoID",(e,t)=>{hd.init(e,t),me.init(e,t)});var Gy=_("ZodCUID",(e,t)=>{gd.init(e,t),me.init(e,t)});var Wy=_("ZodCUID2",(e,t)=>{_d.init(e,t),me.init(e,t)});var Yy=_("ZodULID",(e,t)=>{yd.init(e,t),me.init(e,t)});var Qy=_("ZodXID",(e,t)=>{vd.init(e,t),me.init(e,t)});var Xy=_("ZodKSUID",(e,t)=>{bd.init(e,t),me.init(e,t)});var ev=_("ZodIPv4",(e,t)=>{kd.init(e,t),me.init(e,t)});var tv=_("ZodIPv6",(e,t)=>{zd.init(e,t),me.init(e,t)});var rv=_("ZodCIDRv4",(e,t)=>{Pd.init(e,t),me.init(e,t)});var nv=_("ZodCIDRv6",(e,t)=>{Td.init(e,t),me.init(e,t)});var ov=_("ZodBase64",(e,t)=>{Ed.init(e,t),me.init(e,t)});var sv=_("ZodBase64URL",(e,t)=>{Id.init(e,t),me.init(e,t)});var iv=_("ZodE164",(e,t)=>{Od.init(e,t),me.init(e,t)});var av=_("ZodJWT",(e,t)=>{Ad.init(e,t),me.init(e,t)});var Lo=_("ZodNumber",(e,t)=>{Ei.init(e,t),ce.init(e,t),e.gt=(n,o)=>e.check(Rr(n,o)),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.lt=(n,o)=>e.check(Tr(n,o)),e.lte=(n,o)=>e.check(Pt(n,o)),e.max=(n,o)=>e.check(Pt(n,o)),e.int=n=>e.check(sf(n)),e.safe=n=>e.check(sf(n)),e.positive=n=>e.check(Rr(0,n)),e.nonnegative=n=>e.check(at(0,n)),e.negative=n=>e.check(Tr(0,n)),e.nonpositive=n=>e.check(Pt(0,n)),e.multipleOf=(n,o)=>e.check(vn(n,o)),e.step=(n,o)=>e.check(vn(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Y(e){return Ap(Lo,e)}var cv=_("ZodNumberFormat",(e,t)=>{Cd.init(e,t),Lo.init(e,t)});function sf(e){return Np(cv,e)}var Qi=_("ZodBoolean",(e,t)=>{Nd.init(e,t),ce.init(e,t)});function oe(e){return jp(Qi,e)}var df=_("ZodBigInt",(e,t)=>{jd.init(e,t),ce.init(e,t),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.gt=(n,o)=>e.check(Rr(n,o)),e.gte=(n,o)=>e.check(at(n,o)),e.min=(n,o)=>e.check(at(n,o)),e.lt=(n,o)=>e.check(Tr(n,o)),e.lte=(n,o)=>e.check(Pt(n,o)),e.max=(n,o)=>e.check(Pt(n,o)),e.positive=n=>e.check(Rr(BigInt(0),n)),e.negative=n=>e.check(Tr(BigInt(0),n)),e.nonpositive=n=>e.check(Pt(BigInt(0),n)),e.nonnegative=n=>e.check(at(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(vn(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var uv=_("ZodNull",(e,t)=>{Md.init(e,t),ce.init(e,t)});function pf(e){return Dp(uv,e)}var lv=_("ZodAny",(e,t)=>{Ud.init(e,t),ce.init(e,t)});function ff(){return Zp(lv)}var dv=_("ZodUnknown",(e,t)=>{Dd.init(e,t),ce.init(e,t)});function he(){return qp(dv)}var pv=_("ZodNever",(e,t)=>{Zd.init(e,t),ce.init(e,t)});function fv(e){return Lp(pv,e)}var mf=_("ZodDate",(e,t)=>{qd.init(e,t),ce.init(e,t),e.min=(n,o)=>e.check(at(n,o)),e.max=(n,o)=>e.check(Pt(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var mv=_("ZodArray",(e,t)=>{Ld.init(e,t),ce.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Er(r,n)),e.nonempty=r=>e.check(Er(1,r)),e.max=(r,n)=>e.check(Uo(r,n)),e.length=(r,n)=>e.check(Do(r,n)),e.unwrap=()=>e.element});function z(e,t){return Vp(mv,e,t)}var hf=_("ZodObject",(e,t)=>{Fd.init(e,t),ce.init(e,t),X.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Fe(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:he()}),e.loose=()=>e.clone({...e._zod.def,catchall:he()}),e.strict=()=>e.clone({...e._zod.def,catchall:fv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>X.extend(e,r),e.merge=r=>X.merge(e,r),e.pick=r=>X.pick(e,r),e.omit=r=>X.omit(e,r),e.partial=(...r)=>X.partial(yf,e,r[0]),e.required=(...r)=>X.required(vf,e,r[0])});function P(e,t){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...e}),this.shape},...X.normalizeParams(t)};return new hf(r)}function $e(e,t){return new hf({type:"object",get shape(){return X.assignProp(this,"shape",{...e}),this.shape},catchall:he(),...X.normalizeParams(t)})}var gf=_("ZodUnion",(e,t)=>{Ii.init(e,t),ce.init(e,t),e.options=t.options});function de(e,t){return new gf({type:"union",options:e,...X.normalizeParams(t)})}var hv=_("ZodDiscriminatedUnion",(e,t)=>{gf.init(e,t),Vd.init(e,t)});function Xi(e,t,r){return new hv({type:"union",options:t,discriminator:e,...X.normalizeParams(r)})}var gv=_("ZodIntersection",(e,t)=>{Hd.init(e,t),ce.init(e,t)});function Fo(e,t){return new gv({type:"intersection",left:e,right:t})}var _v=_("ZodRecord",(e,t)=>{Bd.init(e,t),ce.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ue(e,t,r){return new _v({type:"record",keyType:e,valueType:t,...X.normalizeParams(r)})}var Gi=_("ZodEnum",(e,t)=>{Kd.init(e,t),ce.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...t,checks:[],...X.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...t,checks:[],...X.normalizeParams(o),entries:s})}});function Fe(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Gi({type:"enum",entries:r,...X.normalizeParams(t)})}var yv=_("ZodLiteral",(e,t)=>{Jd.init(e,t),ce.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function E(e,t){return new yv({type:"literal",values:Array.isArray(e)?e:[e],...X.normalizeParams(t)})}var vv=_("ZodTransform",(e,t)=>{Gd.init(e,t),ce.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(X.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(X.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function _f(e){return new vv({type:"transform",transform:e})}var yf=_("ZodOptional",(e,t)=>{Wd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ge(e){return new yf({type:"optional",innerType:e})}var bv=_("ZodNullable",(e,t)=>{Yd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function af(e){return new bv({type:"nullable",innerType:e})}var wv=_("ZodDefault",(e,t)=>{Qd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $v(e,t){return new wv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Sv=_("ZodPrefault",(e,t)=>{Xd.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function xv(e,t){return new Sv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var vf=_("ZodNonOptional",(e,t)=>{ep.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function kv(e,t){return new vf({type:"nonoptional",innerType:e,...X.normalizeParams(t)})}var zv=_("ZodCatch",(e,t)=>{tp.init(e,t),ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pv(e,t){return new zv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Tv=_("ZodPipe",(e,t)=>{rp.init(e,t),ce.init(e,t),e.in=t.in,e.out=t.out});function Wi(e,t){return new Tv({type:"pipe",in:e,out:t})}var Rv=_("ZodReadonly",(e,t)=>{np.init(e,t),ce.init(e,t)});function Ev(e){return new Rv({type:"readonly",innerType:e})}var bf=_("ZodCustom",(e,t)=>{op.init(e,t),ce.init(e,t)});function Iv(e){let t=new Ie({check:"custom"});return t._zod.check=e,t}function wf(e,t){return Hp(bf,e??(()=>!0),t)}function Ov(e,t={}){return Bp(bf,e,t)}function Av(e){let t=Iv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(X.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(X.issue(o))}},e(r.value,r)));return t}function ea(e,t){return Wi(_f(e),t)}var $f={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Vo={};ai(Vo,{bigint:()=>Mv,boolean:()=>jv,date:()=>Uv,number:()=>Nv,string:()=>Cv});function Cv(e){return cp(Yi,e)}function Nv(e){return Cp(Lo,e)}function jv(e){return Mp(Qi,e)}function Mv(e){return Up(df,e)}function Uv(e){return Fp(mf,e)}Je(sp());var Cr="2025-11-25";var Sf=[Cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mt="io.modelcontextprotocol/related-task",Bo="2.0",Se=wf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),xf=de([f(),Y().int()]),kf=f(),dE=$e({ttl:Y().optional(),pollInterval:Y().optional()}),Zv=P({ttl:Y().optional()}),qv=P({taskId:f()}),ra=$e({progressToken:xf.optional(),[Mt]:qv.optional()}),Ge=P({_meta:ra.optional()}),$n=Ge.extend({task:Zv.optional()}),zf=e=>$n.safeParse(e).success,xe=P({method:f(),params:Ge.loose().optional()}),Xe=P({_meta:ra.optional()}),et=P({method:f(),params:Xe.loose().optional()}),ke=$e({_meta:ra.optional()}),Ko=de([f(),Y().int()]),Pf=P({jsonrpc:E(Bo),id:Ko,...xe.shape}).strict(),Sn=e=>Pf.safeParse(e).success,Tf=P({jsonrpc:E(Bo),...et.shape}).strict(),Rf=e=>Tf.safeParse(e).success,na=P({jsonrpc:E(Bo),id:Ko,result:ke}).strict(),er=e=>na.safeParse(e).success;var U;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var oa=P({jsonrpc:E(Bo),id:Ko.optional(),error:P({code:Y().int(),message:f(),data:he().optional()})}).strict();var Ef=e=>oa.safeParse(e).success;var Nr=de([Pf,Tf,na,oa]),pE=de([na,oa]),tr=ke.strict(),Lv=Xe.extend({requestId:Ko.optional(),reason:f().optional()}),Jo=et.extend({method:E("notifications/cancelled"),params:Lv}),Fv=P({src:f(),mimeType:f().optional(),sizes:z(f()).optional(),theme:Fe(["light","dark"]).optional()}),xn=P({icons:z(Fv).optional()}),Ar=P({name:f(),title:f().optional()}),If=Ar.extend({...Ar.shape,...xn.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),Vv=Fo(P({applyDefaults:oe().optional()}),ue(f(),he())),Hv=ea(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fo(P({form:Vv.optional(),url:Se.optional()}),ue(f(),he()).optional())),Bv=$e({list:Se.optional(),cancel:Se.optional(),requests:$e({sampling:$e({createMessage:Se.optional()}).optional(),elicitation:$e({create:Se.optional()}).optional()}).optional()}),Kv=$e({list:Se.optional(),cancel:Se.optional(),requests:$e({tools:$e({call:Se.optional()}).optional()}).optional()}),Jv=P({experimental:ue(f(),Se).optional(),sampling:P({context:Se.optional(),tools:Se.optional()}).optional(),elicitation:Hv.optional(),roots:P({listChanged:oe().optional()}).optional(),tasks:Bv.optional(),extensions:ue(f(),Se).optional()}),Gv=Ge.extend({protocolVersion:f(),capabilities:Jv,clientInfo:If}),Wv=xe.extend({method:E("initialize"),params:Gv});var Yv=P({experimental:ue(f(),Se).optional(),logging:Se.optional(),completions:Se.optional(),prompts:P({listChanged:oe().optional()}).optional(),resources:P({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:P({listChanged:oe().optional()}).optional(),tasks:Kv.optional(),extensions:ue(f(),Se).optional()}),sa=ke.extend({protocolVersion:f(),capabilities:Yv,serverInfo:If,instructions:f().optional()}),Of=et.extend({method:E("notifications/initialized"),params:Xe.optional()}),Af=e=>Of.safeParse(e).success,Go=xe.extend({method:E("ping"),params:Ge.optional()}),Qv=P({progress:Y(),total:ge(Y()),message:ge(f())}),Xv=P({...Xe.shape,...Qv.shape,progressToken:xf}),Wo=et.extend({method:E("notifications/progress"),params:Xv}),eb=Ge.extend({cursor:kf.optional()}),kn=xe.extend({params:eb.optional()}),zn=ke.extend({nextCursor:kf.optional()}),tb=Fe(["working","input_required","completed","failed","cancelled"]),Pn=P({taskId:f(),status:tb,ttl:de([Y(),pf()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ge(Y()),statusMessage:ge(f())}),rr=ke.extend({task:Pn}),rb=Xe.merge(Pn),Tn=et.extend({method:E("notifications/tasks/status"),params:rb}),Yo=xe.extend({method:E("tasks/get"),params:Ge.extend({taskId:f()})}),Qo=ke.merge(Pn),Xo=xe.extend({method:E("tasks/result"),params:Ge.extend({taskId:f()})}),fE=ke.loose(),es=kn.extend({method:E("tasks/list")}),ts=zn.extend({tasks:z(Pn)}),rs=xe.extend({method:E("tasks/cancel"),params:Ge.extend({taskId:f()})}),Cf=ke.merge(Pn),Nf=P({uri:f(),mimeType:ge(f()),_meta:ue(f(),he()).optional()}),jf=Nf.extend({text:f()}),ia=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mf=Nf.extend({blob:ia}),Rn=Fe(["user","assistant"]),jr=P({audience:z(Rn).optional(),priority:Y().min(0).max(1).optional(),lastModified:bn.datetime({offset:!0}).optional()}),Uf=P({...Ar.shape,...xn.shape,uri:f(),description:ge(f()),mimeType:ge(f()),size:ge(Y()),annotations:jr.optional(),_meta:ge($e({}))}),nb=P({...Ar.shape,...xn.shape,uriTemplate:f(),description:ge(f()),mimeType:ge(f()),annotations:jr.optional(),_meta:ge($e({}))}),ob=kn.extend({method:E("resources/list")}),aa=zn.extend({resources:z(Uf)}),sb=kn.extend({method:E("resources/templates/list")}),ca=zn.extend({resourceTemplates:z(nb)}),ua=Ge.extend({uri:f()}),ib=ua,ab=xe.extend({method:E("resources/read"),params:ib}),la=ke.extend({contents:z(de([jf,Mf]))}),da=et.extend({method:E("notifications/resources/list_changed"),params:Xe.optional()}),cb=ua,ub=xe.extend({method:E("resources/subscribe"),params:cb}),lb=ua,db=xe.extend({method:E("resources/unsubscribe"),params:lb}),pb=Xe.extend({uri:f()}),fb=et.extend({method:E("notifications/resources/updated"),params:pb}),mb=P({name:f(),description:ge(f()),required:ge(oe())}),hb=P({...Ar.shape,...xn.shape,description:ge(f()),arguments:ge(z(mb)),_meta:ge($e({}))}),gb=kn.extend({method:E("prompts/list")}),pa=zn.extend({prompts:z(hb)}),_b=Ge.extend({name:f(),arguments:ue(f(),f()).optional()}),yb=xe.extend({method:E("prompts/get"),params:_b}),fa=P({type:E("text"),text:f(),annotations:jr.optional(),_meta:ue(f(),he()).optional()}),ma=P({type:E("image"),data:ia,mimeType:f(),annotations:jr.optional(),_meta:ue(f(),he()).optional()}),ha=P({type:E("audio"),data:ia,mimeType:f(),annotations:jr.optional(),_meta:ue(f(),he()).optional()}),vb=P({type:E("tool_use"),name:f(),id:f(),input:ue(f(),he()),_meta:ue(f(),he()).optional()}),bb=P({type:E("resource"),resource:de([jf,Mf]),annotations:jr.optional(),_meta:ue(f(),he()).optional()}),wb=Uf.extend({type:E("resource_link")}),ga=de([fa,ma,ha,wb,bb]),$b=P({role:Rn,content:ga}),_a=ke.extend({description:f().optional(),messages:z($b)}),ya=et.extend({method:E("notifications/prompts/list_changed"),params:Xe.optional()}),Sb=P({title:f().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),xb=P({taskSupport:Fe(["required","optional","forbidden"]).optional()}),Df=P({...Ar.shape,...xn.shape,description:f().optional(),inputSchema:P({type:E("object"),properties:ue(f(),Se).optional(),required:z(f()).optional()}).catchall(he()),outputSchema:P({type:E("object"),properties:ue(f(),Se).optional(),required:z(f()).optional()}).catchall(he()).optional(),annotations:Sb.optional(),execution:xb.optional(),_meta:ue(f(),he()).optional()}),kb=kn.extend({method:E("tools/list")}),va=zn.extend({tools:z(Df)}),Mr=ke.extend({content:z(ga).default([]),structuredContent:ue(f(),he()).optional(),isError:oe().optional()}),mE=Mr.or(ke.extend({toolResult:he()})),zb=$n.extend({name:f(),arguments:ue(f(),he()).optional()}),Pb=xe.extend({method:E("tools/call"),params:zb}),ba=et.extend({method:E("notifications/tools/list_changed"),params:Xe.optional()}),Zf=P({autoRefresh:oe().default(!0),debounceMs:Y().int().nonnegative().default(300)}),qf=Fe(["debug","info","notice","warning","error","critical","alert","emergency"]),Tb=Ge.extend({level:qf}),Rb=xe.extend({method:E("logging/setLevel"),params:Tb}),Eb=Xe.extend({level:qf,logger:f().optional(),data:he()}),Ib=et.extend({method:E("notifications/message"),params:Eb}),Ob=P({name:f().optional()}),Ab=P({hints:z(Ob).optional(),costPriority:Y().min(0).max(1).optional(),speedPriority:Y().min(0).max(1).optional(),intelligencePriority:Y().min(0).max(1).optional()}),Cb=P({mode:Fe(["auto","required","none"]).optional()}),Nb=P({type:E("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:z(ga).default([]),structuredContent:P({}).loose().optional(),isError:oe().optional(),_meta:ue(f(),he()).optional()}),jb=Xi("type",[fa,ma,ha]),Ho=Xi("type",[fa,ma,ha,vb,Nb]),Mb=P({role:Rn,content:de([Ho,z(Ho)]),_meta:ue(f(),he()).optional()}),Ub=$n.extend({messages:z(Mb),modelPreferences:Ab.optional(),systemPrompt:f().optional(),includeContext:Fe(["none","thisServer","allServers"]).optional(),temperature:Y().optional(),maxTokens:Y().int(),stopSequences:z(f()).optional(),metadata:Se.optional(),tools:z(Df).optional(),toolChoice:Cb.optional()}),wa=xe.extend({method:E("sampling/createMessage"),params:Ub}),$a=ke.extend({model:f(),stopReason:ge(Fe(["endTurn","stopSequence","maxTokens"]).or(f())),role:Rn,content:jb}),Sa=ke.extend({model:f(),stopReason:ge(Fe(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:Rn,content:de([Ho,z(Ho)])}),Db=P({type:E("boolean"),title:f().optional(),description:f().optional(),default:oe().optional()}),Zb=P({type:E("string"),title:f().optional(),description:f().optional(),minLength:Y().optional(),maxLength:Y().optional(),format:Fe(["email","uri","date","date-time"]).optional(),default:f().optional()}),qb=P({type:Fe(["number","integer"]),title:f().optional(),description:f().optional(),minimum:Y().optional(),maximum:Y().optional(),default:Y().optional()}),Lb=P({type:E("string"),title:f().optional(),description:f().optional(),enum:z(f()),default:f().optional()}),Fb=P({type:E("string"),title:f().optional(),description:f().optional(),oneOf:z(P({const:f(),title:f()})),default:f().optional()}),Vb=P({type:E("string"),title:f().optional(),description:f().optional(),enum:z(f()),enumNames:z(f()).optional(),default:f().optional()}),Hb=de([Lb,Fb]),Bb=P({type:E("array"),title:f().optional(),description:f().optional(),minItems:Y().optional(),maxItems:Y().optional(),items:P({type:E("string"),enum:z(f())}),default:z(f()).optional()}),Kb=P({type:E("array"),title:f().optional(),description:f().optional(),minItems:Y().optional(),maxItems:Y().optional(),items:P({anyOf:z(P({const:f(),title:f()}))}),default:z(f()).optional()}),Jb=de([Bb,Kb]),Gb=de([Vb,Hb,Jb]),Wb=de([Gb,Db,Zb,qb]),Yb=$n.extend({mode:E("form").optional(),message:f(),requestedSchema:P({type:E("object"),properties:ue(f(),Wb),required:z(f()).optional()})}),Qb=$n.extend({mode:E("url"),message:f(),elicitationId:f(),url:f().url()}),Xb=de([Yb,Qb]),xa=xe.extend({method:E("elicitation/create"),params:Xb}),ew=Xe.extend({elicitationId:f()}),tw=et.extend({method:E("notifications/elicitation/complete"),params:ew}),ka=ke.extend({action:Fe(["accept","decline","cancel"]),content:ea(e=>e===null?void 0:e,ue(f(),de([f(),Y(),oe(),z(f())])).optional())}),rw=P({type:E("ref/resource"),uri:f()});var nw=P({type:E("ref/prompt"),name:f()}),ow=Ge.extend({ref:de([nw,rw]),argument:P({name:f(),value:f()}),context:P({arguments:ue(f(),f()).optional()}).optional()}),sw=xe.extend({method:E("completion/complete"),params:ow});var za=ke.extend({completion:$e({values:z(f()).max(100),total:ge(Y().int()),hasMore:ge(oe())})}),iw=P({uri:f().startsWith("file://"),name:f().optional(),_meta:ue(f(),he()).optional()}),aw=xe.extend({method:E("roots/list"),params:Ge.optional()}),cw=ke.extend({roots:z(iw)}),uw=et.extend({method:E("notifications/roots/list_changed"),params:Xe.optional()}),hE=de([Go,Wv,sw,Rb,yb,gb,ob,sb,ab,ub,db,Pb,kb,Yo,Xo,es,rs]),gE=de([Jo,Wo,Of,uw,Tn]),_E=de([tr,$a,Sa,ka,cw,Qo,ts,rr]),yE=de([Go,wa,xa,aw,Yo,Xo,es,rs]),vE=de([Jo,Wo,Ib,fb,da,ba,ya,Tn,tw]),bE=de([tr,sa,za,_a,pa,aa,ca,la,Mr,va,Qo,ts,rr]),j=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===U.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ta(o.elicitations,r)}return new e(t,r,n)}},ta=class extends j{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Ut(e){return e==="completed"||e==="failed"||e==="cancelled"}var lw=Symbol("Let zodToJsonSchema decide on which parser to use");var XE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pa(e){let r=Zo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Kp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ta(e,t){let r=ct(e,t);if(!r.success)throw r.error;return r.data}var gw=6e4,ns=class{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(Jo,r=>{this._oncancel(r)}),this.setNotificationHandler(Wo,r=>{this._onprogress(r)}),this.setRequestHandler(Go,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Xo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new j(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new j(U.InvalidParams,`Task not found: ${s}`);if(!Ut(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ut(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Mt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(es,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new j(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(rs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ut(o.status))throw new j(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new j(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof j?o:new j(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){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),j.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),er(s)||Ef(s)?this._onresponse(s):Sn(s)?this._onrequest(s,i):Rf(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=j.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[Mt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let a=zf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new j(U.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:t.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).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,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),er(t))n(t);else{let i=new j(t.error.code,t.error.message,t.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(er(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),er(t))o(t);else{let i=j.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof j?i:new j(U.InternalError,String(i))}}return}let s;try{let i=await this.request(t,rr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new j(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Ut(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new j(U.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new j(U.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof j?i:new j(U.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch($){d($);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Mt]:c}});let h=$=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String($)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let w=$ instanceof j?$:new j(U.RequestTimeout,String($));l(w)};this._responseHandlers.set(p,$=>{if(!n?.signal?.aborted){if($ instanceof Error)return l($);try{let w=ct(r,$.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??gw,y=()=>h(j.fromError(U.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let $=w=>{let T=this._responseHandlers.get(p);T?T(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,$),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),l(w)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>{this._cleanupTimeout(p),l($)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Qo,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},ts,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Cf,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 a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Mt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,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 a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=Pa(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ta(t,o);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=Pa(t);this._notificationHandlers.set(n,o=>{let s=Ta(t,o);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 o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Sn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new j(U.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 o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new j(U.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new j(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Tn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ut(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new j(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ut(a.status))throw new j(U.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Tn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ut(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Lf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ff(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];Lf(i)&&Lf(s)?r[o]={...i,...s}:r[o]=s}return r}var Cg=nl(mu(),1),Ng=nl(Ag(),1);function bz(){let e=new Cg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ng.default)(e),e}var Us=class{constructor(t){this._ajv=t??bz()}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 Ds=class{constructor(t){this._client=t}async*callToolStream(t,r=Mr,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new j(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof j){yield{type:"error",error:l};return}yield{type:"error",error:new j(U.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}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 jg(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}}function Mg(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}}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 o of Object.keys(n)){let s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Zs(s,r[o])}}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)}}function wz(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}}var io=class extends ns{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 Us,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ba,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ya,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",da,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=Ff(this._capabilities,t)}setRequestHandler(t,r){let o=Zo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Or(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=ct(xa,c);if(!l.success){let $=l.error instanceof Error?l.error.message:String(l.error);throw new j(U.InvalidParams,`Invalid elicitation request: ${$}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:m}=wz(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new j(U.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!m)throw new j(U.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let $=ct(rr,h);if(!$.success){let w=$.error instanceof Error?$.error.message:String($.error);throw new j(U.InvalidParams,`Invalid task creation result: ${w}`)}return $.data}let g=ct(ka,h);if(!g.success){let $=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid elicitation result: ${$}`)}let y=g.data,S=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Zs(S,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=ct(wa,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new j(U.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let y=ct(rr,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new j(U.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=d.tools||d.toolChoice?Sa:$a,g=ct(h,p);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(t,a)}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:Cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},sa,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sf.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){jg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Mg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},tr,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},za,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},tr,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},_a,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},pa,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},aa,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ca,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},la,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},tr,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},tr,r)}async callTool(t,r=Mr,n){if(this.isToolTaskRequired(t.name))throw new j(U.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new j(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof j?i:new j(U.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}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},va,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=Zf.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:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(t,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function qs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Ug(e=fetch,t){return t?async(r,n)=>{let o={...t,...n,headers:n?.headers?{...qs(t.headers),...qs(n.headers)}:t.headers};return e(r,o)}:e}var $u;$u=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function $z(e){return(await $u).getRandomValues(new Uint8Array(e))}async function Sz(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await $z(e-n.length);for(let s of o)s<r&&(n+=t[s%t.length])}return n}async function xz(e){return await Sz(e)}async function kz(e){let t=await(await $u).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Su(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await xz(e),r=await kz(t);return{code_verifier:t,code_challenge:r}}var Re=lf().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:$f.custom,message:"URL must be parseable",fatal:!0}),ci}).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"}),Zg=$e({resource:f().url(),authorization_servers:z(Re).optional(),jwks_uri:f().url().optional(),scopes_supported:z(f()).optional(),bearer_methods_supported:z(f()).optional(),resource_signing_alg_values_supported:z(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:oe().optional(),authorization_details_types_supported:z(f()).optional(),dpop_signing_alg_values_supported:z(f()).optional(),dpop_bound_access_tokens_required:oe().optional()}),xu=$e({issuer:f(),authorization_endpoint:Re,token_endpoint:Re,registration_endpoint:Re.optional(),scopes_supported:z(f()).optional(),response_types_supported:z(f()),response_modes_supported:z(f()).optional(),grant_types_supported:z(f()).optional(),token_endpoint_auth_methods_supported:z(f()).optional(),token_endpoint_auth_signing_alg_values_supported:z(f()).optional(),service_documentation:Re.optional(),revocation_endpoint:Re.optional(),revocation_endpoint_auth_methods_supported:z(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:z(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(f()).optional(),code_challenge_methods_supported:z(f()).optional(),client_id_metadata_document_supported:oe().optional()}),zz=$e({issuer:f(),authorization_endpoint:Re,token_endpoint:Re,userinfo_endpoint:Re.optional(),jwks_uri:Re,registration_endpoint:Re.optional(),scopes_supported:z(f()).optional(),response_types_supported:z(f()),response_modes_supported:z(f()).optional(),grant_types_supported:z(f()).optional(),acr_values_supported:z(f()).optional(),subject_types_supported:z(f()),id_token_signing_alg_values_supported:z(f()),id_token_encryption_alg_values_supported:z(f()).optional(),id_token_encryption_enc_values_supported:z(f()).optional(),userinfo_signing_alg_values_supported:z(f()).optional(),userinfo_encryption_alg_values_supported:z(f()).optional(),userinfo_encryption_enc_values_supported:z(f()).optional(),request_object_signing_alg_values_supported:z(f()).optional(),request_object_encryption_alg_values_supported:z(f()).optional(),request_object_encryption_enc_values_supported:z(f()).optional(),token_endpoint_auth_methods_supported:z(f()).optional(),token_endpoint_auth_signing_alg_values_supported:z(f()).optional(),display_values_supported:z(f()).optional(),claim_types_supported:z(f()).optional(),claims_supported:z(f()).optional(),service_documentation:f().optional(),claims_locales_supported:z(f()).optional(),ui_locales_supported:z(f()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Re.optional(),op_tos_uri:Re.optional(),client_id_metadata_document_supported:oe().optional()}),qg=P({...zz.shape,...xu.pick({code_challenge_methods_supported:!0}).shape}),Lg=P({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Vo.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Fg=P({error:f(),error_description:f().optional(),error_uri:f().optional()}),Dg=Re.optional().or(E("").transform(()=>{})),Pz=P({redirect_uris:z(Re),token_endpoint_auth_method:f().optional(),grant_types:z(f()).optional(),response_types:z(f()).optional(),client_name:f().optional(),client_uri:Re.optional(),logo_uri:Dg,scope:f().optional(),contacts:z(f()).optional(),tos_uri:Dg,policy_uri:f().optional(),jwks_uri:Re.optional(),jwks:ff().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Tz=P({client_id:f(),client_secret:f().optional(),client_id_issued_at:Y().optional(),client_secret_expires_at:Y().optional()}).strip(),Vg=Pz.merge(Tz),k1=P({error:f(),error_description:f().optional()}).strip(),z1=P({token:f(),token_type_hint:f().optional()}).strip();function Hg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Bg({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 o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var ve=class extends Error{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}},ao=class extends ve{};ao.errorCode="invalid_request";var mr=class extends ve{};mr.errorCode="invalid_client";var hr=class extends ve{};hr.errorCode="invalid_grant";var gr=class extends ve{};gr.errorCode="unauthorized_client";var co=class extends ve{};co.errorCode="unsupported_grant_type";var uo=class extends ve{};uo.errorCode="invalid_scope";var lo=class extends ve{};lo.errorCode="access_denied";var At=class extends ve{};At.errorCode="server_error";var po=class extends ve{};po.errorCode="temporarily_unavailable";var fo=class extends ve{};fo.errorCode="unsupported_response_type";var mo=class extends ve{};mo.errorCode="unsupported_token_type";var ho=class extends ve{};ho.errorCode="invalid_token";var go=class extends ve{};go.errorCode="method_not_allowed";var _o=class extends ve{};_o.errorCode="too_many_requests";var _r=class extends ve{};_r.errorCode="invalid_client_metadata";var yo=class extends ve{};yo.errorCode="insufficient_scope";var vo=class extends ve{};vo.errorCode="invalid_target";var Kg={[ao.errorCode]:ao,[mr.errorCode]:mr,[hr.errorCode]:hr,[gr.errorCode]:gr,[co.errorCode]:co,[uo.errorCode]:uo,[lo.errorCode]:lo,[At.errorCode]:At,[po.errorCode]:po,[fo.errorCode]:fo,[mo.errorCode]:mo,[ho.errorCode]:ho,[go.errorCode]:go,[_o.errorCode]:_o,[_r.errorCode]:_r,[yo.errorCode]:yo,[vo.errorCode]:vo};var Ct=class extends Error{constructor(t){super(t??"Unauthorized")}};function Rz(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var ku="code",zu="S256";function Ez(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Rz(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"}function Iz(e,t,r,n){let{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":Oz(o,s,r);return;case"client_secret_post":Az(o,s,n);return;case"none":Cz(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Oz(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}`)}function Az(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function Cz(e,t){t.set("client_id",e)}async function Gg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Fg.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Kg[o]||At;return new a(s||"",i)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new At(o)}}async function bo(e,t){try{return await Pu(e,t)}catch(r){if(r instanceof mr||r instanceof gr)return await e.invalidateCredentials?.("all"),await Pu(e,t);if(r instanceof hr)return await e.invalidateCredentials?.("tokens"),await Pu(e,t);throw r}}async function Pu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await e.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await Yg(c,{fetchFn:s}),!a)try{a=await Wg(t,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let w=await qz(t,{resourceMetadataUrl:l,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await jz(t,e,a),p=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,m=await Promise.resolve(e.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,T=e.clientMetadataUrl;if(T&&!Nz(T))throw new _r(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${T}`);if(w&&T)m={client_id:T},await e.saveClientInformation?.(m);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let k=await Bz(c,{metadata:u,clientMetadata:e.clientMetadata,scope:p,fetchFn:s});await e.saveClientInformation(k),m=k}}let h=!e.redirectUrl;if(r!==void 0||h){let w=await Hz(e,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}let g=await e.tokens();if(g?.refresh_token)try{let w=await Vz(c,{metadata:u,clientInformation:m,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof ve)||w instanceof At))throw w}let y=e.state?await e.state():void 0,{authorizationUrl:S,codeVerifier:$}=await Lz(c,{metadata:u,clientInformation:m,state:y,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier($),await e.redirectToAuthorization(S),"REDIRECT"}function Nz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function jz(e,t,r){let n=Hg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Bg({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ru(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Tu(e,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Tu(e,"scope")||void 0,a=Tu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Tu(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function Wg(e,t,r=fetch){let n=await Dz(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 Zg.parse(await n.json())}async function Eu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Eu(e,void 0,r):void 0;throw n}}function Mz(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Jg(e,t,r=fetch){return await Eu(e,{"MCP-Protocol-Version":t},r)}function Uz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Dz(e,t,r,n){let o=new URL(e),s=n?.protocolVersion??Cr,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=Mz(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Jg(i,s,r);if(!n?.metadataUrl&&Uz(a,o.pathname)){let c=new URL(`/.well-known/${t}`,o);a=await Jg(c,s,r)}return a}function Zz(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 o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function Yg(e,{fetchFn:t=fetch,protocolVersion:r=Cr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Zz(e);for(let{url:s,type:i}of o){let a=await Eu(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?xu.parse(await a.json()):qg.parse(await a.json())}}}async function qz(e,t){let r,n;try{r=await Wg(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 o=await Yg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Lz(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ku))throw new Error(`Incompatible auth server: does not support response type ${ku}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(zu))throw new Error(`Incompatible auth server: does not support code challenge method ${zu}`)}else a=new URL("/authorize",e);let c=await Su(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",ku),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",zu),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function Fz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Qg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){let a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,a,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],d=Ez(n,l);Iz(d,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await Gg(u);return Lg.parse(await u.json())}async function Vz(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Qg(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function Hz(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=e.clientMetadata.scope,a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await e.codeVerifier();a=Fz(o,u,e.redirectUrl)}let c=await e.clientInformation();return Qg(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Bz(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){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(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await Gg(i);return Vg.parse(await i.json())}var wo=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},Xg=10,Kz=13,yr=32;function Iu(e){}function r_(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Iu,onError:r=Iu,onRetry:n=Iu,onComment:o,maxBufferSize:s}=e,i=[],a=0,c=!0,u,l="",d=0,p,m=!1;function h(v){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){let W=y(v);W!==""&&(i.push(W),a=W.length),g();return}if(v.indexOf(`
36
+ `)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let k=i.join("");i.length=0,a=0;let A=y(k);A!==""&&(i.push(A),a=A.length),g()}function g(){s!==void 0&&(a+l.length<=s||(m=!0,i.length=0,a=0,u=void 0,l="",d=0,p=void 0,r(new wo(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let k=0;if(v.indexOf("\r")===-1){let A=v.indexOf(`
37
37
  `,k);for(;A!==-1;){if(k===A){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0,k=A+1,A=v.indexOf(`
38
- `,k);continue}let W=v.charCodeAt(k);if(e_(v,k,W)){let ie=v.charCodeAt(k+5)===_r?k+6:k+5,be=v.slice(ie,A);if(d===0&&v.charCodeAt(A+1)===Xg){t({id:u,event:p,data:be}),u=void 0,l="",p=void 0,k=A+2,A=v.indexOf(`
38
+ `,k);continue}let W=v.charCodeAt(k);if(e_(v,k,W)){let ie=v.charCodeAt(k+5)===yr?k+6:k+5,be=v.slice(ie,A);if(d===0&&v.charCodeAt(A+1)===Xg){t({id:u,event:p,data:be}),u=void 0,l="",p=void 0,k=A+2,A=v.indexOf(`
39
39
  `,k);continue}l=d===0?be:`${l}
40
- ${be}`,d++}else t_(v,k,W)?p=v.slice(v.charCodeAt(k+6)===_r?k+7:k+6,A)||void 0:S(v,k,A);k=A+1,A=v.indexOf(`
40
+ ${be}`,d++}else t_(v,k,W)?p=v.slice(v.charCodeAt(k+6)===yr?k+7:k+6,A)||void 0:S(v,k,A);k=A+1,A=v.indexOf(`
41
41
  `,k)}return v.slice(k)}for(;k<v.length;){let A=v.indexOf("\r",k),W=v.indexOf(`
42
- `,k),ie=-1;if(A!==-1&&W!==-1?ie=A<W?A:W:A!==-1?A===v.length-1?ie=-1:ie=A:W!==-1&&(ie=W),ie===-1)break;S(v,k,ie),k=ie+1,v.charCodeAt(k-1)===Kz&&v.charCodeAt(k)===Xg&&k++}return v.slice(k)}function S(v,k,A){if(k===A){w();return}let W=v.charCodeAt(k);if(e_(v,k,W)){let Qe=v.charCodeAt(k+5)===_r?k+6:k+5,ko=v.slice(Qe,A);l=d===0?ko:`${l}
43
- ${ko}`,d++;return}if(t_(v,k,W)){p=v.slice(v.charCodeAt(k+6)===_r?k+7:k+6,A)||void 0;return}if(W===105&&v.charCodeAt(k+1)===100&&v.charCodeAt(k+2)===58){let Qe=v.slice(v.charCodeAt(k+3)===_r?k+4:k+3,A);u=Qe.includes("\0")?void 0:Qe;return}if(W===58){if(o){let Qe=v.slice(k,A);o(Qe.slice(v.charCodeAt(k+1)===_r?2:1))}return}let ie=v.slice(k,A),be=ie.indexOf(":");if(be===-1){$(ie,"",ie);return}let qe=ie.slice(0,be),je=ie.charCodeAt(be+1)===_r?2:1,St=ie.slice(be+je);$(qe,St,ie)}function $(v,k,A){switch(v){case"event":p=k||void 0;break;case"data":l=d===0?k:`${l}
44
- ${k}`,d++;break;case"id":u=k.includes("\0")?void 0:k;break;case"retry":/^\d+$/.test(k)?n(parseInt(k,10)):r(new vo(`Invalid \`retry\` value: "${k}"`,{type:"invalid-retry",value:k,line:A}));break;default:r(new vo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:k,line:A}));break}}function w(){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function P(v={}){if(v.consume&&i.length>0){let k=i.join("");S(k,0,k.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,m=!1}return{feed:h,reset:P}}function e_(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function t_(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Ls=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=r_({onEvent:a=>{i.enqueue(a)},onError(a){typeof t=="function"&&t(a),(t==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var Jz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Bt=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},tn=class{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=Ug(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Jz}async _authThenStart(){if(!this._authProvider)throw new At("No auth provider");let t;try{t=await yo(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 At;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=qs(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 o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Bt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ls({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:h}=await l.read();if(h)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let g=Cr.parse(JSON.parse(m.data));Xt(g)&&(c=!0,s!==void 0&&(g.id=s)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 At("No auth provider");if(await yo(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new At("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:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:$n(t)?t.id:void 0}).catch(p=>this.onerror?.(p));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},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Bt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:h}=Ru(a);if(this._resourceMetadataUrl=m,this._scope=h,await yo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new At;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:h,error:g}=Ru(a);if(g==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Bt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await yo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new At;return this.send(t)}}throw new Bt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Af(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let l=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,d=a.headers.get("content-type");if(l)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){let p=await a.json(),m=Array.isArray(p)?p.map(h=>Cr.parse(h)):[Cr.parse(p)];for(let h of m)this.onmessage?.(h)}else throw await a.body?.cancel(),new Bt(-1,`Unexpected content type: ${d}`);else await a.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 Bt(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})}};import*as Ne from"node:fs";import{randomBytes as Gz}from"node:crypto";import{homedir as o_}from"node:os";import{resolve as Vs,join as Ou,dirname as Au,basename as Wz}from"node:path";var bo=["owner","shared","open"],rn={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:Vs(o_(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function wo(){return process.env.OURS_CONFIG??Ou(o_(),".ours","config.json")}function Yz(){let e;try{e=Ne.readFileSync(wo(),"utf8")}catch{return{}}let t;try{t=JSON.parse(e)}catch{return{}}let r={};if(typeof t.brokerUrl=="string"&&(r.brokerUrl=t.brokerUrl),typeof t.port=="number"&&Number.isFinite(t.port)&&(r.port=t.port),typeof t.stateDir=="string"&&(r.stateDir=Vs(t.stateDir)),typeof t.gcIntervalMs=="number"&&Number.isFinite(t.gcIntervalMs)&&(r.gcIntervalMs=t.gcIntervalMs),typeof t.autoStart=="boolean"&&(r.autoStart=t.autoStart),typeof t.apiVisibility=="string"&&bo.includes(t.apiVisibility)&&(r.apiVisibility=t.apiVisibility),typeof t.apiToken=="string"&&t.apiToken.trim()&&(r.apiToken=t.apiToken.trim()),t.stt&&typeof t.stt=="object"){let n=t.stt,o={};typeof n.provider=="string"&&(o.provider=n.provider),typeof n.apiKey=="string"&&(o.apiKey=n.apiKey),typeof n.model=="string"&&(o.model=n.model),typeof n.baseUrl=="string"&&(o.baseUrl=n.baseUrl),typeof n.language=="string"&&(o.language=n.language),typeof n.maxBytes=="number"&&Number.isFinite(n.maxBytes)&&(o.maxBytes=n.maxBytes),typeof n.timeoutMs=="number"&&Number.isFinite(n.timeoutMs)&&(o.timeoutMs=n.timeoutMs),n.custom&&typeof n.custom=="object"&&(o.custom=n.custom),r.stt=o}return r}function Qz(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&bo.includes(e)?e:void 0}function Xz(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function n_(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function Cu(){let e=Yz();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??rn.brokerUrl,port:n_("OURS_PORT")??e.port??rn.port,stateDir:Vs(process.env.OURS_STATE_DIR??e.stateDir??rn.stateDir),gcIntervalMs:n_("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??rn.gcIntervalMs,autoStart:Xz("OURS_AUTOSTART")??e.autoStart??rn.autoStart,apiVisibility:Qz()??e.apiVisibility??rn.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||e.apiToken,stt:eT(e.stt)}}function eT(e){let t={};process.env.OURS_STT_PROVIDER?.trim()&&(t.provider=process.env.OURS_STT_PROVIDER.trim()),process.env.OURS_STT_API_KEY?.trim()&&(t.apiKey=process.env.OURS_STT_API_KEY.trim()),process.env.OURS_STT_MODEL?.trim()&&(t.model=process.env.OURS_STT_MODEL.trim()),process.env.OURS_STT_BASE_URL?.trim()&&(t.baseUrl=process.env.OURS_STT_BASE_URL.trim()),process.env.OURS_STT_LANGUAGE?.trim()&&(t.language=process.env.OURS_STT_LANGUAGE.trim());let r={...e??{},...t};return Object.keys(r).length?r:void 0}var tT="daemon-token";function rT(e){return Ou(e.stateDir,tT)}function Nu(e,t={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let n=e.apiToken?.trim();if(n)return{token:n,source:"config"};let o=rT(e);try{let i=Ne.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let s=Gz(32).toString("hex");try{Ne.mkdirSync(Au(o),{recursive:!0}),Ne.writeFileSync(o,s+`
45
- `,{mode:384}),Ne.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}function s_(e){let t=wo();Ne.mkdirSync(Au(t),{recursive:!0}),Ne.writeFileSync(t,JSON.stringify(e,null,2)+`
42
+ `,k),ie=-1;if(A!==-1&&W!==-1?ie=A<W?A:W:A!==-1?A===v.length-1?ie=-1:ie=A:W!==-1&&(ie=W),ie===-1)break;S(v,k,ie),k=ie+1,v.charCodeAt(k-1)===Kz&&v.charCodeAt(k)===Xg&&k++}return v.slice(k)}function S(v,k,A){if(k===A){w();return}let W=v.charCodeAt(k);if(e_(v,k,W)){let Qe=v.charCodeAt(k+5)===yr?k+6:k+5,zo=v.slice(Qe,A);l=d===0?zo:`${l}
43
+ ${zo}`,d++;return}if(t_(v,k,W)){p=v.slice(v.charCodeAt(k+6)===yr?k+7:k+6,A)||void 0;return}if(W===105&&v.charCodeAt(k+1)===100&&v.charCodeAt(k+2)===58){let Qe=v.slice(v.charCodeAt(k+3)===yr?k+4:k+3,A);u=Qe.includes("\0")?void 0:Qe;return}if(W===58){if(o){let Qe=v.slice(k,A);o(Qe.slice(v.charCodeAt(k+1)===yr?2:1))}return}let ie=v.slice(k,A),be=ie.indexOf(":");if(be===-1){$(ie,"",ie);return}let qe=ie.slice(0,be),Me=ie.charCodeAt(be+1)===yr?2:1,xt=ie.slice(be+Me);$(qe,xt,ie)}function $(v,k,A){switch(v){case"event":p=k||void 0;break;case"data":l=d===0?k:`${l}
44
+ ${k}`,d++;break;case"id":u=k.includes("\0")?void 0:k;break;case"retry":/^\d+$/.test(k)?n(parseInt(k,10)):r(new wo(`Invalid \`retry\` value: "${k}"`,{type:"invalid-retry",value:k,line:A}));break;default:r(new wo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:k,line:A}));break}}function w(){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function T(v={}){if(v.consume&&i.length>0){let k=i.join("");S(k,0,k.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,m=!1}return{feed:h,reset:T}}function e_(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function t_(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Ls=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=r_({onEvent:a=>{i.enqueue(a)},onError(a){typeof t=="function"&&t(a),(t==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var Jz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Kt=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},vr=class{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=Ug(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Jz}async _authThenStart(){if(!this._authProvider)throw new Ct("No auth provider");let t;try{t=await bo(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 Ct;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=qs(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 o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Kt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ls({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:h}=await l.read();if(h)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let g=Nr.parse(JSON.parse(m.data));er(g)&&(c=!0,s!==void 0&&(g.id=s)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 Ct("No auth provider");if(await bo(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ct("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:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Sn(t)?t.id:void 0}).catch(p=>this.onerror?.(p));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},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Kt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:h}=Ru(a);if(this._resourceMetadataUrl=m,this._scope=h,await bo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ct;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:h,error:g}=Ru(a);if(g==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Kt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await bo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ct;return this.send(t)}}throw new Kt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Af(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let l=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,d=a.headers.get("content-type");if(l)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){let p=await a.json(),m=Array.isArray(p)?p.map(h=>Nr.parse(h)):[Nr.parse(p)];for(let h of m)this.onmessage?.(h)}else throw await a.body?.cancel(),new Kt(-1,`Unexpected content type: ${d}`);else await a.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 Kt(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})}};import*as Ne from"node:fs";import{randomBytes as Gz}from"node:crypto";import{homedir as o_}from"node:os";import{resolve as Vs,join as Ou,dirname as Au,basename as Wz}from"node:path";var $o=["owner","shared","open"],rn={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:Vs(o_(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function So(){return process.env.OURS_CONFIG??Ou(o_(),".ours","config.json")}function Yz(){let e;try{e=Ne.readFileSync(So(),"utf8")}catch{return{}}let t;try{t=JSON.parse(e)}catch{return{}}let r={};if(typeof t.brokerUrl=="string"&&(r.brokerUrl=t.brokerUrl),typeof t.port=="number"&&Number.isFinite(t.port)&&(r.port=t.port),typeof t.stateDir=="string"&&(r.stateDir=Vs(t.stateDir)),typeof t.gcIntervalMs=="number"&&Number.isFinite(t.gcIntervalMs)&&(r.gcIntervalMs=t.gcIntervalMs),typeof t.autoStart=="boolean"&&(r.autoStart=t.autoStart),typeof t.apiVisibility=="string"&&$o.includes(t.apiVisibility)&&(r.apiVisibility=t.apiVisibility),typeof t.apiToken=="string"&&t.apiToken.trim()&&(r.apiToken=t.apiToken.trim()),t.stt&&typeof t.stt=="object"){let n=t.stt,o={};typeof n.provider=="string"&&(o.provider=n.provider),typeof n.apiKey=="string"&&(o.apiKey=n.apiKey),typeof n.model=="string"&&(o.model=n.model),typeof n.baseUrl=="string"&&(o.baseUrl=n.baseUrl),typeof n.language=="string"&&(o.language=n.language),typeof n.maxBytes=="number"&&Number.isFinite(n.maxBytes)&&(o.maxBytes=n.maxBytes),typeof n.timeoutMs=="number"&&Number.isFinite(n.timeoutMs)&&(o.timeoutMs=n.timeoutMs),n.custom&&typeof n.custom=="object"&&(o.custom=n.custom),r.stt=o}return r}function Qz(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&$o.includes(e)?e:void 0}function Xz(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function n_(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function Cu(){let e=Yz();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??rn.brokerUrl,port:n_("OURS_PORT")??e.port??rn.port,stateDir:Vs(process.env.OURS_STATE_DIR??e.stateDir??rn.stateDir),gcIntervalMs:n_("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??rn.gcIntervalMs,autoStart:Xz("OURS_AUTOSTART")??e.autoStart??rn.autoStart,apiVisibility:Qz()??e.apiVisibility??rn.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||e.apiToken,stt:eP(e.stt)}}function eP(e){let t={};process.env.OURS_STT_PROVIDER?.trim()&&(t.provider=process.env.OURS_STT_PROVIDER.trim()),process.env.OURS_STT_API_KEY?.trim()&&(t.apiKey=process.env.OURS_STT_API_KEY.trim()),process.env.OURS_STT_MODEL?.trim()&&(t.model=process.env.OURS_STT_MODEL.trim()),process.env.OURS_STT_BASE_URL?.trim()&&(t.baseUrl=process.env.OURS_STT_BASE_URL.trim()),process.env.OURS_STT_LANGUAGE?.trim()&&(t.language=process.env.OURS_STT_LANGUAGE.trim());let r={...e??{},...t};return Object.keys(r).length?r:void 0}var tP="daemon-token";function rP(e){return Ou(e.stateDir,tP)}function Nu(e,t={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let n=e.apiToken?.trim();if(n)return{token:n,source:"config"};let o=rP(e);try{let i=Ne.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let s=Gz(32).toString("hex");try{Ne.mkdirSync(Au(o),{recursive:!0}),Ne.writeFileSync(o,s+`
45
+ `,{mode:384}),Ne.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}function s_(e){let t=So();Ne.mkdirSync(Au(t),{recursive:!0}),Ne.writeFileSync(t,JSON.stringify(e,null,2)+`
46
46
  `,{mode:384});try{Ne.chmodSync(t,384)}catch{}return t}var Fs=".ours-identity";function Hs(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function ju(e){let t=Vs(e);return Wz(t)===Fs?t:Ou(t,Fs)}function i_(e,t,r=!1){let n=Hs(t),o=ju(e);if(!r&&Ne.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Ne.mkdirSync(Au(o),{recursive:!0}),Ne.writeFileSync(o,JSON.stringify(n,null,2)+`
47
47
  `),o}import c_ from"node:process";var Bs=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
48
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),nT(r)}clear(){this._buffer=void 0}};function nT(e){return Cr.parse(JSON.parse(e))}function a_(e){return JSON.stringify(e)+`
49
- `}var Ks=class{constructor(t=c_.stdin,r=c_.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Bs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=a_(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function u_(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as l_,writeFileSync as oT,readFileSync as sT,readdirSync as iT,statSync as Mu,unlinkSync as aT,chmodSync as d_,createWriteStream as cT,accessSync as uT,constants as lT}from"node:fs";import{join as Js,dirname as dT,resolve as pT}from"node:path";import{homedir as fT}from"node:os";import{Readable as mT}from"node:stream";import{pipeline as hT}from"node:stream/promises";var gT="0.17.1",_T=new Set(["choose_identity","create_identity","create_root_identity"]),yT="save_file",vT="get_files",bT=["1","true","yes","on"].includes((process.env.OURS_FILES_ALWAYS_PROMPT??"").trim().toLowerCase()),wT=e=>{try{return uT(e,lT.R_OK),!0}catch{return!1}},$T=e=>` \u2022 ${e.filename} \u2014 ${e.mime||"application/octet-stream"}, ${e.size} B, sha256 ${e.sha256} \u2014 from ${e.sender} \u2014 wire_id ${e.wire_id}`;function ST(e,t){let r=e;if(!r||r.isError)return!1;let n=r.structuredContent?.files;if(!Array.isArray(n))return!1;let o=n.filter(a=>!!a&&typeof a=="object"&&typeof a.path=="string"&&typeof a.wire_id=="string");if(o.length===0)return!1;let s=o.filter(a=>a.kind!=="voice_message"&&!t(a.path));for(let a of o)a.readable=t(a.path);if(s.length===0)return!1;let i=[`${s.length} of ${o.length} received file(s) are NOT readable by your OS user: the ours daemon runs as a different OS user and keeps its files dir private. Nothing was lost \u2014 the bytes are safely on disk. IGNORE the on-disk paths reported below for these files; you cannot open them.`,"","TELL THE USER what arrived (details below) and ASK WHERE TO SAVE each file on this filesystem. Then call save_file({ wire_id, dest_path }) with the path they choose: the ours connector streams the bytes daemon\u2192proxy\u2192disk and writes them as YOUR OS user. The bytes never enter this conversation.","","Awaiting a destination:",...s.map($T)];return r.content=[{type:"text",text:i.join(`
50
- `)},...r.content??[]],!0}var p_=e=>new Promise(t=>setTimeout(t,e)),Uu=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,xT=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,f_=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},m_=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,h_=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase()),Du=(process.env.OURS_BIND_IDENTITY??"").trim()||null;async function g_(e){let t=new URL(e.url),r=!1,n=(...x)=>{if(!r)try{process.stderr.write(`[ours-proxy] ${x.join(" ")}
51
- `)}catch{r=!0,xt(0)}},o=()=>{r=!0,xt(0)};process.stderr.on("error",o),process.stdout.on("error",o);let s=x=>Number.isInteger(x)&&x>1,i=Number(process.env.OURS_CLIENT_PID),a=s(i)?i:s(process.ppid)?process.ppid:process.pid,c=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${a}`,u=null,l=null,d,p=null,m=new Map,h=new Set,g=null,y=h_?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,S=e.stateDir??process.env.OURS_STATE_DIR??Js(fT(),".ours"),$=Js(S,"session-restore"),w=y&&/^[A-Za-z0-9._-]{1,200}$/.test(y)?y:null,P=w?Js($,`${w}.json`):null,v=!1,k=null,A="session-restore";function W(x){if(P)try{l_($,{recursive:!0,mode:448}),oT(P,JSON.stringify({claudeSessionId:y,identity:x,boundAt:new Date().toISOString()}),{mode:384}),d_($,448),d_(P,384)}catch(I){n("restore persist failed (non-fatal):",String(I))}}function ie(){if(!P)return null;try{if(Date.now()-Mu(P).mtimeMs>m_)return null;let x=JSON.parse(sT(P,"utf8"));return(typeof x.identity=="string"?x.identity.trim():"")||null}catch{return null}}function be(){try{let x=Date.now();for(let I of iT($)){if(!I.endsWith(".json"))continue;let N=Js($,I);try{x-Mu(N).mtimeMs>m_&&(aT(N),n("session-restore: pruned expired record",I))}catch{}}}catch{}}let qe=(()=>{let x=(process.env.OURS_REQUEST_TIMEOUT_MS??"").trim();if(x==="")return 12e4;let I=Number(x);return Number.isFinite(I)&&I>=0?I:12e4})(),je=new Map,St=new Map;function Qe(x,I,N){let B=je.get(x);if(!B)return;je.delete(x),B.progressToken!==void 0&&St.delete(B.progressToken);let M=Date.now()-B.sentAt;n(`FAILING BACK request id=${String(x)} method=${B.method} waited_ms=${M} reason=${N}`),mt.send({jsonrpc:"2.0",id:x,error:{code:I,message:`ours proxy: no response from the ours daemon for "${B.method}" after ${M}ms (${N}). The request was NOT retried \u2014 retry it yourself if it is safe to repeat.`,data:{reason:N,method:B.method,waitedMs:M}}}).catch(Z=>n("fail-back send failed:",String(Z)))}qe>0&&setInterval(()=>{let I=Date.now();for(let[N,B]of[...je])B.deadline<=I&&Qe(N,-32001,"watchdog timeout")},1e3).unref?.();let ko=6e4,Wu=3,ri=0,$r=0;function G_(x,I){mt.send({jsonrpc:"2.0",method:"notifications/message",params:{level:x,logger:"ours-proxy",data:I}}).catch(N=>n("downstream notify failed:",String(N)))}let Le=null,W_=()=>Le,zo=!1,cn=!1,Sr=!1,un=[],Y_="__ours_proxy_init__",ni=0,ln=new Set,oi=new Set,mt=new Ks;mt.onmessage=x=>{let I=[],N=!1;for(let B of Gs(x)){let M=B;if(M.method==="notifications/initialized"&&(N=!0),Uu(M)){if(M.method==="initialize"&&(u=M,l)){n("absorbed re-initialize locally \u2014 upstream session kept stable"),mt.send({jsonrpc:"2.0",id:M.id,result:l}).catch(Z=>n("local initialize reply failed:",String(Z)));continue}if(M.method==="tools/call"){let Z=M.params;if(Z&&_T.has(Z.name??"")&&typeof Z.arguments?.name=="string"&&m.set(M.id,Z.arguments.name),Z?.name===vT&&h.add(M.id),Z?.name===yT){let _e=M.params?.arguments??{};ey(M.id,_e);continue}}if(qe>0){let Z=M.id,_e=M.params?._meta,we=Date.now();je.set(Z,{method:typeof M.method=="string"?M.method:"unknown",sentAt:we,deadline:we+qe,transport:null,progressToken:_e?.progressToken}),_e?.progressToken!==void 0&&St.set(_e.progressToken,Z)}}I.push(M)}if(I.length){let B=Array.isArray(x)?I:I[0];Qu(B)}N&&Q_()},mt.onclose=()=>void xt(0),mt.onerror=x=>n("downstream error:",String(x));let Yu=x=>{n(`stdin ${x} \u2014 the client is gone; shutting down`),xt(0)};process.stdin.once("end",()=>Yu("reached EOF")),process.stdin.once("close",()=>Yu("closed"));function Q_(){if(v||!p)return;v=!0;let x=`__ours_proxy_restore_${++ni}__`;ln.add(x),k=x,n(`${A}: binding seeded identity`,`"${p}"`),Qu({jsonrpc:"2.0",id:x,method:"tools/call",params:{name:"choose_identity",arguments:{name:p}}})}function X_(x,I){if(!(qe<=0))for(let N of Gs(x)){let B=N.id;if(B===void 0)continue;let M=je.get(B);M&&(M.transport=I)}}async function ey(x,I){let N=String(I.wire_id??"").trim(),B=String(I.dest_path??"").trim(),M=(Z,_e=!1)=>mt.send({jsonrpc:"2.0",id:x,result:{content:[{type:"text",text:Z}],isError:_e}}).catch(we=>n("save_file reply failed:",String(we)));if(!N||!B){await M("save_file: both `wire_id` and `dest_path` are required.",!0);return}if(!/^[A-Za-z0-9]+$/.test(N)){await M("save_file: invalid wire_id.",!0);return}try{let Z=new URL(t.href);Z.pathname=`/files/${encodeURIComponent(N)}`,Z.search="";let _e={"x-ours-lease-token":c};e.apiToken&&(_e["x-ours-api-token"]=e.apiToken);let we=await fetch(Z,{headers:_e});if(we.status===401||we.status===403){await M("save_file: ours daemon authentication failed; the monitor may be disarmed.",!0);return}if(we.status===404){await M(`save_file: no file with wire_id ${N} is available to the bound identity. Run get_files first; it may already be saved, or it belongs to another identity.`,!0);return}if(!we.ok||!we.body){await M(`save_file: ours daemon returned HTTP ${we.status}. Your ours daemon may be too old to support save_file \u2014 update it, or use get_files and copy the returned path yourself.`,!0);return}let Me=pT(B);l_(dT(Me),{recursive:!0}),await hT(mT.fromWeb(we.body),cT(Me));let sy=Mu(Me).size;await M(`Saved file (wire_id ${N}) to ${Me} (${sy} bytes). The bytes were streamed daemon\u2192proxy\u2192disk and never entered this result.`)}catch(Z){await M(`save_file failed: ${String(Z)}`,!0)}}function Qu(x){if(zo&&Le){let I=Le;X_(x,I),Le.send(x).catch(N=>{n("upstream send failed:",String(N));let B=Gs(x),M=B.filter(Z=>!Uu(Z));M.length&&un.push(Array.isArray(x)?M:M[0]);for(let Z of B){let _e=Z;Uu(_e)&&je.has(_e.id)&&Qe(_e.id,-32e3,"upstream send failed")}si(I,"send failed")})}else un.push(x)}function si(x,I){if(cn||Sr||Le!==null&&x!==Le)return;n(`upstream dropped (${I}) \u2014 reconnecting`),zo=!1;let N=Le;Le=null;try{N?.close?.()}catch{}if(N)for(let[B,M]of[...je])M.transport===N&&Qe(B,-32e3,`upstream dropped (${I})`);ny()}function ty(x){x.onmessage=I=>{let N=[];for(let B of Gs(I)){let M=B;if(M.method==="notifications/progress"){let Z=M.params?.progressToken;if(Z!==void 0){let _e=St.get(Z),we=_e!==void 0?je.get(_e):void 0;we&&(we.deadline=Date.now()+qe)}}if(xT(M)){let Z=M.id,_e=je.get(Z);_e&&(je.delete(Z),_e.progressToken!==void 0&&St.delete(_e.progressToken));let we=M.result?.protocolVersion;if(we&&(oi.has(Z)||Xu(Z))){d=we;try{Le?.setProtocolVersion?.(we)}catch{}if(l==null&&Xu(Z)&&!ln.has(Z)){let Me=M.result??null;Me&&g&&(Me.instructions=`${Me.instructions?Me.instructions+`
48
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),nP(r)}clear(){this._buffer=void 0}};function nP(e){return Nr.parse(JSON.parse(e))}function a_(e){return JSON.stringify(e)+`
49
+ `}var Ks=class{constructor(t=c_.stdin,r=c_.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Bs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=a_(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function u_(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as l_,writeFileSync as oP,readFileSync as sP,readdirSync as iP,statSync as Mu,unlinkSync as aP,chmodSync as d_,createWriteStream as cP,accessSync as uP,constants as lP}from"node:fs";import{join as Js,dirname as dP,resolve as pP}from"node:path";import{homedir as fP}from"node:os";import{Readable as mP}from"node:stream";import{pipeline as hP}from"node:stream/promises";var gP="0.17.2",_P=new Set(["choose_identity","create_identity","create_root_identity","create_temporary_identity"]),yP="save_file",vP="get_files",bP=["1","true","yes","on"].includes((process.env.OURS_FILES_ALWAYS_PROMPT??"").trim().toLowerCase()),wP=e=>{try{return uP(e,lP.R_OK),!0}catch{return!1}},$P=e=>` \u2022 ${e.filename} \u2014 ${e.mime||"application/octet-stream"}, ${e.size} B, sha256 ${e.sha256} \u2014 from ${e.sender} \u2014 wire_id ${e.wire_id}`;function SP(e,t){let r=e;if(!r||r.isError)return!1;let n=r.structuredContent?.files;if(!Array.isArray(n))return!1;let o=n.filter(a=>!!a&&typeof a=="object"&&typeof a.path=="string"&&typeof a.wire_id=="string");if(o.length===0)return!1;let s=o.filter(a=>a.kind!=="voice_message"&&!t(a.path));for(let a of o)a.readable=t(a.path);if(s.length===0)return!1;let i=[`${s.length} of ${o.length} received file(s) are NOT readable by your OS user: the ours daemon runs as a different OS user and keeps its files dir private. Nothing was lost \u2014 the bytes are safely on disk. IGNORE the on-disk paths reported below for these files; you cannot open them.`,"","TELL THE USER what arrived (details below) and ASK WHERE TO SAVE each file on this filesystem. Then call save_file({ wire_id, dest_path }) with the path they choose: the ours connector streams the bytes daemon\u2192proxy\u2192disk and writes them as YOUR OS user. The bytes never enter this conversation.","","Awaiting a destination:",...s.map($P)];return r.content=[{type:"text",text:i.join(`
50
+ `)},...r.content??[]],!0}var p_=e=>new Promise(t=>setTimeout(t,e)),Uu=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,xP=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,f_=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},m_=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,h_=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase()),Du=(process.env.OURS_BIND_IDENTITY??"").trim()||null;async function g_(e){let t=new URL(e.url),r=!1,n=(...x)=>{if(!r)try{process.stderr.write(`[ours-proxy] ${x.join(" ")}
51
+ `)}catch{r=!0,kt(0)}},o=()=>{r=!0,kt(0)};process.stderr.on("error",o),process.stdout.on("error",o);let s=x=>Number.isInteger(x)&&x>1,i=Number(process.env.OURS_CLIENT_PID),a=s(i)?i:s(process.ppid)?process.ppid:process.pid,c=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${a}`,u=null,l=null,d,p=null,m=new Map,h=new Set,g=null,y=h_?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,S=e.stateDir??process.env.OURS_STATE_DIR??Js(fP(),".ours"),$=Js(S,"session-restore"),w=y&&/^[A-Za-z0-9._-]{1,200}$/.test(y)?y:null,T=w?Js($,`${w}.json`):null,v=!1,k=null,A="session-restore";function W(x){if(T)try{l_($,{recursive:!0,mode:448}),oP(T,JSON.stringify({claudeSessionId:y,identity:x,boundAt:new Date().toISOString()}),{mode:384}),d_($,448),d_(T,384)}catch(I){n("restore persist failed (non-fatal):",String(I))}}function ie(){if(!T)return null;try{if(Date.now()-Mu(T).mtimeMs>m_)return null;let x=JSON.parse(sP(T,"utf8"));return(typeof x.identity=="string"?x.identity.trim():"")||null}catch{return null}}function be(){try{let x=Date.now();for(let I of iP($)){if(!I.endsWith(".json"))continue;let N=Js($,I);try{x-Mu(N).mtimeMs>m_&&(aP(N),n("session-restore: pruned expired record",I))}catch{}}}catch{}}let qe=(()=>{let x=(process.env.OURS_REQUEST_TIMEOUT_MS??"").trim();if(x==="")return 12e4;let I=Number(x);return Number.isFinite(I)&&I>=0?I:12e4})(),Me=new Map,xt=new Map;function Qe(x,I,N){let B=Me.get(x);if(!B)return;Me.delete(x),B.progressToken!==void 0&&xt.delete(B.progressToken);let M=Date.now()-B.sentAt;n(`FAILING BACK request id=${String(x)} method=${B.method} waited_ms=${M} reason=${N}`),mt.send({jsonrpc:"2.0",id:x,error:{code:I,message:`ours proxy: no response from the ours daemon for "${B.method}" after ${M}ms (${N}). The request was NOT retried \u2014 retry it yourself if it is safe to repeat.`,data:{reason:N,method:B.method,waitedMs:M}}}).catch(Z=>n("fail-back send failed:",String(Z)))}qe>0&&setInterval(()=>{let I=Date.now();for(let[N,B]of[...Me])B.deadline<=I&&Qe(N,-32001,"watchdog timeout")},1e3).unref?.();let zo=6e4,Wu=3,ri=0,Sr=0;function G_(x,I){mt.send({jsonrpc:"2.0",method:"notifications/message",params:{level:x,logger:"ours-proxy",data:I}}).catch(N=>n("downstream notify failed:",String(N)))}let Le=null,W_=()=>Le,Po=!1,un=!1,xr=!1,ln=[],Y_="__ours_proxy_init__",ni=0,dn=new Set,oi=new Set,mt=new Ks;mt.onmessage=x=>{let I=[],N=!1;for(let B of Gs(x)){let M=B;if(M.method==="notifications/initialized"&&(N=!0),Uu(M)){if(M.method==="initialize"&&(u=M,l)){n("absorbed re-initialize locally \u2014 upstream session kept stable"),mt.send({jsonrpc:"2.0",id:M.id,result:l}).catch(Z=>n("local initialize reply failed:",String(Z)));continue}if(M.method==="tools/call"){let Z=M.params;if(Z&&_P.has(Z.name??"")&&typeof Z.arguments?.name=="string"&&m.set(M.id,Z.arguments.name),Z?.name===vP&&h.add(M.id),Z?.name===yP){let _e=M.params?.arguments??{};ey(M.id,_e);continue}}if(qe>0){let Z=M.id,_e=M.params?._meta,we=Date.now();Me.set(Z,{method:typeof M.method=="string"?M.method:"unknown",sentAt:we,deadline:we+qe,transport:null,progressToken:_e?.progressToken}),_e?.progressToken!==void 0&&xt.set(_e.progressToken,Z)}}I.push(M)}if(I.length){let B=Array.isArray(x)?I:I[0];Qu(B)}N&&Q_()},mt.onclose=()=>void kt(0),mt.onerror=x=>n("downstream error:",String(x));let Yu=x=>{n(`stdin ${x} \u2014 the client is gone; shutting down`),kt(0)};process.stdin.once("end",()=>Yu("reached EOF")),process.stdin.once("close",()=>Yu("closed"));function Q_(){if(v||!p)return;v=!0;let x=`__ours_proxy_restore_${++ni}__`;dn.add(x),k=x,n(`${A}: binding seeded identity`,`"${p}"`),Qu({jsonrpc:"2.0",id:x,method:"tools/call",params:{name:"choose_identity",arguments:{name:p}}})}function X_(x,I){if(!(qe<=0))for(let N of Gs(x)){let B=N.id;if(B===void 0)continue;let M=Me.get(B);M&&(M.transport=I)}}async function ey(x,I){let N=String(I.wire_id??"").trim(),B=String(I.dest_path??"").trim(),M=(Z,_e=!1)=>mt.send({jsonrpc:"2.0",id:x,result:{content:[{type:"text",text:Z}],isError:_e}}).catch(we=>n("save_file reply failed:",String(we)));if(!N||!B){await M("save_file: both `wire_id` and `dest_path` are required.",!0);return}if(!/^[A-Za-z0-9]+$/.test(N)){await M("save_file: invalid wire_id.",!0);return}try{let Z=new URL(t.href);Z.pathname=`/files/${encodeURIComponent(N)}`,Z.search="";let _e={"x-ours-lease-token":c};e.apiToken&&(_e["x-ours-api-token"]=e.apiToken);let we=await fetch(Z,{headers:_e});if(we.status===401||we.status===403){await M("save_file: ours daemon authentication failed; the monitor may be disarmed.",!0);return}if(we.status===404){await M(`save_file: no file with wire_id ${N} is available to the bound identity. Run get_files first; it may already be saved, or it belongs to another identity.`,!0);return}if(!we.ok||!we.body){await M(`save_file: ours daemon returned HTTP ${we.status}. Your ours daemon may be too old to support save_file \u2014 update it, or use get_files and copy the returned path yourself.`,!0);return}let Ue=pP(B);l_(dP(Ue),{recursive:!0}),await hP(mP.fromWeb(we.body),cP(Ue));let sy=Mu(Ue).size;await M(`Saved file (wire_id ${N}) to ${Ue} (${sy} bytes). The bytes were streamed daemon\u2192proxy\u2192disk and never entered this result.`)}catch(Z){await M(`save_file failed: ${String(Z)}`,!0)}}function Qu(x){if(Po&&Le){let I=Le;X_(x,I),Le.send(x).catch(N=>{n("upstream send failed:",String(N));let B=Gs(x),M=B.filter(Z=>!Uu(Z));M.length&&ln.push(Array.isArray(x)?M:M[0]);for(let Z of B){let _e=Z;Uu(_e)&&Me.has(_e.id)&&Qe(_e.id,-32e3,"upstream send failed")}si(I,"send failed")})}else ln.push(x)}function si(x,I){if(un||xr||Le!==null&&x!==Le)return;n(`upstream dropped (${I}) \u2014 reconnecting`),Po=!1;let N=Le;Le=null;try{N?.close?.()}catch{}if(N)for(let[B,M]of[...Me])M.transport===N&&Qe(B,-32e3,`upstream dropped (${I})`);ny()}function ty(x){x.onmessage=I=>{let N=[];for(let B of Gs(I)){let M=B;if(M.method==="notifications/progress"){let Z=M.params?.progressToken;if(Z!==void 0){let _e=xt.get(Z),we=_e!==void 0?Me.get(_e):void 0;we&&(we.deadline=Date.now()+qe)}}if(xP(M)){let Z=M.id,_e=Me.get(Z);_e&&(Me.delete(Z),_e.progressToken!==void 0&&xt.delete(_e.progressToken));let we=M.result?.protocolVersion;if(we&&(oi.has(Z)||Xu(Z))){d=we;try{Le?.setProtocolVersion?.(we)}catch{}if(l==null&&Xu(Z)&&!dn.has(Z)){let Ue=M.result??null;Ue&&g&&(Ue.instructions=`${Ue.instructions?Ue.instructions+`
52
52
 
53
- `:""}${g}`),l=Me}oi.delete(Z)}if(ln.has(Z)){ln.delete(Z),Z===k&&(k=null,f_(M)&&(p=null,n(`${A}: bind refused (identity live elsewhere, or no such identity) \u2014 this session starts UNBOUND;`,"create the identity, or bind one with choose_identity")));continue}if(h.has(Z)&&(h.delete(Z),ST(M.result,bT?()=>!1:wT)&&n("get_files: daemon copy unreadable by this OS user \u2014 asked the agent for a destination")),m.has(Z)){let Me=m.get(Z);m.delete(Z),f_(M)||(p=Me,n("bound identity tracked:",Me),W(Me))}}N.push(M)}if(N.length){let B=Array.isArray(I)?N:N[0];mt.send(B).catch(M=>n("downstream send failed:",String(M)))}},x.onerror=I=>{let N=String(I);if(n("upstream error:",N),!/Maximum reconnection attempts \(\d+\) exceeded/.test(N))return;let B=Date.now();if(B-ri<ko){n(`notification stream exhausted again within cooldown \u2014 not escalating (${Math.round((B-ri)/1e3)}s since last)`);return}if(ri=B,$r++,$r>Wu){n(`NOTIFICATION STREAM DEAD \u2014 ${$r-1} reconnect escalations exhausted; server\u2192client notifications are NOT arriving`),G_("error",`ours proxy: the server\u2192client notification stream could not be re-established after ${$r-1} attempts. Tool calls still work, but you will NOT receive new-mail or other server notifications until this session reconnects. Treat any "waiting for a message" as unreliable.`);return}n(`notification stream exhausted its retries \u2014 escalating to a full reconnect (${$r}/${Wu})`),si(x,"notification stream exhausted")},x.onclose=()=>si(x,"closed")}let Xu=x=>u!=null&&u.id===x;async function el(){e.ensureDaemon&&await e.ensureDaemon().catch(I=>n("ensureDaemon:",String(I)));let x=new tn(t,{reconnectionOptions:{initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:5},requestInit:{headers:{"x-ours-lease-token":c,"x-ours-client-pid":String(a),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(ty(x),await x.start(),d)try{x.setProtocolVersion?.(d)}catch{}Le=x}async function tl(x,I){I&&x.id!==void 0&&ln.add(x.id),await Le.send(x)}let ry=()=>{if(a===process.pid)return!0;try{return process.kill(a,0),!0}catch(x){return x.code!=="ESRCH"}};async function ny(){if(Sr||cn)return;Sr=!0;let x=500;for(;;){if(cn){Sr=!1;return}if(!ry()){n(`client pid ${a} is gone \u2014 abandoning reconnect instead of churning the daemon's sessions`),Sr=!1,xt(0);return}try{if(await el(),u){let N=`${Y_}${ni}`;oi.add(N),await tl({...u,id:N},!0),await Le.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(p){let N=`__ours_proxy_rebind_${++ni}__`;await tl({jsonrpc:"2.0",id:N,method:"tools/call",params:{name:"choose_identity",arguments:{name:p}}},!0)}zo=!0;let I=un.splice(0);for(let N of I)await Le.send(N).catch(B=>n("flush failed:",String(B)));n("upstream reconnected",p?`(re-bound "${p}")`:""),$r=0,Sr=!1;return}catch(I){n("reconnect attempt failed:",String(I)),await p_(x),x=Math.min(Math.floor(x*1.5),1e4)}}}async function xt(x){if(!cn){cn=!0;try{await Le?.close()}catch{}try{await mt.close()}catch{}process.exit(x)}}process.on("SIGINT",()=>void xt(0)),process.on("SIGTERM",()=>void xt(0));let rl=x=>{let I=x?.code;return I==="EPIPE"||I==="ECONNRESET"||I==="ERR_STREAM_DESTROYED"||I==="ERR_STREAM_WRITE_AFTER_END"};process.on("unhandledRejection",x=>{if(rl(x)){r=!0,xt(0);return}n("UNHANDLED REJECTION (proxy stays up):",x instanceof Error?x.stack??x.message:String(x))}),process.on("uncaughtException",x=>{if(rl(x)){r=!0,xt(0);return}n("UNCAUGHT EXCEPTION (proxy stays up):",x?.stack??String(x))});async function oy(){let x=new URL(t.href);x.pathname="/state-dir";let I;try{I=await(await fetch(x,{signal:AbortSignal.timeout(3e3)})).json()}catch(N){n("compat handshake: could not read daemon /state-dir, proceeding:",String(N));return}g=u_({selfVersion:gT,daemonVersion:typeof I?.version=="string"?I.version:null}),g&&n(g)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(N=>n("ensureDaemon:",String(N))),await oy();let x=500;for(;;)try{await el();break}catch(N){n("initial upstream connect failed, retrying:",String(N)),await p_(x),x=Math.min(Math.floor(x*1.5),1e4)}zo=!0;let I=un.splice(0);for(let N=0;N<I.length;N++){let B=W_();if(!B){un.unshift(...I.slice(N));break}await B.send(I[N]).catch(M=>n("flush failed:",String(M)))}n(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),y){be();let x=ie();x&&(p=x,n("session-restore: found prior binding for this session \u2014 will self-recover",`"${x}"`))}else h_&&n("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");!p&&Du&&(p=Du,A="OURS_BIND_IDENTITY",n("OURS_BIND_IDENTITY: supervisor named this session's identity \u2014 will bind",`"${Du}"`)),await mt.start(),n("proxy started (stdio transport up)")}function Gs(e){return Array.isArray(e)?e:[e]}var Zu=["openai-compatible","elevenlabs","deepgram","custom"],uN=5*1024*1024;function $o(e){let t="configure it in config.json `stt: {}` or via OURS_STT_* env";if(!e?.provider)return{ready:!1,reason:`no STT provider configured (stt.provider: ${Zu.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!Zu.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${Zu.join(" | ")})`};if(!e.apiKey?.trim())return{ready:!1,reason:`STT provider "${r}" is set but the API key is missing (stt.apiKey / OURS_STT_API_KEY)`};if(r==="openai-compatible"){if(!e.baseUrl?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.baseUrl / OURS_STT_BASE_URL (e.g. your provider's /v1 root) \u2014 no endpoint is assumed"};if(!e.model?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.model / OURS_STT_MODEL (passed to the provider verbatim) \u2014 no model is assumed"}}if(r==="elevenlabs"&&!e.model?.trim())return{ready:!1,reason:"elevenlabs STT needs stt.model / OURS_STT_MODEL (the model_id, e.g. from your ElevenLabs account) \u2014 no model is assumed"};if(r==="custom"){if(!e.custom?.url?.trim())return{ready:!1,reason:"custom STT needs stt.custom.url (the full endpoint URL of your provider)"};if((e.custom.url.includes("{model}")||e.custom.modelField!==void 0&&e.custom.modelField!=="")&&!e.model?.trim())return{ready:!1,reason:"the custom STT template references a model (url {model} or modelField) but stt.model / OURS_STT_MODEL is not set"}}return{ready:!0,provider:r}}function kT(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trimStart();return/^[A-Za-z](?:\s|$)/.test(r)?r[0]:null}function __(e){let t=kT(e);return t==="Z"||t==="X"||t==="x"}import{chmodSync as y_,closeSync as zT,existsSync as w_,mkdirSync as TT,openSync as v_,readFileSync as $_,readSync as S_,renameSync as PT,statSync as RT,unlinkSync as x_,writeFileSync as ET,writeSync as IT}from"node:fs";import{spawnSync as Ws}from"node:child_process";import{dirname as OT}from"node:path";var We=[{value:"openai-compatible",label:"OpenAI-compatible",detail:"an OpenAI-style /v1 transcription endpoint"},{value:"elevenlabs",label:"ElevenLabs",detail:"ElevenLabs speech-to-text"},{value:"deepgram",label:"Deepgram",detail:"Deepgram speech-to-text"},{value:"custom",label:"Custom HTTP endpoint",detail:"a fully specified transcription URL"}],Ee=class extends Error{constructor(r){super(r);this.reason=r}};function AT(e){if(!w_(e))return{};let t=JSON.parse($_(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("config root must be a JSON object");return t}function CT(e){return w_(e)?{exists:!0,text:$_(e,"utf8"),mode:RT(e).mode&511}:{exists:!1}}function NT(e,t){k_(e,`${JSON.stringify(t,null,2)}
54
- `,384)}function k_(e,t,r){TT(OT(e),{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${Date.now()}`;try{ET(n,t,{encoding:"utf8",mode:r,flag:"wx"}),y_(n,r),PT(n,e),y_(e,r)}catch(o){try{x_(n)}catch{}throw o}}function jT(e,t){if(!t.exists){try{x_(e)}catch{}return}k_(e,t.text,t.mode)}async function MT(e,t,r,n){let o=CT(e);try{NT(e,t)}catch{return{ok:!1,stage:"write",rolledBack:!0,daemonRestored:!0}}if(r!=="managed")return{ok:!0,stage:"write"};let s;try{s=n?await n():{ok:!1}}catch{s={ok:!1}}if(s.ok)return{ok:!0,stage:"apply"};try{jT(e,o)}catch{return{ok:!1,stage:"rollback",rolledBack:!1,daemonRestored:!1}}let i;try{i=n?await n():{ok:!1}}catch{i={ok:!1}}return{ok:!1,stage:i.ok?"apply":"rollback",rolledBack:!0,daemonRestored:i.ok}}function b_(e,t){let r={...e},n=[["provider",t.OURS_STT_PROVIDER],["apiKey",t.OURS_STT_API_KEY],["model",t.OURS_STT_MODEL],["baseUrl",t.OURS_STT_BASE_URL],["language",t.OURS_STT_LANGUAGE]];for(let[o,s]of n)s?.trim()&&(r[o]=s.trim());return r}function UT(e){let t=e.trim();return t.length<8?{ok:!1,reason:"API key must contain at least 8 characters"}:/[\s\x00-\x1f\x7f]/.test(t)?{ok:!1,reason:"API key must not contain whitespace or control characters"}:{ok:!0,value:t}}function DT(){try{return v_("/dev/tty","r+")}catch{if(process.stdin.isTTY&&process.stdout.isTTY)try{return v_("/dev/stdin","r+")}catch{}return null}}function Ye(e,t){IT(e,t)}function qu(e){let t=Buffer.alloc(1);try{return S_(e,t,0,1,null)===1?t[0]:null}catch(r){throw r.code==="EINTR"?new Ee("cancel"):r}}function z_(e){let t="";for(let r=0;r<12;r++){let n=qu(e);if(n===null)break;let o=String.fromCharCode(n);if(t+=o,/[A-Za-z~]$/.test(t))break}return t}function T_(e,t){let r=Ws("stty",["-g"],{stdio:[e,"pipe","ignore"],encoding:"utf8"}),n=(r.stdout||"").trim();if(r.status!==0||!n)throw new Ee("unavailable");if(Ws("stty",["-icanon","-echo","-isig","min","1","time","0"],{stdio:[e,"ignore","ignore"]}).status!==0)throw new Ee("unavailable");let s=!1,i=()=>{if(s)return;s=!0,Ws("stty",[n],{stdio:[e,"ignore","ignore"]}).status!==0&&Ws("stty",["sane"],{stdio:[e,"ignore","ignore"]})};process.once("exit",i);try{return t()}finally{process.removeListener("exit",i),i()}}function ZT(e,t,r,n){return T_(e,()=>{Ye(e,t);let o="";for(;;){let i=qu(e);if(i===null||i===4)throw new Ee("eof");if(i===3)throw new Ee("cancel");if(i===10||i===13){Ye(e,`
55
- `);break}if(i===127||i===8){o.length&&(o=o.slice(0,-1),n||Ye(e,"\b \b"));continue}if(i===27){z_(e);continue}if(i<32||o.length>=16384)continue;let a=String.fromCharCode(i);o+=a,n||Ye(e,a)}let s=o.trim();return s===""?r:s})}function Ys(e,t,r=""){Ye(e,t);let n=[],o=0;for(;;){let i=Buffer.alloc(1024),a;try{a=S_(e,i,0,i.length,null)}catch(l){throw l.code==="EINTR"?new Ee("cancel"):l}if(a===0)throw new Ee("eof");let c=i.subarray(0,a).indexOf(10),u=c>=0?i.subarray(0,c):i.subarray(0,a);if(n.push(u),o+=u.length,o>16384)throw new Error("prompt input too long");if(c>=0)break}let s=Buffer.concat(n).toString("utf8").replace(/\r$/,"").trim();return s===""?r:s}function wt(e,t,r="",n=!1){try{return ZT(e,t,r,n)}catch(o){if(o instanceof Ee&&o.reason==="unavailable"&&!n)return Ys(e,t,r);throw o}}function qT(e,t,r){let n=wt(e,`${t} ${r?"[Y/n]":"[y/N]"} `,r?"y":"n");return/^y(?:es)?$/i.test(n)}function LT(e,t){let r=We.findIndex(n=>n.value===t);r<0&&(r=0);try{return T_(e,()=>{Ye(e,`Choose one transcription provider (\u2191/\u2193 or j/k, then Enter; q cancels):
53
+ `:""}${g}`),l=Ue}oi.delete(Z)}if(dn.has(Z)){dn.delete(Z),Z===k&&(k=null,f_(M)&&(p=null,n(`${A}: bind refused (identity live elsewhere, or no such identity) \u2014 this session starts UNBOUND;`,"create the identity, or bind one with choose_identity")));continue}if(h.has(Z)&&(h.delete(Z),SP(M.result,bP?()=>!1:wP)&&n("get_files: daemon copy unreadable by this OS user \u2014 asked the agent for a destination")),m.has(Z)){let Ue=m.get(Z);m.delete(Z),f_(M)||(p=Ue,n("bound identity tracked:",Ue),W(Ue))}}N.push(M)}if(N.length){let B=Array.isArray(I)?N:N[0];mt.send(B).catch(M=>n("downstream send failed:",String(M)))}},x.onerror=I=>{let N=String(I);if(n("upstream error:",N),!/Maximum reconnection attempts \(\d+\) exceeded/.test(N))return;let B=Date.now();if(B-ri<zo){n(`notification stream exhausted again within cooldown \u2014 not escalating (${Math.round((B-ri)/1e3)}s since last)`);return}if(ri=B,Sr++,Sr>Wu){n(`NOTIFICATION STREAM DEAD \u2014 ${Sr-1} reconnect escalations exhausted; server\u2192client notifications are NOT arriving`),G_("error",`ours proxy: the server\u2192client notification stream could not be re-established after ${Sr-1} attempts. Tool calls still work, but you will NOT receive new-mail or other server notifications until this session reconnects. Treat any "waiting for a message" as unreliable.`);return}n(`notification stream exhausted its retries \u2014 escalating to a full reconnect (${Sr}/${Wu})`),si(x,"notification stream exhausted")},x.onclose=()=>si(x,"closed")}let Xu=x=>u!=null&&u.id===x;async function el(){e.ensureDaemon&&await e.ensureDaemon().catch(I=>n("ensureDaemon:",String(I)));let x=new vr(t,{reconnectionOptions:{initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:5},requestInit:{headers:{"x-ours-lease-token":c,"x-ours-client-pid":String(a),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(ty(x),await x.start(),d)try{x.setProtocolVersion?.(d)}catch{}Le=x}async function tl(x,I){I&&x.id!==void 0&&dn.add(x.id),await Le.send(x)}let ry=()=>{if(a===process.pid)return!0;try{return process.kill(a,0),!0}catch(x){return x.code!=="ESRCH"}};async function ny(){if(xr||un)return;xr=!0;let x=500;for(;;){if(un){xr=!1;return}if(!ry()){n(`client pid ${a} is gone \u2014 abandoning reconnect instead of churning the daemon's sessions`),xr=!1,kt(0);return}try{if(await el(),u){let N=`${Y_}${ni}`;oi.add(N),await tl({...u,id:N},!0),await Le.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(p){let N=`__ours_proxy_rebind_${++ni}__`;await tl({jsonrpc:"2.0",id:N,method:"tools/call",params:{name:"choose_identity",arguments:{name:p}}},!0)}Po=!0;let I=ln.splice(0);for(let N of I)await Le.send(N).catch(B=>n("flush failed:",String(B)));n("upstream reconnected",p?`(re-bound "${p}")`:""),Sr=0,xr=!1;return}catch(I){n("reconnect attempt failed:",String(I)),await p_(x),x=Math.min(Math.floor(x*1.5),1e4)}}}async function kt(x){if(!un){un=!0;try{await Le?.close()}catch{}try{await mt.close()}catch{}process.exit(x)}}process.on("SIGINT",()=>void kt(0)),process.on("SIGTERM",()=>void kt(0));let rl=x=>{let I=x?.code;return I==="EPIPE"||I==="ECONNRESET"||I==="ERR_STREAM_DESTROYED"||I==="ERR_STREAM_WRITE_AFTER_END"};process.on("unhandledRejection",x=>{if(rl(x)){r=!0,kt(0);return}n("UNHANDLED REJECTION (proxy stays up):",x instanceof Error?x.stack??x.message:String(x))}),process.on("uncaughtException",x=>{if(rl(x)){r=!0,kt(0);return}n("UNCAUGHT EXCEPTION (proxy stays up):",x?.stack??String(x))});async function oy(){let x=new URL(t.href);x.pathname="/state-dir";let I;try{I=await(await fetch(x,{signal:AbortSignal.timeout(3e3)})).json()}catch(N){n("compat handshake: could not read daemon /state-dir, proceeding:",String(N));return}g=u_({selfVersion:gP,daemonVersion:typeof I?.version=="string"?I.version:null}),g&&n(g)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(N=>n("ensureDaemon:",String(N))),await oy();let x=500;for(;;)try{await el();break}catch(N){n("initial upstream connect failed, retrying:",String(N)),await p_(x),x=Math.min(Math.floor(x*1.5),1e4)}Po=!0;let I=ln.splice(0);for(let N=0;N<I.length;N++){let B=W_();if(!B){ln.unshift(...I.slice(N));break}await B.send(I[N]).catch(M=>n("flush failed:",String(M)))}n(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),y){be();let x=ie();x&&(p=x,n("session-restore: found prior binding for this session \u2014 will self-recover",`"${x}"`))}else h_&&n("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");!p&&Du&&(p=Du,A="OURS_BIND_IDENTITY",n("OURS_BIND_IDENTITY: supervisor named this session's identity \u2014 will bind",`"${Du}"`)),await mt.start(),n("proxy started (stdio transport up)")}function Gs(e){return Array.isArray(e)?e:[e]}var Zu=["openai-compatible","elevenlabs","deepgram","custom"],lN=5*1024*1024;function xo(e){let t="configure it in config.json `stt: {}` or via OURS_STT_* env";if(!e?.provider)return{ready:!1,reason:`no STT provider configured (stt.provider: ${Zu.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!Zu.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${Zu.join(" | ")})`};if(!e.apiKey?.trim())return{ready:!1,reason:`STT provider "${r}" is set but the API key is missing (stt.apiKey / OURS_STT_API_KEY)`};if(r==="openai-compatible"){if(!e.baseUrl?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.baseUrl / OURS_STT_BASE_URL (e.g. your provider's /v1 root) \u2014 no endpoint is assumed"};if(!e.model?.trim())return{ready:!1,reason:"openai-compatible STT needs stt.model / OURS_STT_MODEL (passed to the provider verbatim) \u2014 no model is assumed"}}if(r==="elevenlabs"&&!e.model?.trim())return{ready:!1,reason:"elevenlabs STT needs stt.model / OURS_STT_MODEL (the model_id, e.g. from your ElevenLabs account) \u2014 no model is assumed"};if(r==="custom"){if(!e.custom?.url?.trim())return{ready:!1,reason:"custom STT needs stt.custom.url (the full endpoint URL of your provider)"};if((e.custom.url.includes("{model}")||e.custom.modelField!==void 0&&e.custom.modelField!=="")&&!e.model?.trim())return{ready:!1,reason:"the custom STT template references a model (url {model} or modelField) but stt.model / OURS_STT_MODEL is not set"}}return{ready:!0,provider:r}}function kP(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trimStart();return/^[A-Za-z](?:\s|$)/.test(r)?r[0]:null}function __(e){let t=kP(e);return t==="Z"||t==="X"||t==="x"}import{chmodSync as y_,closeSync as zP,existsSync as w_,mkdirSync as PP,openSync as v_,readFileSync as $_,readSync as S_,renameSync as TP,statSync as RP,unlinkSync as x_,writeFileSync as EP,writeSync as IP}from"node:fs";import{spawnSync as Ws}from"node:child_process";import{dirname as OP}from"node:path";var We=[{value:"openai-compatible",label:"OpenAI-compatible",detail:"an OpenAI-style /v1 transcription endpoint"},{value:"elevenlabs",label:"ElevenLabs",detail:"ElevenLabs speech-to-text"},{value:"deepgram",label:"Deepgram",detail:"Deepgram speech-to-text"},{value:"custom",label:"Custom HTTP endpoint",detail:"a fully specified transcription URL"}],Ee=class extends Error{constructor(r){super(r);this.reason=r}};function AP(e){if(!w_(e))return{};let t=JSON.parse($_(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("config root must be a JSON object");return t}function CP(e){return w_(e)?{exists:!0,text:$_(e,"utf8"),mode:RP(e).mode&511}:{exists:!1}}function NP(e,t){k_(e,`${JSON.stringify(t,null,2)}
54
+ `,384)}function k_(e,t,r){PP(OP(e),{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${Date.now()}`;try{EP(n,t,{encoding:"utf8",mode:r,flag:"wx"}),y_(n,r),TP(n,e),y_(e,r)}catch(o){try{x_(n)}catch{}throw o}}function jP(e,t){if(!t.exists){try{x_(e)}catch{}return}k_(e,t.text,t.mode)}async function MP(e,t,r,n){let o=CP(e);try{NP(e,t)}catch{return{ok:!1,stage:"write",rolledBack:!0,daemonRestored:!0}}if(r!=="managed")return{ok:!0,stage:"write"};let s;try{s=n?await n():{ok:!1}}catch{s={ok:!1}}if(s.ok)return{ok:!0,stage:"apply"};try{jP(e,o)}catch{return{ok:!1,stage:"rollback",rolledBack:!1,daemonRestored:!1}}let i;try{i=n?await n():{ok:!1}}catch{i={ok:!1}}return{ok:!1,stage:i.ok?"apply":"rollback",rolledBack:!0,daemonRestored:i.ok}}function b_(e,t){let r={...e},n=[["provider",t.OURS_STT_PROVIDER],["apiKey",t.OURS_STT_API_KEY],["model",t.OURS_STT_MODEL],["baseUrl",t.OURS_STT_BASE_URL],["language",t.OURS_STT_LANGUAGE]];for(let[o,s]of n)s?.trim()&&(r[o]=s.trim());return r}function UP(e){let t=e.trim();return t.length<8?{ok:!1,reason:"API key must contain at least 8 characters"}:/[\s\x00-\x1f\x7f]/.test(t)?{ok:!1,reason:"API key must not contain whitespace or control characters"}:{ok:!0,value:t}}function DP(){try{return v_("/dev/tty","r+")}catch{if(process.stdin.isTTY&&process.stdout.isTTY)try{return v_("/dev/stdin","r+")}catch{}return null}}function Ye(e,t){IP(e,t)}function qu(e){let t=Buffer.alloc(1);try{return S_(e,t,0,1,null)===1?t[0]:null}catch(r){throw r.code==="EINTR"?new Ee("cancel"):r}}function z_(e){let t="";for(let r=0;r<12;r++){let n=qu(e);if(n===null)break;let o=String.fromCharCode(n);if(t+=o,/[A-Za-z~]$/.test(t))break}return t}function P_(e,t){let r=Ws("stty",["-g"],{stdio:[e,"pipe","ignore"],encoding:"utf8"}),n=(r.stdout||"").trim();if(r.status!==0||!n)throw new Ee("unavailable");if(Ws("stty",["-icanon","-echo","-isig","min","1","time","0"],{stdio:[e,"ignore","ignore"]}).status!==0)throw new Ee("unavailable");let s=!1,i=()=>{if(s)return;s=!0,Ws("stty",[n],{stdio:[e,"ignore","ignore"]}).status!==0&&Ws("stty",["sane"],{stdio:[e,"ignore","ignore"]})};process.once("exit",i);try{return t()}finally{process.removeListener("exit",i),i()}}function ZP(e,t,r,n){return P_(e,()=>{Ye(e,t);let o="";for(;;){let i=qu(e);if(i===null||i===4)throw new Ee("eof");if(i===3)throw new Ee("cancel");if(i===10||i===13){Ye(e,`
55
+ `);break}if(i===127||i===8){o.length&&(o=o.slice(0,-1),n||Ye(e,"\b \b"));continue}if(i===27){z_(e);continue}if(i<32||o.length>=16384)continue;let a=String.fromCharCode(i);o+=a,n||Ye(e,a)}let s=o.trim();return s===""?r:s})}function Ys(e,t,r=""){Ye(e,t);let n=[],o=0;for(;;){let i=Buffer.alloc(1024),a;try{a=S_(e,i,0,i.length,null)}catch(l){throw l.code==="EINTR"?new Ee("cancel"):l}if(a===0)throw new Ee("eof");let c=i.subarray(0,a).indexOf(10),u=c>=0?i.subarray(0,c):i.subarray(0,a);if(n.push(u),o+=u.length,o>16384)throw new Error("prompt input too long");if(c>=0)break}let s=Buffer.concat(n).toString("utf8").replace(/\r$/,"").trim();return s===""?r:s}function wt(e,t,r="",n=!1){try{return ZP(e,t,r,n)}catch(o){if(o instanceof Ee&&o.reason==="unavailable"&&!n)return Ys(e,t,r);throw o}}function qP(e,t,r){let n=wt(e,`${t} ${r?"[Y/n]":"[y/N]"} `,r?"y":"n");return/^y(?:es)?$/i.test(n)}function LP(e,t){let r=We.findIndex(n=>n.value===t);r<0&&(r=0);try{return P_(e,()=>{Ye(e,`Choose one transcription provider (\u2191/\u2193 or j/k, then Enter; q cancels):
56
56
  `);let n=!1,o=()=>{n&&Ye(e,`\x1B[${We.length}A`),n=!0,We.forEach((s,i)=>{Ye(e,`\r\x1B[K ${i===r?">":" "} ${i===r?"(*)":"( )"} ${s.label} \u2014 ${s.detail}
57
57
  `)})};for(o();;){let s=qu(e);if(s===null||s===4)throw new Ee("eof");if(s===3||s===113||s===81)throw new Ee("cancel");if(s===10||s===13)return Ye(e,`
58
58
  `),We[r].value;if(s>=49&&s<=52)r=s-49;else if(s===107||s===75)r=(r-1+We.length)%We.length;else if(s===106||s===74)r=(r+1)%We.length;else if(s===27){let i=z_(e);i==="[A"||i==="OA"?r=(r-1+We.length)%We.length:(i==="[B"||i==="OB")&&(r=(r+1)%We.length)}else continue;o()}})}catch(n){if(!(n instanceof Ee)||n.reason!=="unavailable")throw n;Ye(e,`Choose one transcription provider:
59
59
  `),We.forEach((s,i)=>{Ye(e,` ${i+1}. ${s.label} \u2014 ${s.detail}
60
- `)});let o=Ys(e,`Select 1-${We.length}: `);if(!/^[1-4]$/.test(o))throw new Ee("cancel");return We[Number(o)-1].value}}function FT(e){let t=e.stt;return t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{}}async function P_(e){let t=e.env??process.env,r=e.stdout??(i=>process.stdout.write(i)),n=(i="")=>r(`${i}
61
- `),o=e.daemonState??"stopped",s=null;try{let i;try{i=AT(e.configFile)}catch{return n(`voice setup: ${e.configFile} is not valid JSON; no changes made.`),1}let a=FT(i),c=$o(b_(a,t)),u=t.OURS_STT_API_KEY?.trim()?"environment":a.apiKey?.trim()?"config":"missing";if(s=t.OURS_ASSUME_YES?null:DT(),n(`ours-mcp voice-setup \u2014 ${e.configFile}`),c.ready){if(n(`voice transcription is already ready (${c.provider}; API key from ${u}).`),s===null)return 0;if(!qT(s,"Change the current voice settings?",!1))return n("kept the current voice settings; no changes made."),0}else if(n("Voice transcription is not ready. This command keeps the provider key hidden."),s===null)return n("No interactive terminal is available; no changes made."),n("Run `ours-mcp voice-setup` in a terminal, or configure OURS_STT_* environment values."),0;n("");let l=String(t.OURS_STT_PROVIDER||a.provider||"").trim().toLowerCase(),d=LT(s,l),p=String(t.OURS_STT_MODEL||a.model||"").trim(),m=String(t.OURS_STT_BASE_URL||a.baseUrl||"").trim(),h=String(a.custom?.url||"").trim();d==="openai-compatible"?(m=wt(s,`Provider /v1 base URL${m?` [${m}]`:""}: `,m),p=wt(s,`Model name (sent verbatim)${p?` [${p}]`:""}: `,p)):d==="elevenlabs"?(p=wt(s,`ElevenLabs model id${p?` [${p}]`:""}: `,p),m=wt(s,`Custom base URL (Enter for provider default)${m?` [${m}]`:""}: `,m)):d==="deepgram"?(p=wt(s,`Model (optional; Enter for provider default)${p?` [${p}]`:""}: `,p),m=wt(s,`Custom base URL (optional)${m?` [${m}]`:""}: `,m)):(h=wt(s,`Full transcription endpoint URL${h?` [${h}]`:""}: `,h),p=wt(s,`Model (optional unless URL contains {model})${p?` [${p}]`:""}: `,p));let g=t.OURS_STT_API_KEY?.trim(),y=String(a.apiKey||"").trim();if(g)n("API key: using OURS_STT_API_KEY from the environment; it will not be copied to config.");else{let v=y?"Provider API key [configured; Enter keeps it]: ":"Provider API key (input hidden): ",k;try{k=wt(s,v,y,!0)}catch(W){if(!(W instanceof Ee)||W.reason!=="unavailable")throw W;if(Ye(s,`
60
+ `)});let o=Ys(e,`Select 1-${We.length}: `);if(!/^[1-4]$/.test(o))throw new Ee("cancel");return We[Number(o)-1].value}}function FP(e){let t=e.stt;return t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{}}async function T_(e){let t=e.env??process.env,r=e.stdout??(i=>process.stdout.write(i)),n=(i="")=>r(`${i}
61
+ `),o=e.daemonState??"stopped",s=null;try{let i;try{i=AP(e.configFile)}catch{return n(`voice setup: ${e.configFile} is not valid JSON; no changes made.`),1}let a=FP(i),c=xo(b_(a,t)),u=t.OURS_STT_API_KEY?.trim()?"environment":a.apiKey?.trim()?"config":"missing";if(s=t.OURS_ASSUME_YES?null:DP(),n(`ours-mcp voice-setup \u2014 ${e.configFile}`),c.ready){if(n(`voice transcription is already ready (${c.provider}; API key from ${u}).`),s===null)return 0;if(!qP(s,"Change the current voice settings?",!1))return n("kept the current voice settings; no changes made."),0}else if(n("Voice transcription is not ready. This command keeps the provider key hidden."),s===null)return n("No interactive terminal is available; no changes made."),n("Run `ours-mcp voice-setup` in a terminal, or configure OURS_STT_* environment values."),0;n("");let l=String(t.OURS_STT_PROVIDER||a.provider||"").trim().toLowerCase(),d=LP(s,l),p=String(t.OURS_STT_MODEL||a.model||"").trim(),m=String(t.OURS_STT_BASE_URL||a.baseUrl||"").trim(),h=String(a.custom?.url||"").trim();d==="openai-compatible"?(m=wt(s,`Provider /v1 base URL${m?` [${m}]`:""}: `,m),p=wt(s,`Model name (sent verbatim)${p?` [${p}]`:""}: `,p)):d==="elevenlabs"?(p=wt(s,`ElevenLabs model id${p?` [${p}]`:""}: `,p),m=wt(s,`Custom base URL (Enter for provider default)${m?` [${m}]`:""}: `,m)):d==="deepgram"?(p=wt(s,`Model (optional; Enter for provider default)${p?` [${p}]`:""}: `,p),m=wt(s,`Custom base URL (optional)${m?` [${m}]`:""}: `,m)):(h=wt(s,`Full transcription endpoint URL${h?` [${h}]`:""}: `,h),p=wt(s,`Model (optional unless URL contains {model})${p?` [${p}]`:""}: `,p));let g=t.OURS_STT_API_KEY?.trim(),y=String(a.apiKey||"").trim();if(g)n("API key: using OURS_STT_API_KEY from the environment; it will not be copied to config.");else{let v=y?"Provider API key [configured; Enter keeps it]: ":"Provider API key (input hidden): ",k;try{k=wt(s,v,y,!0)}catch(W){if(!(W instanceof Ee)||W.reason!=="unavailable")throw W;if(Ye(s,`
62
62
  Secure hidden input is unavailable on this terminal.
63
63
  `),Ye(s,`Visible fallback will echo the token on screen and may leave it in scrollback.
64
- `),Ys(s,"Type SHOW to enter the token visibly, or press Enter to cancel: ")!=="SHOW")throw new Ee("cancel");k=Ys(s,"Provider API key (VISIBLE): ",y)}let A=UT(k);if(!A.ok)return n(`Voice setup was not saved: ${A.reason}.`),1;y=A.value}let S={...a,provider:d,...y?{apiKey:y}:{},...p?{model:p}:{},...m?{baseUrl:m}:{},...d==="custom"&&h?{custom:{...a.custom??{},url:h}}:{}},$=$o(b_(S,t));if(!$.ready)return n(`Voice setup was not saved: ${$.reason}.`),1;if(e.dryRun)return n(`voice transcription would be configured (${d}); API key stays hidden.`),n("dry-run: config, daemon, and existing settings were not changed."),0;let w={...i,stt:S};o==="managed"&&n("Restarting ours-mcp to apply and verify voice transcription\u2026");let P=await MT(e.configFile,w,o,e.apply);return!P.ok&&P.stage==="write"?(n(`Could not write ${e.configFile}; the prior config is intact.`),1):o==="stopped"?(n(`voice transcription configured (${d}); API key saved in mode-0600 config.`),n("The daemon is stopped; run `ours-mcp start` to apply it."),0):o==="external"?(n(`voice transcription configured (${d}); API key saved in mode-0600 config.`),n("The daemon has no managed PID; restart its external launcher to apply the new settings."),0):P.ok?(n(`voice transcription: ready (${d}).`),n("API key saved in mode-0600 config and never displayed."),0):P.rolledBack?(n("Voice readiness check failed; restored the exact prior config."),P.daemonRestored?(n("The prior config and daemon state were restored; voice setup was not changed."),2):(n("The prior config is restored, but the daemon did not restart; run `ours-mcp status`."),2)):(n("Voice setup failed and automatic config rollback also failed; inspect the config before restarting."),2)}catch(i){return i instanceof Ee?i.reason==="cancel"?(n(""),n("voice setup cancelled; no configuration changes were made."),130):i.reason==="eof"?(n(""),n("voice setup ended at EOF; no configuration changes were made."),1):(n("Secure interactive input is unavailable on this terminal; no changes made."),1):(n("voice setup failed unexpectedly; no credential was displayed."),1)}finally{if(s!==null)try{zT(s)}catch{}}}var R_=`ours-mcp voice-setup \u2014 configure voice transcription securely
64
+ `),Ys(s,"Type SHOW to enter the token visibly, or press Enter to cancel: ")!=="SHOW")throw new Ee("cancel");k=Ys(s,"Provider API key (VISIBLE): ",y)}let A=UP(k);if(!A.ok)return n(`Voice setup was not saved: ${A.reason}.`),1;y=A.value}let S={...a,provider:d,...y?{apiKey:y}:{},...p?{model:p}:{},...m?{baseUrl:m}:{},...d==="custom"&&h?{custom:{...a.custom??{},url:h}}:{}},$=xo(b_(S,t));if(!$.ready)return n(`Voice setup was not saved: ${$.reason}.`),1;if(e.dryRun)return n(`voice transcription would be configured (${d}); API key stays hidden.`),n("dry-run: config, daemon, and existing settings were not changed."),0;let w={...i,stt:S};o==="managed"&&n("Restarting ours-mcp to apply and verify voice transcription\u2026");let T=await MP(e.configFile,w,o,e.apply);return!T.ok&&T.stage==="write"?(n(`Could not write ${e.configFile}; the prior config is intact.`),1):o==="stopped"?(n(`voice transcription configured (${d}); API key saved in mode-0600 config.`),n("The daemon is stopped; run `ours-mcp start` to apply it."),0):o==="external"?(n(`voice transcription configured (${d}); API key saved in mode-0600 config.`),n("The daemon has no managed PID; restart its external launcher to apply the new settings."),0):T.ok?(n(`voice transcription: ready (${d}).`),n("API key saved in mode-0600 config and never displayed."),0):T.rolledBack?(n("Voice readiness check failed; restored the exact prior config."),T.daemonRestored?(n("The prior config and daemon state were restored; voice setup was not changed."),2):(n("The prior config is restored, but the daemon did not restart; run `ours-mcp status`."),2)):(n("Voice setup failed and automatic config rollback also failed; inspect the config before restarting."),2)}catch(i){return i instanceof Ee?i.reason==="cancel"?(n(""),n("voice setup cancelled; no configuration changes were made."),130):i.reason==="eof"?(n(""),n("voice setup ended at EOF; no configuration changes were made."),1):(n("Secure interactive input is unavailable on this terminal; no changes made."),1):(n("voice setup failed unexpectedly; no credential was displayed."),1)}finally{if(s!==null)try{zP(s)}catch{}}}var R_=`ours-mcp voice-setup \u2014 configure voice transcription securely
65
65
 
66
66
  Usage: ours-mcp voice-setup [--dry-run]
67
67
 
@@ -76,31 +76,31 @@ exact prior config.
76
76
 
77
77
  Headless automation remains environment-driven through OURS_STT_PROVIDER,
78
78
  OURS_STT_API_KEY, OURS_STT_MODEL, OURS_STT_BASE_URL, and OURS_STT_LANGUAGE.
79
- Exit 2 means restart/readiness failed after a write and rollback was attempted.`;import*as yr from"node:fs";import{join as VT}from"node:path";var HT="startup-progress.json",BT=1,E_={initializing:"Initializing daemon",wrapper:"Starting protocol runtime",registrar:"Starting local contact book",identities:"Restoring identities",reconciliation:"Reconciling restored identities",server:"Opening local API",ready:"Daemon ready",failed:"Daemon startup failed"};function KT(e){return VT(e,HT)}function JT(e){return typeof e=="string"&&Object.hasOwn(E_,e)}function I_(e){try{let t=JSON.parse(yr.readFileSync(KT(e),"utf8"));return t.version!==BT||!Number.isInteger(t.pid)||(t.pid??0)<=0||typeof t.bootId!="string"||!t.bootId||!JT(t.phase)||!Number.isFinite(t.startedAt)||!Number.isFinite(t.updatedAt)||(t.completed!==void 0||t.total!==void 0)&&(!Number.isInteger(t.completed)||!Number.isInteger(t.total)||(t.completed??-1)<0||(t.total??-1)<0||(t.completed??0)>(t.total??0))?null:t}catch{return null}}function Lu(e){let t=E_[e.phase];return e.phase==="identities"&&e.completed!==void 0&&e.total!==void 0?`${t} ${e.completed}/${e.total}`:t}function O_(e,t){let r=`startup: ${Lu(e)}`;return t?`\r${r}\x1B[K`:`${r}
80
- `}async function A_(e){let t=e.now??Date.now,r=e.sleep??(c=>new Promise(u=>setTimeout(u,c))),n=t(),o=n,s=-1,i="",a=null;for(;;){if(await e.isReady())return{ok:!0,elapsedMs:t()-n,lastProgress:a};let c=e.readProgress();if(c?.pid===e.pid){a=c,c.updatedAt>s&&(s=c.updatedAt,o=t());let p=`${c.phase}:${c.completed??""}:${c.total??""}`;if(p!==i&&(i=p,e.onProgress?.(c)),c.phase==="failed")return{ok:!1,reason:"daemon-reported-failure",elapsedMs:t()-n,lastProgress:a}}if(!e.isProcessAlive())return{ok:!1,reason:"process-exited",elapsedMs:t()-n,lastProgress:a};let u=t()-n;if(u>=e.absoluteMs)return{ok:!1,reason:"absolute-timeout",elapsedMs:u,lastProgress:a};if(t()-o>=e.inactivityMs)return{ok:!1,reason:"inactivity-timeout",elapsedMs:u,lastProgress:a};let l=e.absoluteMs-u,d=e.inactivityMs-(t()-o);await r(Math.max(1,Math.min(e.pollMs,l,d)))}}if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;H.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var $t=Cu(),Ze=$t.stateDir,se=$t.port,xo=()=>{let e=Nu($t,{generate:!1})?.token??null;return e?{"x-ours-api-token":e}:{}},sn=$t.brokerUrl,wr=Ct(Ze,"daemon.pid"),vr=Ct(Ze,"daemon.log"),Jt=WT(import.meta.url),b=(...e)=>process.stdout.write(`${e.join(" ")}
79
+ Exit 2 means restart/readiness failed after a write and rollback was attempted.`;import*as br from"node:fs";import{join as VP}from"node:path";var HP="startup-progress.json",BP=1,E_={initializing:"Initializing daemon",wrapper:"Starting protocol runtime",registrar:"Starting local contact book",identities:"Restoring identities",reconciliation:"Reconciling restored identities",server:"Opening local API",ready:"Daemon ready",failed:"Daemon startup failed"};function KP(e){return VP(e,HP)}function JP(e){return typeof e=="string"&&Object.hasOwn(E_,e)}function I_(e){try{let t=JSON.parse(br.readFileSync(KP(e),"utf8"));return t.version!==BP||!Number.isInteger(t.pid)||(t.pid??0)<=0||typeof t.bootId!="string"||!t.bootId||!JP(t.phase)||!Number.isFinite(t.startedAt)||!Number.isFinite(t.updatedAt)||(t.completed!==void 0||t.total!==void 0)&&(!Number.isInteger(t.completed)||!Number.isInteger(t.total)||(t.completed??-1)<0||(t.total??-1)<0||(t.completed??0)>(t.total??0))?null:t}catch{return null}}function Lu(e){let t=E_[e.phase];return e.phase==="identities"&&e.completed!==void 0&&e.total!==void 0?`${t} ${e.completed}/${e.total}`:t}function O_(e,t){let r=`startup: ${Lu(e)}`;return t?`\r${r}\x1B[K`:`${r}
80
+ `}async function A_(e){let t=e.now??Date.now,r=e.sleep??(c=>new Promise(u=>setTimeout(u,c))),n=t(),o=n,s=-1,i="",a=null;for(;;){if(await e.isReady())return{ok:!0,elapsedMs:t()-n,lastProgress:a};let c=e.readProgress();if(c?.pid===e.pid){a=c,c.updatedAt>s&&(s=c.updatedAt,o=t());let p=`${c.phase}:${c.completed??""}:${c.total??""}`;if(p!==i&&(i=p,e.onProgress?.(c)),c.phase==="failed")return{ok:!1,reason:"daemon-reported-failure",elapsedMs:t()-n,lastProgress:a}}if(!e.isProcessAlive())return{ok:!1,reason:"process-exited",elapsedMs:t()-n,lastProgress:a};let u=t()-n;if(u>=e.absoluteMs)return{ok:!1,reason:"absolute-timeout",elapsedMs:u,lastProgress:a};if(t()-o>=e.inactivityMs)return{ok:!1,reason:"inactivity-timeout",elapsedMs:u,lastProgress:a};let l=e.absoluteMs-u,d=e.inactivityMs-(t()-o);await r(Math.max(1,Math.min(e.pollMs,l,d)))}}if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;V.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var St=Cu(),je=St.stateDir,re=St.port,an=()=>{let e=Nu(St,{generate:!1})?.token??null;return e?{"x-ours-api-token":e}:{}},sn=St.brokerUrl,$r=$t(je,"daemon.pid"),wr=$t(je,"daemon.log"),Wt=WP(import.meta.url),b=(...e)=>process.stdout.write(`${e.join(" ")}
81
81
  `),ee=(...e)=>process.stderr.write(`${e.join(" ")}
82
- `),br="0.17.1";async function Ku(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),n=await fetch(`http://127.0.0.1:${se}${e}`,{signal:t.signal});if(clearTimeout(r),n.ok){let o=await n.json();if(o&&typeof o.version=="string")return o}}catch{}return null}function C_(e){if(b(` cli: v${br}`),e?.version){let t=e.version!==br;b(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${br}`:""))}else b(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var ti=e=>new Promise(t=>setTimeout(t,e));function QT(){try{let e=parseInt(H.readFileSync(wr,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Xs(e){try{if(process.kill(e,0),process.platform==="linux")try{if(__(H.readFileSync(`/proc/${e}/stat`,"utf8")))return!1}catch{try{process.kill(e,0)}catch{return!1}}return!0}catch{return!1}}function an(){let e=QT();if(e&&Xs(e))return e;if(e)try{H.rmSync(wr,{force:!0})}catch{}return null}function Gt(e,t=1e3){return new Promise(r=>{let n=GT({host:"127.0.0.1",port:e}),o=s=>{n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>o(!0)),n.once("timeout",()=>o(!1)),n.once("error",()=>o(!1))})}async function XT(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await Gt(e))return!0;await ti(400)}return!1}function Gu(e,t){let r=Number(process.env[e]||"");return Number.isFinite(r)&&r>0?r:t}var L_=Gu("OURS_TEST_STARTUP_ABSOLUTE_MS",18e4),F_=Gu("OURS_TEST_STARTUP_INACTIVITY_MS",3e4),V_=Gu("OURS_TEST_STARTUP_POLL_MS",400);async function eP(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Math.min(1e3,V_));try{let n=await fetch(`http://127.0.0.1:${e}/identities`,{signal:t.signal,headers:xo()}),o=n.ok;try{await n.body?.cancel()}catch{}return o}catch{return!1}finally{clearTimeout(r)}}function N_(e){return e<1e3?`${Math.round(e)}ms`:e%6e4===0?`${e/6e4}m`:`${Math.round(e/1e3)}s`}function tP(e,t){let r=t?` Last phase: ${Lu(t)}.`:"";return e==="process-exited"||e==="daemon-reported-failure"?`daemon exited before becoming ready.${r}`:e==="inactivity-timeout"?`daemon startup made no observable progress for ${N_(F_)}.${r} The process is still running, but startup is stalled.`:`daemon startup did not finish within ${N_(L_)}.${r} The bounded wait expired.`}async function j_(){let e=an();if(e){b(`ours-mcp is already running (pid ${e}, port ${se}).`);return}H.mkdirSync(Ze,{recursive:!0});let t=H.openSync(vr,"a"),r=D_(process.execPath,[Jt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(se),OURS_BROKER_URL:sn,OURS_STATE_DIR:Ze}});r.unref(),r.pid||(ee("failed to spawn the daemon."),process.exit(1)),H.writeFileSync(wr,String(r.pid)),b(`starting ours-mcp (pid ${r.pid})\u2026`);let n=!!process.stderr.isTTY,o=!1,s=await A_({pid:r.pid,absoluteMs:L_,inactivityMs:F_,pollMs:V_,isProcessAlive:()=>Xs(r.pid),isReady:()=>eP(se),readProgress:()=>I_(Ze),onProgress:i=>{o=!0,process.stderr.write(O_(i,n))}});o&&n&&process.stderr.write(`
83
- `),s.ok?(b(`ours-mcp is up on http://localhost:${se}/mcp`),b(` broker: ${sn}`),b(` state: ${Ze}`),b(` logs: ${vr}`)):(ee(`${tP(s.reason,s.lastProgress)} Check ${vr}.`),process.exit(1))}async function rP(){if(!await Gt(se)){if(!an()){H.mkdirSync(Ze,{recursive:!0});let e=H.openSync(vr,"a"),t=D_(process.execPath,[Jt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(se),OURS_BROKER_URL:sn,OURS_STATE_DIR:Ze}});if(t.unref(),t.pid)try{H.writeFileSync(wr,String(t.pid))}catch{}}await XT(se)}}async function ei(){let e=an();if(!e){b("ours-mcp is not running.");return}b(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){ee(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Xs(e);t++)await ti(200);if(Xs(e)){ee(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{H.rmSync(wr,{force:!0})}catch{}b("stopped.")}async function nP(){let e=an();if(!e){if(await Gt(se)){let n=await Ku();b("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),b(` url: http://localhost:${se}/mcp (reachable)`),C_(n);return}b("ours-mcp: stopped"),b(` cli: v${br}`),process.exitCode=1;return}let t=await Gt(se),r=t?await Ku():null;b("ours-mcp: running"),b(` pid: ${e}`),b(` url: http://localhost:${se}/mcp ${t?"(reachable)":"(port not answering!)"}`),b(` broker: ${sn}`),b(` state: ${Ze}`),b(` logs: ${vr}`),C_(r)}async function oP(){if(b(`ours-mcp v${br}`),await Gt(se)){let e=await Ku();e?.version?b(`running daemon: v${e.version}`+(e.version!==br?" (differs \u2014 restart to update)":"")):b("running daemon: version unknown (predates /version)")}else b("daemon: not running")}async function sP(){let e=Cu(),t=wo();b(`ours-mcp setup \u2014 ${t}`),b("Enter a value, or press Enter to keep the current [bracketed] one."),b("");let r=Qs({input:process.stdin,output:process.stdout}),n;try{let l=async(ie,be)=>{let qe=(await r.question(` ${ie} [${be}]: `)).trim();return qe===""?be:qe},d=await l("broker URL",e.brokerUrl),p=await l("HTTP port",String(e.port)),m=await l("state dir",e.stateDir),h=await l("GC interval (ms)",String(e.gcIntervalMs)),g=await l("proxy auto-starts daemon (true/false)",String(e.autoStart)),y=await l("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility);b(""),b(" Voice-message transcription (STT). Leave provider empty to keep it off \u2014"),b(" agents then deterministically tell users voice messages cannot be read."),b(" No provider or model is assumed; model strings pass to your provider verbatim.");let S=(await r.question(` STT provider (openai-compatible / elevenlabs / deepgram / custom, empty=off) [${e.stt?.provider??""}]: `)).trim()||(e.stt?.provider??""),$=e.stt?.model??"",w=e.stt?.baseUrl??"";S&&($=await l("STT model (verbatim, e.g. whisper-large-v3-turbo / scribe_v1 / nova-2)",$),w=await l("STT base URL (required for openai-compatible; empty = provider default)",w),b(" (API key is not echoed here. Run `ours-mcp voice-setup` for guided hidden input,"),b(" or set OURS_STT_API_KEY for environment-only secret injection.)"));let P=parseInt(p,10);(!Number.isFinite(P)||P<=0)&&(ee(`invalid port: ${p}`),process.exit(1));let v=parseInt(h,10);(!Number.isFinite(v)||v<=0)&&(ee(`invalid GC interval: ${h}`),process.exit(1));let k=g.toLowerCase()==="true"||g==="1",A=y.trim().toLowerCase();bo.includes(A)||(ee(`invalid visibility: ${y} (expected one of ${bo.join(", ")})`),process.exit(1));let W=S?{...e.stt??{},provider:S,...$?{model:$}:{},...w?{baseUrl:w}:{}}:e.stt;n={brokerUrl:d,port:P,stateDir:q_(m),gcIntervalMs:v,autoStart:k,apiVisibility:A,...e.apiToken?{apiToken:e.apiToken}:{},...W?{stt:W}:{}}}finally{r.close()}s_(n),b(""),b(`wrote ${t} (mode 0600):`);let o={...n,...n.apiToken?{apiToken:"[redacted]"}:{},...n.stt?{stt:{...n.stt,...n.stt.apiKey?{apiKey:"[redacted]"}:{}}}:{}};b(JSON.stringify(o,null,2));let s=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART","OURS_API_VISIBILITY","OURS_API_TOKEN","OURS_STT_PROVIDER","OURS_STT_API_KEY","OURS_STT_MODEL","OURS_STT_BASE_URL","OURS_STT_LANGUAGE"].filter(l=>process.env[l]!==void 0);s.length&&(b(""),b(`note: these env vars are set and OVERRIDE the file at runtime: ${s.join(", ")}`));let i=an();if(!i)return;let a=Qs({input:process.stdin,output:process.stdout}),c=!1;try{let l=(await a.question(`
84
- daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=l==="y"||l==="yes"}finally{a.close()}if(!c){b("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await ei();let u=on(process.execPath,[Jt,"start"],{stdio:"inherit"});u.status!==0&&process.exit(u.status??1)}function iP(e){let t=$o($t.stt),r=$t.stt?.provider?.trim().toLowerCase()||null,n=process.env.OURS_STT_API_KEY?.trim()?"environment":$t.stt?.apiKey?.trim()?"config":"missing",o=t.ready?{ready:!0,provider:t.provider,apiKey:"configured",keySource:n}:{ready:!1,provider:r,apiKey:n==="missing"?"missing":"configured",keySource:n,reason:t.reason};if(e.includes("--json")){b(JSON.stringify(o));return}o.ready?b(`voice transcription: ready (${o.provider}; API key from ${o.keySource})`):b(`voice transcription: not ready \u2014 ${o.reason}`)}async function aP(e){if(e.includes("--help")||e.includes("-h")){b(R_);return}let t=new Set(["--dry-run"]);if(e.filter(i=>!t.has(i)).length){ee("voice-setup: unsupported command-line option or argument"),ee("The provider key is never accepted as a CLI argument. Run `ours-mcp voice-setup --help`."),process.exitCode=1;return}let n=an()!==null,o=await Gt(se),s=await P_({configFile:wo(),env:process.env,dryRun:e.includes("--dry-run"),daemonState:n?"managed":o?"external":"stopped",apply:async()=>{let i=on(process.execPath,[Jt,"restart"],{stdio:"inherit"});if(i.error||i.status!==0)return{ok:!1};let a=on(process.execPath,[Jt,"voice-status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(a.error||a.status!==0)return{ok:!1};try{return{ok:JSON.parse(a.stdout||"{}").ready===!0}}catch{return{ok:!1}}}});s!==0&&(process.exitCode=s)}function Vu(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Hu(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function cP(e){let t=Hu(e,"--name"),r=Vu(e,"--force-bind","--no-force-bind"),n=Vu(e,"--local-book","--no-local-book"),o=Vu(e,"--auto-accept-local","--no-auto-accept-local"),s=e.includes("--overwrite"),i=e.includes("--print"),a=Hu(e,"--path")??Hu(e,"--dir")??process.cwd(),c=t!==void 0||r.set||n.set||o.set||i,u;if(c?((!t||!t.trim())&&(ee("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),u={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:o.value??!0}):u=await uP(),i){b(JSON.stringify(Hs(u),null,2));return}let l=ju(a);if(!s&&H.existsSync(l)){c&&(ee(`define-local-identity-file: ${l} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let p=Qs({input:process.stdin,output:process.stdout}),m=!1;try{let h=(await p.question(`
85
- ${l} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();m=h==="y"||h==="yes"}finally{p.close()}if(!m){b("aborted \u2014 nothing written.");return}}let d=i_(a,u,!0);b(""),b(`wrote ${d}:`),b(JSON.stringify(Hs(u),null,2))}async function uP(){b("ours-mcp define-local-identity-file \u2014 interactive"),b(`Answer the prompts; the result is written to ${Ct(process.cwd(),Fs)}.`),b("");let e=Qs({input:process.stdin,output:process.stdout});try{let t=async(i,a)=>{let c=a?"Y/n":"y/N",u=(await e.question(` ${i} [${c}]: `)).trim().toLowerCase();return u===""?a:u==="y"||u==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||b(" (name is required)");let n=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),o=await t("Add to the host-local contact book?",!0),s=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:n,exposeLocal:o,localAutoAccept:s}}finally{e.close()}}async function lP(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(ee('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await Gt(se)||(ee(`create-root: the daemon is not running on port ${se} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new tn(new URL(`http://127.0.0.1:${se}/mcp`),{requestInit:{headers:xo()}}),n=new Zs({name:"ours-mcp-cli",version:br});try{await n.connect(r);let o=await n.callTool({name:"create_root_identity",arguments:{name:t,skip_if_root_exists:!0}}),s=(Array.isArray(o.content)?o.content:[]).map(i=>typeof i.text=="string"?i.text:"").join(" ").split(/\n\nAsk the user\b/)[0].replace(/^create_root_identity failed: /,"").trim();if(o.isError){if(/a root identity already exists/i.test(s)){b(`create-root: ${s.split("\u2014")[0].trim()} \u2014 nothing to do.`);return}ee(`create-root failed: ${s}`),process.exit(1)}b(s)}finally{try{await r.terminateSession()}catch{}try{await n.close()}catch{}}}function H_(e,t){t.event==="message_received"?b(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="file_received"?b(`[${e}] new file ${t.filename??"?"} from ${t.from??"?"}`+(t.bytes!==void 0?` (${t.bytes} B)`:"")+(t.file_id!==void 0?` (#${t.file_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="local_contact_request"?b(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"&&b(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`)}function Kt(e){ee(`ours-mcp watch: ${e}`),process.exit(1)}async function dP(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${se}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?q_(n.stateDir):Ze}}catch{}return null}var pP=e=>`http://127.0.0.1:${se}/identities/${encodeURIComponent(e)}/notifications`;async function M_(e){let t=async o=>{let s=new AbortController,i=setTimeout(()=>s.abort(),35e3),a;try{a=await fetch(`${pP(e)}?since=${o}`,{headers:xo(),signal:s.signal})}finally{clearTimeout(i)}if(a.status===401&&Kt(`daemon rejected the API token (401) for identity "${e}". Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode).`),!a.ok)throw new Error(`daemon returned HTTP ${a.status}`);return await a.json()},r=(await t("tip")).cursor??0,n=0;for(;;)try{let o=await t(String(r));if(n=0,Array.isArray(o.events))for(let s of o.events)H_(e,s);typeof o.cursor=="number"&&(r=o.cursor)}catch(o){n=Math.min(n+1e3,5e3),ee(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(o?.message??o)}), retrying\u2026`),await ti(n)}}async function fP(e){if(e){await M_(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${se}/identities`,{headers:xo()});if(r.status===401&&Kt("daemon rejected the API token (401). Set OURS_API_TOKEN or run watch as the daemon owner."),r.ok){let n=await r.json();for(let o of n.identities??[]){let s=typeof o?.name=="string"?o.name:void 0;s&&!t.has(s)&&(t.add(s),M_(s))}}}catch{}await ti(3e3)}}var Bu=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function mP(e,t){try{H.readdirSync(e)}catch(i){Kt(`cannot watch \u2014 the daemon API is unreachable AND ${e} is not readable (${i?.code??i}). On a multi-user host, run watch as the daemon owner, or enable the daemon API (start the daemon) so watch can stream over HTTP.`)}if(t)try{H.readdirSync(Ct(e,t))}catch(i){Kt(`cannot watch identity "${t}" \u2014 ${Ct(e,t)} is not readable (${i?.code??i}). Is the daemon running and the name correct?`)}let r=new Map,n=i=>{let a;try{a=H.readdirSync(e,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name)}catch(c){Bu(c)&&Kt(`lost read access to ${e} (${c.code}) \u2014 cannot watch.`);return}for(let c of a){if(t&&c!==t)continue;let u=Ct(e,c,"notifications.log"),l;try{l=H.statSync(u).size}catch(m){Bu(m)&&Kt(`cannot read ${u} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}let d=r.get(u);if(d===void 0&&(d=i?l:0,r.set(u,d),i))continue;if(l<=d){l<d&&r.set(u,l);continue}let p;try{let m=H.openSync(u,"r"),h=Buffer.alloc(l-d);H.readSync(m,h,0,h.length,d),H.closeSync(m),p=h.toString("utf8")}catch(m){Bu(m)&&Kt(`cannot read ${u} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}r.set(u,l);for(let m of p.split(`
86
- `))if(m.trim())try{H_(c,JSON.parse(m))}catch{}}};ee(`ours-mcp watch: daemon API unreachable \u2014 falling back to file poll of ${e} (Ctrl-C to stop)`),n(!0);let o=setInterval(()=>n(!1),1e3),s=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}async function hP(){try{let e=await fetch(`http://127.0.0.1:${se}/identities`,{headers:xo()});return e.status===401&&Kt("daemon rejected the API token (401). Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode)."),e.status===404?"file":e.ok?"api":"file"}catch{return"file"}}async function gP(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await dP()!==null&&await hP()==="api"){ee(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${se} (Ctrl-C to stop)`),await fP(e);return}mP(Ze,e)}var So="ours.service",B_="solutions.adaptframework.ours";function K_(){return Ct(Z_(),".config","systemd","user",So)}function J_(){return Ct(Z_(),"Library","LaunchAgents",`${B_}.plist`)}function nn(e,t){return on(e,t,{stdio:"inherit"}).status===0}function _P(){let e=K_();H.mkdirSync(Ju(e),{recursive:!0});let t=`[Unit]
82
+ `),Gt="0.17.2";async function Ku(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),n=await fetch(`http://127.0.0.1:${re}${e}`,{signal:t.signal});if(clearTimeout(r),n.ok){let o=await n.json();if(o&&typeof o.version=="string")return o}}catch{}return null}function C_(e){if(b(` cli: v${Gt}`),e?.version){let t=e.version!==Gt;b(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${Gt}`:""))}else b(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var ti=e=>new Promise(t=>setTimeout(t,e));function QP(){try{let e=parseInt(V.readFileSync($r,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Xs(e){try{if(process.kill(e,0),process.platform==="linux")try{if(__(V.readFileSync(`/proc/${e}/stat`,"utf8")))return!1}catch{try{process.kill(e,0)}catch{return!1}}return!0}catch{return!1}}function cn(){let e=QP();if(e&&Xs(e))return e;if(e)try{V.rmSync($r,{force:!0})}catch{}return null}function Nt(e,t=1e3){return new Promise(r=>{let n=GP({host:"127.0.0.1",port:e}),o=s=>{n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>o(!0)),n.once("timeout",()=>o(!1)),n.once("error",()=>o(!1))})}async function XP(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await Nt(e))return!0;await ti(400)}return!1}function Gu(e,t){let r=Number(process.env[e]||"");return Number.isFinite(r)&&r>0?r:t}var L_=Gu("OURS_TEST_STARTUP_ABSOLUTE_MS",18e4),F_=Gu("OURS_TEST_STARTUP_INACTIVITY_MS",3e4),V_=Gu("OURS_TEST_STARTUP_POLL_MS",400);async function eT(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Math.min(1e3,V_));try{let n=await fetch(`http://127.0.0.1:${e}/identities`,{signal:t.signal,headers:an()}),o=n.ok;try{await n.body?.cancel()}catch{}return o}catch{return!1}finally{clearTimeout(r)}}function N_(e){return e<1e3?`${Math.round(e)}ms`:e%6e4===0?`${e/6e4}m`:`${Math.round(e/1e3)}s`}function tT(e,t){let r=t?` Last phase: ${Lu(t)}.`:"";return e==="process-exited"||e==="daemon-reported-failure"?`daemon exited before becoming ready.${r}`:e==="inactivity-timeout"?`daemon startup made no observable progress for ${N_(F_)}.${r} The process is still running, but startup is stalled.`:`daemon startup did not finish within ${N_(L_)}.${r} The bounded wait expired.`}async function j_(){let e=cn();if(e){b(`ours-mcp is already running (pid ${e}, port ${re}).`);return}V.mkdirSync(je,{recursive:!0});let t=V.openSync(wr,"a"),r=D_(process.execPath,[Wt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(re),OURS_BROKER_URL:sn,OURS_STATE_DIR:je}});r.unref(),r.pid||(ee("failed to spawn the daemon."),process.exit(1)),V.writeFileSync($r,String(r.pid)),b(`starting ours-mcp (pid ${r.pid})\u2026`);let n=!!process.stderr.isTTY,o=!1,s=await A_({pid:r.pid,absoluteMs:L_,inactivityMs:F_,pollMs:V_,isProcessAlive:()=>Xs(r.pid),isReady:()=>eT(re),readProgress:()=>I_(je),onProgress:i=>{o=!0,process.stderr.write(O_(i,n))}});o&&n&&process.stderr.write(`
83
+ `),s.ok?(b(`ours-mcp is up on http://localhost:${re}/mcp`),b(` broker: ${sn}`),b(` state: ${je}`),b(` logs: ${wr}`)):(ee(`${tT(s.reason,s.lastProgress)} Check ${wr}.`),process.exit(1))}async function rT(){if(!await Nt(re)){if(!cn()){V.mkdirSync(je,{recursive:!0});let e=V.openSync(wr,"a"),t=D_(process.execPath,[Wt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(re),OURS_BROKER_URL:sn,OURS_STATE_DIR:je}});if(t.unref(),t.pid)try{V.writeFileSync($r,String(t.pid))}catch{}}await XP(re)}}async function ei(){let e=cn();if(!e){b("ours-mcp is not running.");return}b(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){ee(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Xs(e);t++)await ti(200);if(Xs(e)){ee(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{V.rmSync($r,{force:!0})}catch{}b("stopped.")}async function nT(){let e=cn();if(!e){if(await Nt(re)){let n=await Ku();b("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),b(` url: http://localhost:${re}/mcp (reachable)`),C_(n);return}b("ours-mcp: stopped"),b(` cli: v${Gt}`),process.exitCode=1;return}let t=await Nt(re),r=t?await Ku():null;b("ours-mcp: running"),b(` pid: ${e}`),b(` url: http://localhost:${re}/mcp ${t?"(reachable)":"(port not answering!)"}`),b(` broker: ${sn}`),b(` state: ${je}`),b(` logs: ${wr}`),C_(r)}async function oT(){if(b(`ours-mcp v${Gt}`),await Nt(re)){let e=await Ku();e?.version?b(`running daemon: v${e.version}`+(e.version!==Gt?" (differs \u2014 restart to update)":"")):b("running daemon: version unknown (predates /version)")}else b("daemon: not running")}async function sT(){let e=Cu(),t=So();b(`ours-mcp setup \u2014 ${t}`),b("Enter a value, or press Enter to keep the current [bracketed] one."),b("");let r=Qs({input:process.stdin,output:process.stdout}),n;try{let l=async(ie,be)=>{let qe=(await r.question(` ${ie} [${be}]: `)).trim();return qe===""?be:qe},d=await l("broker URL",e.brokerUrl),p=await l("HTTP port",String(e.port)),m=await l("state dir",e.stateDir),h=await l("GC interval (ms)",String(e.gcIntervalMs)),g=await l("proxy auto-starts daemon (true/false)",String(e.autoStart)),y=await l("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility);b(""),b(" Voice-message transcription (STT). Leave provider empty to keep it off \u2014"),b(" agents then deterministically tell users voice messages cannot be read."),b(" No provider or model is assumed; model strings pass to your provider verbatim.");let S=(await r.question(` STT provider (openai-compatible / elevenlabs / deepgram / custom, empty=off) [${e.stt?.provider??""}]: `)).trim()||(e.stt?.provider??""),$=e.stt?.model??"",w=e.stt?.baseUrl??"";S&&($=await l("STT model (verbatim, e.g. whisper-large-v3-turbo / scribe_v1 / nova-2)",$),w=await l("STT base URL (required for openai-compatible; empty = provider default)",w),b(" (API key is not echoed here. Run `ours-mcp voice-setup` for guided hidden input,"),b(" or set OURS_STT_API_KEY for environment-only secret injection.)"));let T=parseInt(p,10);(!Number.isFinite(T)||T<=0)&&(ee(`invalid port: ${p}`),process.exit(1));let v=parseInt(h,10);(!Number.isFinite(v)||v<=0)&&(ee(`invalid GC interval: ${h}`),process.exit(1));let k=g.toLowerCase()==="true"||g==="1",A=y.trim().toLowerCase();$o.includes(A)||(ee(`invalid visibility: ${y} (expected one of ${$o.join(", ")})`),process.exit(1));let W=S?{...e.stt??{},provider:S,...$?{model:$}:{},...w?{baseUrl:w}:{}}:e.stt;n={brokerUrl:d,port:T,stateDir:q_(m),gcIntervalMs:v,autoStart:k,apiVisibility:A,...e.apiToken?{apiToken:e.apiToken}:{},...W?{stt:W}:{}}}finally{r.close()}s_(n),b(""),b(`wrote ${t} (mode 0600):`);let o={...n,...n.apiToken?{apiToken:"[redacted]"}:{},...n.stt?{stt:{...n.stt,...n.stt.apiKey?{apiKey:"[redacted]"}:{}}}:{}};b(JSON.stringify(o,null,2));let s=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART","OURS_API_VISIBILITY","OURS_API_TOKEN","OURS_STT_PROVIDER","OURS_STT_API_KEY","OURS_STT_MODEL","OURS_STT_BASE_URL","OURS_STT_LANGUAGE"].filter(l=>process.env[l]!==void 0);s.length&&(b(""),b(`note: these env vars are set and OVERRIDE the file at runtime: ${s.join(", ")}`));let i=cn();if(!i)return;let a=Qs({input:process.stdin,output:process.stdout}),c=!1;try{let l=(await a.question(`
84
+ daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=l==="y"||l==="yes"}finally{a.close()}if(!c){b("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await ei();let u=on(process.execPath,[Wt,"start"],{stdio:"inherit"});u.status!==0&&process.exit(u.status??1)}function iT(e){let t=xo(St.stt),r=St.stt?.provider?.trim().toLowerCase()||null,n=process.env.OURS_STT_API_KEY?.trim()?"environment":St.stt?.apiKey?.trim()?"config":"missing",o=t.ready?{ready:!0,provider:t.provider,apiKey:"configured",keySource:n}:{ready:!1,provider:r,apiKey:n==="missing"?"missing":"configured",keySource:n,reason:t.reason};if(e.includes("--json")){b(JSON.stringify(o));return}o.ready?b(`voice transcription: ready (${o.provider}; API key from ${o.keySource})`):b(`voice transcription: not ready \u2014 ${o.reason}`)}async function aT(e){if(e.includes("--help")||e.includes("-h")){b(R_);return}let t=new Set(["--dry-run"]);if(e.filter(i=>!t.has(i)).length){ee("voice-setup: unsupported command-line option or argument"),ee("The provider key is never accepted as a CLI argument. Run `ours-mcp voice-setup --help`."),process.exitCode=1;return}let n=cn()!==null,o=await Nt(re),s=await T_({configFile:So(),env:process.env,dryRun:e.includes("--dry-run"),daemonState:n?"managed":o?"external":"stopped",apply:async()=>{let i=on(process.execPath,[Wt,"restart"],{stdio:"inherit"});if(i.error||i.status!==0)return{ok:!1};let a=on(process.execPath,[Wt,"voice-status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(a.error||a.status!==0)return{ok:!1};try{return{ok:JSON.parse(a.stdout||"{}").ready===!0}}catch{return{ok:!1}}}});s!==0&&(process.exitCode=s)}function Vu(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Hu(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function cT(e){let t=Hu(e,"--name"),r=Vu(e,"--force-bind","--no-force-bind"),n=Vu(e,"--local-book","--no-local-book"),o=Vu(e,"--auto-accept-local","--no-auto-accept-local"),s=e.includes("--overwrite"),i=e.includes("--print"),a=Hu(e,"--path")??Hu(e,"--dir")??process.cwd(),c=t!==void 0||r.set||n.set||o.set||i,u;if(c?((!t||!t.trim())&&(ee("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),u={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:o.value??!0}):u=await uT(),i){b(JSON.stringify(Hs(u),null,2));return}let l=ju(a);if(!s&&V.existsSync(l)){c&&(ee(`define-local-identity-file: ${l} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let p=Qs({input:process.stdin,output:process.stdout}),m=!1;try{let h=(await p.question(`
85
+ ${l} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();m=h==="y"||h==="yes"}finally{p.close()}if(!m){b("aborted \u2014 nothing written.");return}}let d=i_(a,u,!0);b(""),b(`wrote ${d}:`),b(JSON.stringify(Hs(u),null,2))}async function uT(){b("ours-mcp define-local-identity-file \u2014 interactive"),b(`Answer the prompts; the result is written to ${$t(process.cwd(),Fs)}.`),b("");let e=Qs({input:process.stdin,output:process.stdout});try{let t=async(i,a)=>{let c=a?"Y/n":"y/N",u=(await e.question(` ${i} [${c}]: `)).trim().toLowerCase();return u===""?a:u==="y"||u==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||b(" (name is required)");let n=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),o=await t("Add to the host-local contact book?",!0),s=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:n,exposeLocal:o,localAutoAccept:s}}finally{e.close()}}async function lT(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(ee('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await Nt(re)||(ee(`create-root: the daemon is not running on port ${re} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new vr(new URL(`http://127.0.0.1:${re}/mcp`),{requestInit:{headers:an()}}),n=new io({name:"ours-mcp-cli",version:Gt});try{await n.connect(r);let o=await n.callTool({name:"create_root_identity",arguments:{name:t,skip_if_root_exists:!0}}),s=(Array.isArray(o.content)?o.content:[]).map(i=>typeof i.text=="string"?i.text:"").join(" ").split(/\n\nAsk the user\b/)[0].replace(/^create_root_identity failed: /,"").trim();if(o.isError){if(/a root identity already exists/i.test(s)){b(`create-root: ${s.split("\u2014")[0].trim()} \u2014 nothing to do.`);return}ee(`create-root failed: ${s}`),process.exit(1)}b(s)}finally{try{await r.terminateSession()}catch{}try{await n.close()}catch{}}}async function dT(){if(!await Nt(re))return;let e=Number(process.env.OURS_CLIENT_PID),t=Number.isInteger(e)&&e>1?e:process.ppid>1?process.ppid:process.pid,r=(process.env.CLAUDE_CODE_SESSION_ID??"").trim(),n=r||`client:${t}`,o=new vr(new URL(`http://127.0.0.1:${re}/mcp`),{requestInit:{headers:{...an(),"x-ours-lease-token":n,"x-ours-client-pid":String(t)}}}),s=new io({name:"ours-session-end-hook",version:Gt});try{await s.connect(o),await o.terminateSession()}finally{try{await s.close()}catch{}if(r&&/^[A-Za-z0-9._-]{1,200}$/.test(r))try{V.rmSync($t(je,"session-restore",`${r}.json`),{force:!0})}catch{}}}function H_(e,t){t.event==="message_received"?b(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="file_received"?b(`[${e}] new file ${t.filename??"?"} from ${t.from??"?"}`+(t.bytes!==void 0?` (${t.bytes} B)`:"")+(t.file_id!==void 0?` (#${t.file_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="local_contact_request"?b(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"&&b(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`)}function Jt(e){ee(`ours-mcp watch: ${e}`),process.exit(1)}async function pT(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${re}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?q_(n.stateDir):je}}catch{}return null}var fT=e=>`http://127.0.0.1:${re}/identities/${encodeURIComponent(e)}/notifications`;async function M_(e){let t=async o=>{let s=new AbortController,i=setTimeout(()=>s.abort(),35e3),a;try{a=await fetch(`${fT(e)}?since=${o}`,{headers:an(),signal:s.signal})}finally{clearTimeout(i)}if(a.status===401&&Jt(`daemon rejected the API token (401) for identity "${e}". Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode).`),!a.ok)throw new Error(`daemon returned HTTP ${a.status}`);return await a.json()},r=(await t("tip")).cursor??0,n=0;for(;;)try{let o=await t(String(r));if(n=0,Array.isArray(o.events))for(let s of o.events)H_(e,s);typeof o.cursor=="number"&&(r=o.cursor)}catch(o){n=Math.min(n+1e3,5e3),ee(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(o?.message??o)}), retrying\u2026`),await ti(n)}}async function mT(e){if(e){await M_(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${re}/identities`,{headers:an()});if(r.status===401&&Jt("daemon rejected the API token (401). Set OURS_API_TOKEN or run watch as the daemon owner."),r.ok){let n=await r.json();for(let o of n.identities??[]){let s=typeof o?.name=="string"?o.name:void 0;s&&!t.has(s)&&(t.add(s),M_(s))}}}catch{}await ti(3e3)}}var Bu=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function hT(e,t){try{V.readdirSync(e)}catch(i){Jt(`cannot watch \u2014 the daemon API is unreachable AND ${e} is not readable (${i?.code??i}). On a multi-user host, run watch as the daemon owner, or enable the daemon API (start the daemon) so watch can stream over HTTP.`)}if(t)try{V.readdirSync($t(e,t))}catch(i){Jt(`cannot watch identity "${t}" \u2014 ${$t(e,t)} is not readable (${i?.code??i}). Is the daemon running and the name correct?`)}let r=new Map,n=i=>{let a;try{a=V.readdirSync(e,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name)}catch(c){Bu(c)&&Jt(`lost read access to ${e} (${c.code}) \u2014 cannot watch.`);return}for(let c of a){if(t&&c!==t)continue;let u=$t(e,c,"notifications.log"),l;try{l=V.statSync(u).size}catch(m){Bu(m)&&Jt(`cannot read ${u} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}let d=r.get(u);if(d===void 0&&(d=i?l:0,r.set(u,d),i))continue;if(l<=d){l<d&&r.set(u,l);continue}let p;try{let m=V.openSync(u,"r"),h=Buffer.alloc(l-d);V.readSync(m,h,0,h.length,d),V.closeSync(m),p=h.toString("utf8")}catch(m){Bu(m)&&Jt(`cannot read ${u} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}r.set(u,l);for(let m of p.split(`
86
+ `))if(m.trim())try{H_(c,JSON.parse(m))}catch{}}};ee(`ours-mcp watch: daemon API unreachable \u2014 falling back to file poll of ${e} (Ctrl-C to stop)`),n(!0);let o=setInterval(()=>n(!1),1e3),s=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}async function gT(){try{let e=await fetch(`http://127.0.0.1:${re}/identities`,{headers:an()});return e.status===401&&Jt("daemon rejected the API token (401). Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode)."),e.status===404?"file":e.ok?"api":"file"}catch{return"file"}}async function _T(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await pT()!==null&&await gT()==="api"){ee(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${re} (Ctrl-C to stop)`),await mT(e);return}hT(je,e)}var ko="ours.service",B_="solutions.adaptframework.ours";function K_(){return $t(Z_(),".config","systemd","user",ko)}function J_(){return $t(Z_(),"Library","LaunchAgents",`${B_}.plist`)}function nn(e,t){return on(e,t,{stdio:"inherit"}).status===0}function yT(){let e=K_();V.mkdirSync(Ju(e),{recursive:!0});let t=`[Unit]
87
87
  Description=ours MCP daemon (secure agent-to-agent messaging over ADAPT)
88
88
  After=network-online.target
89
89
  Wants=network-online.target
90
90
 
91
91
  [Service]
92
92
  Type=simple
93
- ExecStart=${process.execPath} ${Jt} serve
93
+ ExecStart=${process.execPath} ${Wt} serve
94
94
  Environment=OURS_TRANSPORT=http
95
- Environment=OURS_PORT=${se}
95
+ Environment=OURS_PORT=${re}
96
96
  Environment=OURS_BROKER_URL=${sn}
97
- Environment=OURS_STATE_DIR=${Ze}
97
+ Environment=OURS_STATE_DIR=${je}
98
98
  Restart=on-failure
99
99
  RestartSec=2
100
100
 
101
101
  [Install]
102
102
  WantedBy=default.target
103
- `;H.writeFileSync(e,t),b(`wrote ${e}`),nn("systemctl",["--user","daemon-reload"]),nn("systemctl",["--user","enable","--now",So])||(ee("failed to enable/start the service via systemctl --user."),process.env.XDG_RUNTIME_DIR||(ee(`hint: no user runtime dir \u2014 enable linger: sudo loginctl enable-linger ${Fu().username}`),ee(" (if linger is already on: export XDG_RUNTIME_DIR=/run/user/$(id -u))")),process.exit(1)),nn("loginctl",["enable-linger",Fu().username])||(ee("warning: could not enable linger \u2014 the daemon may not start until you log in."),ee(` run manually: loginctl enable-linger ${Fu().username}`)),b(""),b("ours-mcp installed as a systemd user service and started."),b(` status: systemctl --user status ${So}`),b(` logs: journalctl --user -u ${So} -f`),b(" remove: ours-mcp uninstall-service")}function yP(){nn("systemctl",["--user","disable","--now",So]);let e=K_();try{H.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(t){ee(`failed to remove ${e}: ${String(t)}`)}nn("systemctl",["--user","daemon-reload"]),b("ours-mcp service uninstalled.")}function vP(){let e=J_();H.mkdirSync(Ju(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
103
+ `;V.writeFileSync(e,t),b(`wrote ${e}`),nn("systemctl",["--user","daemon-reload"]),nn("systemctl",["--user","enable","--now",ko])||(ee("failed to enable/start the service via systemctl --user."),process.env.XDG_RUNTIME_DIR||(ee(`hint: no user runtime dir \u2014 enable linger: sudo loginctl enable-linger ${Fu().username}`),ee(" (if linger is already on: export XDG_RUNTIME_DIR=/run/user/$(id -u))")),process.exit(1)),nn("loginctl",["enable-linger",Fu().username])||(ee("warning: could not enable linger \u2014 the daemon may not start until you log in."),ee(` run manually: loginctl enable-linger ${Fu().username}`)),b(""),b("ours-mcp installed as a systemd user service and started."),b(` status: systemctl --user status ${ko}`),b(` logs: journalctl --user -u ${ko} -f`),b(" remove: ours-mcp uninstall-service")}function vT(){nn("systemctl",["--user","disable","--now",ko]);let e=K_();try{V.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(t){ee(`failed to remove ${e}: ${String(t)}`)}nn("systemctl",["--user","daemon-reload"]),b("ours-mcp service uninstalled.")}function bT(){let e=J_();V.mkdirSync(Ju(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
104
104
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
105
105
  <plist version="1.0">
106
106
  <dict>
@@ -108,21 +108,21 @@ WantedBy=default.target
108
108
  <key>ProgramArguments</key>
109
109
  <array>
110
110
  <string>${process.execPath}</string>
111
- <string>${Jt}</string>
111
+ <string>${Wt}</string>
112
112
  <string>serve</string>
113
113
  </array>
114
114
  <key>EnvironmentVariables</key>
115
115
  <dict>
116
116
  <key>OURS_TRANSPORT</key><string>http</string>
117
- <key>OURS_PORT</key><string>${se}</string>
117
+ <key>OURS_PORT</key><string>${re}</string>
118
118
  <key>OURS_BROKER_URL</key><string>${sn}</string>
119
- <key>OURS_STATE_DIR</key><string>${Ze}</string>
119
+ <key>OURS_STATE_DIR</key><string>${je}</string>
120
120
  </dict>
121
121
  <key>RunAtLoad</key><true/>
122
122
  <key>KeepAlive</key><true/>
123
- <key>StandardOutPath</key><string>${vr}</string>
124
- <key>StandardErrorPath</key><string>${vr}</string>
123
+ <key>StandardOutPath</key><string>${wr}</string>
124
+ <key>StandardErrorPath</key><string>${wr}</string>
125
125
  </dict>
126
126
  </plist>
127
- `;H.writeFileSync(e,t),b(`wrote ${e}`);let r=`gui/${process.getuid()}`;on("launchctl",["bootout",r,e],{stdio:"ignore"}),nn("launchctl",["bootstrap",r,e])||(ee("failed to load the launchd agent."),process.exit(1)),b(""),b("ours-mcp installed as a launchd agent and started."),b(" remove: ours-mcp uninstall-service")}function bP(){let e=J_(),t=`gui/${process.getuid()}`;on("launchctl",["bootout",t,e],{stdio:"ignore"});try{H.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(r){ee(`failed to remove ${e}: ${String(r)}`)}b("ours-mcp service uninstalled.")}async function wP(){if(await ei(),process.platform==="linux")return _P();if(process.platform==="darwin")return vP();ee(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function $P(){if(process.platform==="linux")return yP();if(process.platform==="darwin")return bP();ee(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function U_(){b("ours-mcp \u2014 daemon for the ours MCP server"),b(""),b("Usage: ours-mcp <command>"),b(" start start in the background; show structured progress until ready"),b(" stop stop the running daemon"),b(" restart stop then start; healthy slow restores may take up to 3 minutes"),b(" status show whether the daemon is running (incl. CLI + running-daemon version)"),b(" version print the CLI version and the running daemon version (GET /version)"),b(" setup interactively edit the config file (broker / port / state dir / gc)"),b(" voice-setup [--dry-run] securely choose a provider and configure its hidden API key"),b(" voice-status [--json] check voice-transcription readiness (never prints the API key)"),b(" serve run in the foreground (used by start; handy for debugging)"),b(" watch [identity] stream one line per new inbound message (wake source for a Monitor)"),b(" proxy per-session stdio shim \u2192 daemon (stable binding; for the MCP client config)"),b(""),b(' create-root "<name>" create THE root human identity (one per host) via the running'),b(" daemon \u2014 quiet no-op if a root already exists (installer seam)"),b(""),b(" define-local-identity-file write a .ours-identity workspace pin"),b(" interactive (default): 4-question survey, writes to CWD"),b(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),b(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),b(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),b(""),b(" install-service install + start a boot-persistent service (systemd/launchd)"),b(" uninstall-service stop + remove that service"),b(""),b("Config precedence (per field): env var > config.json > default."),b(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),b(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000), OURS_AUTOSTART (off)"),b("(install-service bakes the resolved config values into the service definition.)")}async function SP(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),H.mkdirSync(Ze,{recursive:!0}),H.writeFileSync(wr,String(process.pid));{let t=()=>{try{H.rmSync(wr,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(YT(Ct(Ju(Jt),"index.js")).href);break;case"start":await j_();break;case"stop":await ei();break;case"restart":await ei(),await j_();break;case"status":await nP();break;case"version":case"--version":case"-v":await oP();break;case"setup":await sP();break;case"voice-status":case"stt-status":iP(process.argv.slice(3));break;case"voice-setup":case"stt-setup":await aP(process.argv.slice(3));break;case"create-root":await lP(process.argv.slice(3));break;case"define-local-identity-file":await cP(process.argv.slice(3));break;case"watch":await gP(process.argv[3]);break;case"proxy":!$t.autoStart&&!await Gt(se)&&(ee(`ours-mcp daemon is not running on port ${se} \u2014 start it with \`ours-mcp start\`.`),ee("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1)),await g_({url:`http://127.0.0.1:${se}/mcp`,ensureDaemon:$t.autoStart?rP:void 0,stateDir:Ze,apiToken:Nu($t,{generate:!1})?.token});break;case"install-service":await wP();break;case"uninstall-service":$P();break;case"help":case"--help":case"-h":U_();break;default:ee(`unknown command: ${e}
128
- `),U_(),process.exit(1)}}SP().catch(e=>{ee(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});
127
+ `;V.writeFileSync(e,t),b(`wrote ${e}`);let r=`gui/${process.getuid()}`;on("launchctl",["bootout",r,e],{stdio:"ignore"}),nn("launchctl",["bootstrap",r,e])||(ee("failed to load the launchd agent."),process.exit(1)),b(""),b("ours-mcp installed as a launchd agent and started."),b(" remove: ours-mcp uninstall-service")}function wT(){let e=J_(),t=`gui/${process.getuid()}`;on("launchctl",["bootout",t,e],{stdio:"ignore"});try{V.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(r){ee(`failed to remove ${e}: ${String(r)}`)}b("ours-mcp service uninstalled.")}async function $T(){if(await ei(),process.platform==="linux")return yT();if(process.platform==="darwin")return bT();ee(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function ST(){if(process.platform==="linux")return vT();if(process.platform==="darwin")return wT();ee(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function U_(){b("ours-mcp \u2014 daemon for the ours MCP server"),b(""),b("Usage: ours-mcp <command>"),b(" start start in the background; show structured progress until ready"),b(" stop stop the running daemon"),b(" restart stop then start; healthy slow restores may take up to 3 minutes"),b(" status show whether the daemon is running (incl. CLI + running-daemon version)"),b(" version print the CLI version and the running daemon version (GET /version)"),b(" setup interactively edit the config file (broker / port / state dir / gc)"),b(" voice-setup [--dry-run] securely choose a provider and configure its hidden API key"),b(" voice-status [--json] check voice-transcription readiness (never prints the API key)"),b(" serve run in the foreground (used by start; handy for debugging)"),b(" watch [identity] stream one line per new inbound message (wake source for a Monitor)"),b(" proxy per-session stdio shim \u2192 daemon (stable binding; for the MCP client config)"),b(" session-end internal harness hook: deterministically release this session lease"),b(""),b(' create-root "<name>" create THE root human identity (one per host) via the running'),b(" daemon \u2014 quiet no-op if a root already exists (installer seam)"),b(""),b(" define-local-identity-file write a .ours-identity workspace pin"),b(" interactive (default): 4-question survey, writes to CWD"),b(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),b(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),b(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),b(""),b(" install-service install + start a boot-persistent service (systemd/launchd)"),b(" uninstall-service stop + remove that service"),b(""),b("Config precedence (per field): env var > config.json > default."),b(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),b(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000), OURS_AUTOSTART (off)"),b("(install-service bakes the resolved config values into the service definition.)")}async function xT(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),V.mkdirSync(je,{recursive:!0}),V.writeFileSync($r,String(process.pid));{let t=()=>{try{V.rmSync($r,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(YP($t(Ju(Wt),"index.js")).href);break;case"start":await j_();break;case"stop":await ei();break;case"restart":await ei(),await j_();break;case"status":await nT();break;case"version":case"--version":case"-v":await oT();break;case"setup":await sT();break;case"voice-status":case"stt-status":iT(process.argv.slice(3));break;case"voice-setup":case"stt-setup":await aT(process.argv.slice(3));break;case"create-root":await lT(process.argv.slice(3));break;case"session-end":await dT();break;case"define-local-identity-file":await cT(process.argv.slice(3));break;case"watch":await _T(process.argv[3]);break;case"proxy":!St.autoStart&&!await Nt(re)&&(ee(`ours-mcp daemon is not running on port ${re} \u2014 start it with \`ours-mcp start\`.`),ee("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1)),await g_({url:`http://127.0.0.1:${re}/mcp`,ensureDaemon:St.autoStart?rT:void 0,stateDir:je,apiToken:Nu(St,{generate:!1})?.token});break;case"install-service":await $T();break;case"uninstall-service":ST();break;case"help":case"--help":case"-h":U_();break;default:ee(`unknown command: ${e}
128
+ `),U_(),process.exit(1)}}xT().catch(e=>{ee(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});